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 // make grid ref available in get() to set totalCount, if known.
223 // this allows us disable the 'next' paging button correctly
224 grid.dataProvider.grid = grid;
226 grid.dataProvider.columnsProvider = grid.columnsProvider;
228 $scope.itemFieldValue = grid.dataProvider.itemFieldValue;
229 $scope.indexValue = function(item) {
230 return grid.indexValue(item)
233 grid.applyControlFunctions();
235 grid.loadConfig().then(function() {
236 // link columns to scope after loadConfig(), since it
237 // replaces the columns array.
238 $scope.columns = grid.columnsProvider.columns;
241 // NOTE: grid.collect() is first called from link(), not here.
244 // link our control functions into the gridControls
245 // scope object so the caller can access them.
246 grid.applyControlFunctions = function() {
248 // we use some of these controls internally, so sett
249 // them up even if the caller doesn't request them.
250 var controls = $scope.gridControls || {};
252 controls.columnMap = function() {
254 angular.forEach(grid.columnsProvider.columns, function (c) {
260 controls.columnsProvider = function() {
261 return grid.columnsProvider;
264 // link in the control functions
265 controls.selectedItems = function() {
266 return grid.getSelectedItems()
269 controls.allItems = function() {
273 controls.selectItems = function(ids) {
275 $scope.selected = {};
276 angular.forEach(ids, function(i) {
277 $scope.selected[''+i] = true;
281 // if the caller provided a functional setQuery,
282 // extract the value before replacing it
283 if (controls.setQuery) {
284 grid.dataProvider.query =
288 controls.setQuery = function(query) {
289 grid.dataProvider.query = query;
293 if (controls.watchQuery) {
294 // capture the initial query value
295 grid.dataProvider.query = controls.watchQuery();
298 $scope.gridWatchQuery = controls.watchQuery;
299 $scope.$watch('gridWatchQuery()', function(newv) {
300 controls.setQuery(newv);
304 // if the caller provided a functional setSort
305 // extract the value before replacing it
306 grid.dataProvider.sort =
307 controls.setSort ? controls.setSort() : [];
309 controls.setSort = function(sort) {
313 controls.refresh = function(noReset) {
314 if (!noReset) grid.offset = 0;
318 controls.setLimit = function(limit,forget) {
319 if (!forget && grid.persistKey)
320 egCore.hatch.setLocalItem('eg.grid.' + grid.persistKey + '.limit', limit);
323 controls.getLimit = function() {
326 controls.setOffset = function(offset) {
327 grid.offset = offset;
329 controls.getOffset = function() {
333 controls.saveConfig = function () {
334 return $scope.saveConfig();
337 grid.dataProvider.refresh = controls.refresh;
338 grid.controls = controls;
341 // If a menu item provides its own HTML template, translate it,
342 // using the menu item for the template scope.
343 // note: $sce is required to avoid security restrictions and
344 // is OK here, since the template comes directly from a
345 // local HTML template (not user input).
346 $scope.translateMenuItemTemplate = function(item) {
347 var html = egCore.strings.$replace(item.template, {item : item});
348 return $sce.trustAsHtml(html);
351 // add a new (global) grid menu item
352 grid.addMenuItem = function(item) {
353 $scope.menuItems.push(item);
354 var handler = item.handler;
355 item.handler = function() {
356 $scope.gridMenuIsOpen = false; // close menu
359 item.handlerData, grid.getSelectedItems());
364 // add a selected-items action
365 grid.addAction = function(act) {
367 $scope.actionGroups.forEach(function(g){
368 if (g.label === act.group) {
374 $scope.actionGroups.push({
381 // remove the stored column configuration preferenc, then recover
382 // the column visibility information from the initial page load.
383 $scope.resetColumns = function() {
384 $scope.gridColumnPickerIsOpen = false;
385 egCore.hatch.removeItem('eg.grid.' + grid.persistKey)
387 grid.columnsProvider.reset();
388 if (grid.selfManagedData) grid.collect();
392 $scope.showAllColumns = function() {
393 $scope.gridColumnPickerIsOpen = false;
394 grid.columnsProvider.showAllColumns();
395 if (grid.selfManagedData) grid.collect();
398 $scope.hideAllColumns = function() {
399 $scope.gridColumnPickerIsOpen = false;
400 grid.columnsProvider.hideAllColumns();
401 // note: no need to fetch new data if no columns are visible
404 $scope.toggleColumnVisibility = function(col) {
405 $scope.gridColumnPickerIsOpen = false;
406 col.visible = !col.visible;
408 // egGridFlatDataProvider only retrieves data to be
409 // displayed. When column visibility changes, it's
410 // necessary to fetch the newly visible column data.
411 if (grid.selfManagedData) grid.collect();
414 // save the columns configuration (position, sort, width) to
415 // eg.grid.<persist-key>
416 $scope.saveConfig = function() {
417 $scope.gridColumnPickerIsOpen = false;
419 if (!grid.persistKey) {
421 "Cannot save settings without a grid persist-key");
425 // only store information about visible columns.
426 var conf = grid.columnsProvider.columns.filter(
427 function(col) {return Boolean(col.visible) });
429 // now scrunch the data down to just the needed info
430 conf = conf.map(function(col) {
431 var c = {name : col.name}
432 // Apart from the name, only store non-default values.
433 // No need to store col.visible, since that's implicit
434 if (col.align != 'left') c.align = col.align;
435 if (col.flex != 2) c.flex = col.flex;
436 if (Number(col.sort)) c.sort = Number(c.sort);
440 egCore.hatch.setItem('eg.grid.' + grid.persistKey, conf)
442 // Save operation performed from the grid configuration UI.
443 // Hide the configuration UI and re-draw w/ sort applied
444 if ($scope.showGridConf)
445 $scope.toggleConfDisplay();
450 // load the columns configuration (position, sort, width) from
451 // eg.grid.<persist-key> and apply the loaded settings to the
452 // columns on our columnsProvider
453 grid.loadConfig = function() {
454 if (!grid.persistKey) return $q.when();
456 return egCore.hatch.getItem('eg.grid.' + grid.persistKey)
457 .then(function(conf) {
460 var columns = grid.columnsProvider.columns;
463 angular.forEach(conf, function(col) {
464 var grid_col = columns.filter(
465 function(c) {return c.name == col.name})[0];
468 // saved column does not match a column in the
469 // current grid. skip it.
473 grid_col.align = col.align || 'left';
474 grid_col.flex = col.flex || 2;
475 grid_col.sort = col.sort || 0;
476 // all saved columns are assumed to be true
477 grid_col.visible = true;
479 .filter(function (c) {
480 return c.name == grid_col.name;
483 new_cols.push(grid_col);
486 // columns which are not expressed within the saved
487 // configuration are marked as non-visible and
488 // appended to the end of the new list of columns.
489 angular.forEach(columns, function(col) {
490 var found = conf.filter(
491 function(c) {return (c.name == col.name)})[0];
498 grid.columnsProvider.columns = new_cols;
504 $scope.onContextMenu = function($event) {
505 var col = angular.element($event.target).attr('column');
506 console.log('selected column ' + col);
509 $scope.page = function() {
510 return (grid.offset / grid.limit) + 1;
513 $scope.goToPage = function(page) {
515 if (angular.isNumber(page) && page > 0) {
516 grid.offset = (page - 1) * grid.limit;
521 $scope.offset = function(o) {
522 if (angular.isNumber(o))
527 $scope.limit = function(l) {
528 if (angular.isNumber(l)) {
530 egCore.hatch.setLocalItem('eg.grid.' + grid.persistKey + '.limit', l);
536 $scope.onFirstPage = function() {
537 return grid.offset == 0;
540 $scope.hasNextPage = function() {
541 // we have less data than requested, there must
542 // not be any more pages
543 if (grid.count() < grid.limit) return false;
545 // if the total count is not known, assume that a full
546 // page of data implies more pages are available.
547 if (grid.totalCount == -1) return true;
549 // we have a full page of data, but is there more?
550 return grid.totalCount > (grid.offset + grid.count());
553 $scope.incrementPage = function() {
554 grid.offset += grid.limit;
558 $scope.decrementPage = function() {
559 if (grid.offset < grid.limit) {
562 grid.offset -= grid.limit;
567 // number of items loaded for the current page of results
568 grid.count = function() {
569 return $scope.items.length;
572 // returns the unique identifier value for the provided item
573 // for internal consistency, indexValue is always coerced
575 grid.indexValue = function(item) {
576 if (angular.isObject(item)) {
578 if (angular.isFunction(item[grid.indexField]))
579 return ''+item[grid.indexField]();
580 return ''+item[grid.indexField]; // flat data
583 // passed a non-object; assume it's an index
587 // fires the hide handler function for a context action
588 $scope.actionHide = function(action) {
589 if (typeof action.hide == 'undefined') {
592 if (angular.isFunction(action.hide))
593 return action.hide(action);
597 // fires the disable handler function for a context action
598 $scope.actionDisable = function(action) {
599 if (typeof action.disabled == 'undefined') {
602 if (angular.isFunction(action.disabled))
603 return action.disabled(action);
604 return action.disabled;
607 // fires the action handler function for a context action
608 $scope.actionLauncher = function(action) {
609 if (!action.handler) {
611 'No handler specified for "' + action.label + '"');
615 action.handler(grid.getSelectedItems());
617 console.error('Error executing handler for "'
618 + action.label + '" => ' + E + "\n" + E.stack);
621 if ($scope.action_context_showing) $scope.hideActionContextMenu();
626 $scope.hideActionContextMenu = function () {
627 $($scope.menu_dom).css({
629 width: $scope.action_context_width,
630 top: $scope.action_context_y,
631 left: $scope.action_context_x
633 $($scope.action_context_parent).append($scope.menu_dom);
634 $scope.action_context_oldy = $scope.action_context_oldx = 0;
635 $('body').unbind('click.remove_context_menu_'+$scope.action_context_index);
636 $scope.action_context_showing = false;
639 $scope.action_context_showing = false;
640 $scope.showActionContextMenu = function ($event) {
642 // Have to gather these here, instead of inside link()
643 if (!$scope.menu_dom) $scope.menu_dom = $($scope.grid_element).find('.grid-action-dropdown')[0];
644 if (!$scope.action_context_parent) $scope.action_context_parent = $($scope.menu_dom).parent();
646 if (!grid.getSelectedItems().length) // Nothing selected, fire the click event
647 $event.target.click();
649 if (!$scope.action_context_showing) {
650 $scope.action_context_width = $($scope.menu_dom).css('width');
651 $scope.action_context_y = $($scope.menu_dom).css('top');
652 $scope.action_context_x = $($scope.menu_dom).css('left');
653 $scope.action_context_showing = true;
654 $scope.action_context_index = Math.floor((Math.random() * 1000) + 1);
656 $('body').append($($scope.menu_dom));
657 $('body').bind('click.remove_context_menu_'+$scope.action_context_index, $scope.hideActionContextMenu);
660 $($scope.menu_dom).css({
662 width: $scope.action_context_width,
670 // returns the list of selected item objects
671 grid.getSelectedItems = function() {
672 return $scope.items.filter(
674 return Boolean($scope.selected[grid.indexValue(item)]);
679 grid.getItemByIndex = function(index) {
680 for (var i = 0; i < $scope.items.length; i++) {
681 var item = $scope.items[i];
682 if (grid.indexValue(item) == index)
687 // selects one row after deselecting all of the others
688 grid.selectOneItem = function(index) {
689 $scope.selected = {};
690 $scope.selected[index] = true;
693 // selects or deselects an item, without affecting the others.
694 // returns true if the item is selected; false if de-selected.
695 // we overwrite the object so that we can watch $scope.selected
696 grid.toggleSelectOneItem = function(index) {
697 if ($scope.selected[index]) {
698 delete $scope.selected[index];
699 $scope.selected = angular.copy($scope.selected);
702 $scope.selected[index] = true;
703 $scope.selected = angular.copy($scope.selected);
708 $scope.updateSelected = function () {
709 return $scope.selected = angular.copy($scope.selected);
712 grid.selectAllItems = function() {
713 angular.forEach($scope.items, function(item) {
714 $scope.selected[grid.indexValue(item)] = true
716 $scope.selected = angular.copy($scope.selected);
719 $scope.$watch('selectAll', function(newVal) {
721 grid.selectAllItems();
723 $scope.selected = {};
727 if ($scope.onSelect) {
728 $scope.$watch('selected', function(newVal) {
729 $scope.onSelect(grid.getSelectedItems());
730 if ($scope.afterSelect) $scope.afterSelect();
734 // returns true if item1 appears in the list before item2;
735 // false otherwise. this is slightly more efficient that
736 // finding the position of each then comparing them.
737 // item1 / item2 may be an item or an item index
738 grid.itemComesBefore = function(itemOrIndex1, itemOrIndex2) {
739 var idx1 = grid.indexValue(itemOrIndex1);
740 var idx2 = grid.indexValue(itemOrIndex2);
742 // use for() for early exit
743 for (var i = 0; i < $scope.items.length; i++) {
744 var idx = grid.indexValue($scope.items[i]);
745 if (idx == idx1) return true;
746 if (idx == idx2) return false;
751 // 0-based position of item in the current data set
752 grid.indexOf = function(item) {
753 var idx = grid.indexValue(item);
754 for (var i = 0; i < $scope.items.length; i++) {
755 if (grid.indexValue($scope.items[i]) == idx)
761 grid.modifyColumnFlex = function(column, val) {
763 // prevent flex:0; use hiding instead
767 $scope.modifyColumnFlex = function(col, val) {
768 $scope.lastModColumn = col.name;
769 grid.modifyColumnFlex(col, val);
772 grid.modifyColumnPos = function(col, diff) {
773 var srcIdx, targetIdx;
774 angular.forEach(grid.columnsProvider.columns,
775 function(c, i) { if (c.name == col.name) srcIdx = i });
777 targetIdx = srcIdx + diff;
780 } else if (targetIdx >= grid.columnsProvider.columns.length) {
781 // Target index follows the last visible column.
783 angular.forEach(grid.columnsProvider.columns,
784 function(column, idx) {
785 if (column.visible) lastVisible = idx;
789 // When moving a column (down) causes one or more
790 // visible columns to shuffle forward, our column
791 // moves into the slot of the last visible column.
792 // Otherwise, put it into the slot directly following
793 // the last visible column.
795 srcIdx <= lastVisible ? lastVisible : 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 $scope.showColumnDialog = function() {
1092 return $uibModal.open({
1093 templateUrl: './share/t_grid_columns',
1096 controller: ['$scope', '$uibModalInstance',
1097 function($dialogScope, $uibModalInstance) {
1098 $dialogScope.modifyColumnPos = $scope.modifyColumnPos;
1099 $dialogScope.disableMultiSort = $scope.disableMultiSort;
1100 $dialogScope.columns = $scope.columns;
1102 // Push visible columns to the top of the list
1103 $dialogScope.elevateVisible = function() {
1105 angular.forEach($dialogScope.columns, function(col) {
1106 if (col.visible) new_cols.push(col);
1108 angular.forEach($dialogScope.columns, function(col) {
1109 if (!col.visible) new_cols.push(col);
1112 // Update all references to the list of columns
1113 $dialogScope.columns =
1115 grid.columnsProvider.columns =
1119 $dialogScope.toggle = function(col) {
1120 col.visible = !Boolean(col.visible);
1122 $dialogScope.ok = $dialogScope.cancel = function() {
1123 delete $scope.lastModColumn;
1124 $uibModalInstance.close()
1131 // generates CSV for the currently visible grid contents
1132 grid.generateCSV = function() {
1133 return grid.getAllItemsAsText().then(function(text_items) {
1134 var columns = text_items.columns;
1135 var items = text_items.items;
1139 angular.forEach(columns, function(col) {
1140 csvStr += grid.csvDatum(col.label);
1144 csvStr = csvStr.replace(/,$/,'\n');
1147 angular.forEach(items, function(item) {
1148 angular.forEach(columns, function(col) {
1149 csvStr += grid.csvDatum(item[col.name]);
1152 csvStr = csvStr.replace(/,$/,'\n');
1159 // Interpolate the value for column.linkpath within the context
1160 // of the row item to generate the final link URL.
1161 $scope.generateLinkPath = function(col, item) {
1162 return egCore.strings.$replace(col.linkpath, {item : item});
1165 // If a column provides its own HTML template, translate it,
1166 // using the current item for the template scope.
1167 // note: $sce is required to avoid security restrictions and
1168 // is OK here, since the template comes directly from a
1169 // local HTML template (not user input).
1170 $scope.translateCellTemplate = function(col, item) {
1171 var html = egCore.strings.$replace(col.template, {item : item});
1172 return $sce.trustAsHtml(html);
1175 $scope.collect = function() { grid.collect() }
1177 // asks the dataProvider for a page of data
1178 grid.collect = function() {
1180 // avoid firing the collect if there is nothing to collect.
1181 if (grid.selfManagedData && !grid.dataProvider.query) return;
1183 if (grid.collecting) return; // avoid parallel collect()
1184 grid.collecting = true;
1186 console.debug('egGrid.collect() offset='
1187 + grid.offset + '; limit=' + grid.limit);
1189 // ensure all of our dropdowns are closed
1190 // TODO: git rid of these and just use dropdown-toggle,
1191 // which is more reliable.
1192 $scope.gridColumnPickerIsOpen = false;
1193 $scope.gridRowCountIsOpen = false;
1194 $scope.gridPageSelectIsOpen = false;
1197 $scope.selected = {};
1199 // Inform the caller we've asked the data provider
1200 // for data. This is useful for knowing when collection
1201 // has started (e.g. to display a progress dialg) when
1202 // using the stock (flattener) data provider, where the
1203 // user is not directly defining a get() handler.
1204 if (grid.controls.collectStarted)
1205 grid.controls.collectStarted(grid.offset, grid.limit);
1207 grid.dataProvider.get(grid.offset, grid.limit).then(
1209 if (grid.controls.allItemsRetrieved)
1210 grid.controls.allItemsRetrieved();
1215 $scope.items.push(item)
1216 if (grid.controls.itemRetrieved)
1217 grid.controls.itemRetrieved(item);
1218 if ($scope.selectAll)
1219 $scope.selected[grid.indexValue(item)] = true
1221 }).finally(function() {
1222 console.debug('egGrid.collect() complete');
1223 grid.collecting = false
1224 $scope.selected = angular.copy($scope.selected);
1234 * eg-grid-field : used for collecting custom field data from the templates.
1235 * This directive does not direct display, it just passes data up to the
1238 .directive('egGridField', function() {
1240 require : '^egGrid',
1243 flesher: '=', // optional; function that can flesh a linked field, given the value
1244 comparator: '=', // optional; function that can sort the thing at the end of 'path'
1245 name : '@', // required; unique name
1246 path : '@', // optional; flesh path
1247 ignore: '@', // optional; fields to ignore when path is a wildcard
1248 label : '@', // optional; display label
1249 flex : '@', // optional; default flex width
1250 align : '@', // optional; default alignment, left/center/right
1251 dateformat : '@', // optional: passed down to egGridValueFilter
1252 datecontext: '@', // optional: passed down to egGridValueFilter to choose TZ
1253 datefilter: '@', // optional: passed down to egGridValueFilter to choose specialized date filters
1254 dateonlyinterval: '@', // optional: passed down to egGridValueFilter to choose a "better" format
1256 // if a field is part of an IDL object, but we are unable to
1257 // determine the class, because it's nested within a hash
1258 // (i.e. we can't navigate directly to the object via the IDL),
1259 // idlClass lets us specify the class. This is particularly
1260 // useful for nested wildcard fields.
1261 parentIdlClass : '@',
1263 // optional: for non-IDL columns, specifying a datatype
1264 // lets the caller control which display filter is used.
1265 // datatype should match the standard IDL datatypes.
1268 // optional hash of functions that can be imported into
1269 // the directive's scope; meant for cases where the "compiled"
1273 link : function(scope, element, attrs, egGridCtrl) {
1275 // boolean fields are presented as value-less attributes
1285 'required' // if set, always fetch data for this column
1288 if (angular.isDefined(attrs[field]))
1289 scope[field] = true;
1293 // any HTML content within the field is its custom template
1294 var tmpl = element.html();
1295 if (tmpl && !tmpl.match(/^\s*$/))
1296 scope.template = tmpl
1298 egGridCtrl.columnsProvider.add(scope);
1305 * eg-grid-action : used for specifying actions which may be applied
1306 * to items within the grid.
1308 .directive('egGridAction', function() {
1310 require : '^egGrid',
1314 group : '@', // Action group, ungrouped if not set
1315 label : '@', // Action label
1316 handler : '=', // Action function handler
1318 disabled : '=', // function
1321 link : function(scope, element, attrs, egGridCtrl) {
1322 egGridCtrl.addAction({
1324 group : scope.group,
1325 label : scope.label,
1326 divider : scope.divider,
1327 handler : scope.handler,
1328 disabled : scope.disabled,
1335 .factory('egGridColumnsProvider', ['egCore', function(egCore) {
1337 function ColumnsProvider(args) {
1340 cols.stockVisible = [];
1341 cols.idlClass = args.idlClass;
1342 cols.clientSort = args.clientSort;
1343 cols.defaultToHidden = args.defaultToHidden;
1344 cols.defaultToNoSort = args.defaultToNoSort;
1345 cols.defaultToNoMultiSort = args.defaultToNoMultiSort;
1346 cols.defaultDateFormat = args.defaultDateFormat;
1347 cols.defaultDateContext = args.defaultDateContext;
1349 // resets column width, visibility, and sort behavior
1350 // Visibility resets to the visibility settings defined in the
1351 // template (i.e. the original egGridField values).
1352 cols.reset = function() {
1353 angular.forEach(cols.columns, function(col) {
1357 if (cols.stockVisible.indexOf(col.name) > -1) {
1360 col.visible = false;
1365 // returns true if any columns are sortable
1366 cols.hasSortableColumn = function() {
1367 return cols.columns.filter(
1369 return col.sortable || col.multisortable;
1374 cols.showAllColumns = function() {
1375 angular.forEach(cols.columns, function(column) {
1376 column.visible = true;
1380 cols.hideAllColumns = function() {
1381 angular.forEach(cols.columns, function(col) {
1386 cols.indexOf = function(name) {
1387 for (var i = 0; i < cols.columns.length; i++) {
1388 if (cols.columns[i].name == name)
1394 cols.findColumn = function(name) {
1395 return cols.columns[cols.indexOf(name)];
1398 cols.compileAutoColumns = function() {
1399 var idl_class = egCore.idl.classes[cols.idlClass];
1404 if (field.virtual) return;
1405 if (field.datatype == 'link' || field.datatype == 'org_unit') {
1406 // if the field is a link and the linked class has a
1407 // "selector" field specified, use the selector field
1408 // as the display field for the columns.
1409 // flattener will take care of the fleshing.
1410 if (field['class']) {
1411 var selector_field = egCore.idl.classes[field['class']].fields
1412 .filter(function(f) { return Boolean(f.selector) })[0];
1413 if (selector_field) {
1414 field.path = field.name + '.' + selector_field.selector;
1418 cols.add(field, true);
1423 // if a column definition has a path with a wildcard, create
1424 // columns for all non-virtual fields at the specified
1425 // position in the path.
1426 cols.expandPath = function(colSpec) {
1428 var ignoreList = [];
1430 ignoreList = colSpec.ignore.split(' ');
1432 var dotpath = colSpec.path.replace(/\.?\*$/,'');
1436 if (colSpec.parentIdlClass) {
1437 class_obj = egCore.idl.classes[colSpec.parentIdlClass];
1439 class_obj = egCore.idl.classes[cols.idlClass];
1441 var idl_parent = class_obj;
1442 var old_field_label = '';
1444 if (!class_obj) return;
1446 //console.debug('egGrid: auto dotpath is: ' + dotpath);
1447 var path_parts = dotpath.split(/\./);
1449 // find the IDL class definition for the last element in the
1450 // path before the .*
1451 // an empty path_parts means expand the root class
1454 for (var path_idx in path_parts) {
1455 old_field = idl_field;
1457 var part = path_parts[path_idx];
1458 idl_field = class_obj.field_map[part];
1460 // unless we're at the end of the list, this field should
1461 // link to another class.
1462 if (idl_field && idl_field['class'] && (
1463 idl_field.datatype == 'link' ||
1464 idl_field.datatype == 'org_unit')) {
1465 if (old_field_label) old_field_label += ' : ';
1466 old_field_label += idl_field.label;
1467 class_obj = egCore.idl.classes[idl_field['class']];
1468 if (old_field) idl_parent = old_field;
1470 if (path_idx < (path_parts.length - 1)) {
1471 // we ran out of classes to hop through before
1472 // we ran out of path components
1473 console.error("egGrid: invalid IDL path: " + dotpath);
1480 angular.forEach(class_obj.fields, function(field) {
1482 // Only show wildcard fields where we have data to show
1483 // Virtual and un-fleshed links will not have any data.
1484 if (field.virtual ||
1485 (field.datatype == 'link' || field.datatype == 'org_unit') ||
1486 ignoreList.indexOf(field.name) > -1
1490 var col = cols.cloneFromScope(colSpec);
1491 col.path = (dotpath ? dotpath + '.' + field.name : field.name);
1493 // log line below is very chatty. disable until needed.
1494 // console.debug('egGrid: field: ' +field.name + '; parent field: ' + js2JSON(idl_parent));
1495 cols.add(col, false, true,
1496 {idl_parent : idl_parent, idl_field : field, idl_class : class_obj, field_parent_label : old_field_label });
1499 cols.columns = cols.columns.sort(
1501 if (a.explicit) return -1;
1502 if (b.explicit) return 1;
1504 if (a.idlclass && b.idlclass) {
1505 if (a.idlclass < b.idlclass) return -1;
1506 if (b.idlclass < a.idlclass) return 1;
1509 if (a.path && b.path && a.path.lastIndexOf('.') && b.path.lastIndexOf('.')) {
1510 if (a.path.substring(0, a.path.lastIndexOf('.')) < b.path.substring(0, b.path.lastIndexOf('.'))) return -1;
1511 if (b.path.substring(0, b.path.lastIndexOf('.')) < a.path.substring(0, a.path.lastIndexOf('.'))) return 1;
1514 if (a.label && b.label) {
1515 if (a.label < b.label) return -1;
1516 if (b.label < a.label) return 1;
1519 return a.name < b.name ? -1 : 1;
1526 "egGrid: wildcard path does not resolve to an object: "
1531 // angular.clone(scopeObject) is not permittable. Manually copy
1532 // the fields over that we need (so the scope object can go away).
1533 cols.cloneFromScope = function(colSpec) {
1535 flesher : colSpec.flesher,
1536 comparator : colSpec.comparator,
1537 name : colSpec.name,
1538 label : colSpec.label,
1539 path : colSpec.path,
1540 align : colSpec.align || 'left',
1541 flex : Number(colSpec.flex) || 2,
1542 sort : Number(colSpec.sort) || 0,
1543 required : colSpec.required,
1544 linkpath : colSpec.linkpath,
1545 template : colSpec.template,
1546 visible : colSpec.visible,
1547 compiled : colSpec.compiled,
1548 handlers : colSpec.handlers,
1549 hidden : colSpec.hidden,
1550 datatype : colSpec.datatype,
1551 sortable : colSpec.sortable,
1552 nonsortable : colSpec.nonsortable,
1553 multisortable : colSpec.multisortable,
1554 nonmultisortable : colSpec.nonmultisortable,
1555 dateformat : colSpec.dateformat,
1556 datecontext : colSpec.datecontext,
1557 datefilter : colSpec.datefilter,
1558 dateonlyinterval : colSpec.dateonlyinterval,
1559 parentIdlClass : colSpec.parentIdlClass
1564 // Add a column to the columns collection.
1565 // Columns may come from a slim eg-columns-field or
1566 // directly from the IDL.
1567 cols.add = function(colSpec, fromIDL, fromExpand, idl_info) {
1569 // First added column with the specified path takes precedence.
1570 // This allows for specific definitions followed by wildcard
1571 // definitions. If a match is found, back out.
1572 if (cols.columns.filter(function(c) {
1573 return (c.path == colSpec.path) })[0]) {
1574 console.debug('skipping pre-existing column ' + colSpec.path);
1578 var column = fromExpand ? colSpec : cols.cloneFromScope(colSpec);
1580 if (column.path && column.path.match(/\*$/))
1581 return cols.expandPath(colSpec);
1583 if (!fromExpand) column.explicit = true;
1585 if (!column.name) column.name = column.path;
1586 if (!column.path) column.path = column.name;
1588 if (column.visible || (!cols.defaultToHidden && !column.hidden))
1589 column.visible = true;
1591 if (column.sortable || (!cols.defaultToNoSort && !column.nonsortable))
1592 column.sortable = true;
1594 if (column.multisortable ||
1595 (!cols.defaultToNoMultiSort && !column.nonmultisortable))
1596 column.multisortable = true;
1598 if (cols.defaultDateFormat && ! column.dateformat) {
1599 column.dateformat = cols.defaultDateFormat;
1602 if (cols.defaultDateOnlyInterval && ! column.dateonlyinterval) {
1603 column.dateonlyinterval = cols.defaultDateOnlyInterval;
1606 if (cols.defaultDateContext && ! column.datecontext) {
1607 column.datecontext = cols.defaultDateContext;
1610 if (cols.defaultDateFilter && ! column.datefilter) {
1611 column.datefilter = cols.defaultDateFilter;
1614 cols.columns.push(column);
1616 // Track which columns are visible by default in case we
1617 // need to reset column visibility
1619 cols.stockVisible.push(column.name);
1621 if (fromIDL) return; // directly from egIDL. nothing left to do.
1623 // lookup the matching IDL field
1624 if (!idl_info && cols.idlClass)
1625 idl_info = cols.idlFieldFromPath(column.path);
1628 // column is not represented within the IDL
1629 column.adhoc = true;
1633 column.datatype = idl_info.idl_field.datatype;
1635 if (!column.label) {
1636 column.label = idl_info.idl_field.label || column.name;
1639 if (fromExpand && idl_info.idl_class) {
1640 column.idlclass = '';
1641 if (idl_info.field_parent_label && idl_info.idl_parent.label != idl_info.idl_class.label) {
1642 column.idlclass = (idl_info.field_parent_label || idl_info.idl_parent.label || idl_info.idl_parent.name);
1644 column.idlclass += idl_info.idl_class.label || idl_info.idl_class.name;
1649 // finds the IDL field from the dotpath, using the columns
1650 // idlClass as the base.
1651 cols.idlFieldFromPath = function(dotpath) {
1652 var class_obj = egCore.idl.classes[cols.idlClass];
1653 if (!dotpath) return null;
1655 var path_parts = dotpath.split(/\./);
1659 for (var path_idx in path_parts) {
1660 var part = path_parts[path_idx];
1661 idl_parent = idl_field;
1662 idl_field = class_obj.field_map[part];
1665 if (idl_field['class'] && (
1666 idl_field.datatype == 'link' ||
1667 idl_field.datatype == 'org_unit')) {
1668 class_obj = egCore.idl.classes[idl_field['class']];
1676 idl_parent: idl_parent,
1677 idl_field : idl_field,
1678 idl_class : class_obj
1684 instance : function(args) { return new ColumnsProvider(args) }
1690 * Generic data provider template class. This is basically an abstract
1691 * class factory service whose instances can be locally modified to
1692 * meet the needs of each individual grid.
1694 .factory('egGridDataProvider',
1695 ['$q','$timeout','$filter','egCore',
1696 function($q , $timeout , $filter , egCore) {
1698 function GridDataProvider(args) {
1699 var gridData = this;
1700 if (!args) args = {};
1703 gridData.get = args.get;
1704 gridData.query = args.query;
1705 gridData.idlClass = args.idlClass;
1706 gridData.columnsProvider = args.columnsProvider;
1708 // Delivers a stream of array data via promise.notify()
1709 // Useful for passing an array of data to egGrid.get()
1710 // If a count is provided, the array will be trimmed to
1711 // the range defined by count and offset
1712 gridData.arrayNotifier = function(arr, offset, count) {
1713 if (!arr || arr.length == 0) return $q.when();
1715 if (gridData.columnsProvider.clientSort
1717 && gridData.sort.length > 0
1719 var sorter_cache = [];
1720 arr.sort(function(a,b) {
1721 for (var si = 0; si < gridData.sort.length; si++) {
1722 if (!sorter_cache[si]) { // Build sort structure on first comparison, reuse thereafter
1723 var field = gridData.sort[si];
1726 if (angular.isObject(field)) {
1727 dir = Object.values(field)[0];
1728 field = Object.keys(field)[0];
1731 var path = gridData.columnsProvider.findColumn(field).path || field;
1732 var comparator = gridData.columnsProvider.findColumn(field).comparator ||
1733 function (x,y) { if (x < y) return -1; if (x > y) return 1; return 0 };
1735 sorter_cache[si] = {
1738 comparator : comparator
1742 var sc = sorter_cache[si];
1746 if (a._isfieldmapper || angular.isFunction(a[sc.field])) {
1747 try {af = a[sc.field](); bf = b[sc.field]() } catch (e) {};
1749 af = a[sc.field]; bf = b[sc.field];
1751 if (af === undefined && sc.field.indexOf('.') > -1) { // assume an object, not flat path
1752 var parts = sc.field.split('.');
1755 angular.forEach(parts, function (p) {
1757 if (af._isfieldmapper || angular.isFunction(af[p])) af = af[p]();
1761 if (bf._isfieldmapper || angular.isFunction(bf[p])) bf = bf[p]();
1767 if (af === undefined) af = null;
1768 if (bf === undefined) bf = null;
1770 if (af === null && bf !== null) return 1;
1771 if (bf === null && af !== null) return -1;
1773 if (!(bf === null && af === null)) {
1774 var partial = sc.comparator(af,bf);
1776 if (sc.dir == 'desc') {
1777 if (partial > 0) return -1;
1789 if (count) arr = arr.slice(offset, offset + count);
1790 var def = $q.defer();
1791 // promise notifications are only witnessed when delivered
1792 // after the caller has his hands on the promise object
1793 $timeout(function() {
1794 angular.forEach(arr, def.notify);
1800 // Calls the grid refresh function. Once instantiated, the
1801 // grid will replace this function with it's own refresh()
1802 gridData.refresh = function(noReset) { }
1804 if (!gridData.get) {
1805 // returns a promise whose notify() delivers items
1806 gridData.get = function(index, count) {
1807 console.error("egGridDataProvider.get() not implemented");
1811 // attempts a flat field lookup first. If the column is not
1812 // found on the top-level object, attempts a nested lookup
1813 // TODO: consider a caching layer to speed up template
1814 // rendering, particularly for nested objects?
1815 gridData.itemFieldValue = function(item, column) {
1817 if (column.name in item) {
1818 if (typeof item[column.name] == 'function') {
1819 val = item[column.name]();
1821 val = item[column.name];
1824 val = gridData.nestedItemFieldValue(item, column);
1830 // TODO: deprecate me
1831 gridData.flatItemFieldValue = function(item, column) {
1832 console.warn('gridData.flatItemFieldValue deprecated; '
1833 + 'leave provider.itemFieldValue unset');
1834 return item[column.name];
1837 // given an object and a dot-separated path to a field,
1838 // extract the value of the field. The path can refer
1839 // to function names or object attributes. If the final
1840 // value is an IDL field, run the value through its
1841 // corresponding output filter.
1842 gridData.nestedItemFieldValue = function(obj, column) {
1843 item = obj; // keep a copy around
1845 if (obj === null || obj === undefined || obj === '') return '';
1846 if (!column.path) return obj;
1849 var parts = column.path.split('.');
1851 angular.forEach(parts, function(step, idx) {
1852 // object is not fleshed to the expected extent
1853 if (typeof obj != 'object') {
1854 if (typeof obj != 'undefined' && column.flesher) {
1855 obj = column.flesher(obj, column, item);
1862 if (!obj) return '';
1864 var cls = obj.classname;
1865 if (cls && (class_obj = egCore.idl.classes[cls])) {
1866 idl_field = class_obj.field_map[step];
1867 obj = obj[step] ? obj[step]() : '';
1869 if (angular.isFunction(obj[step])) {
1877 // We found a nested IDL object which may or may not have
1878 // been configured as a top-level column. Grab the datatype.
1879 if (idl_field && !column.datatype)
1880 column.datatype = idl_field.datatype;
1882 if (obj === null || obj === undefined || obj === '') return '';
1888 instance : function(args) {
1889 return new GridDataProvider(args);
1896 // Factory service for egGridDataManager instances, which are
1897 // responsible for collecting flattened grid data.
1898 .factory('egGridFlatDataProvider',
1899 ['$q','egCore','egGridDataProvider',
1900 function($q , egCore , egGridDataProvider) {
1903 instance : function(args) {
1904 var provider = egGridDataProvider.instance(args);
1906 provider.get = function(offset, count) {
1908 // no query means no call
1909 if (!provider.query ||
1910 angular.equals(provider.query, {}))
1913 // find all of the currently visible columns
1914 var queryFields = {}
1915 angular.forEach(provider.columnsProvider.columns,
1917 // only query IDL-tracked columns
1918 if (!col.adhoc && col.name && col.path && (col.required || col.visible))
1919 queryFields[col.name] = col.path;
1923 return egCore.net.request(
1925 'open-ils.fielder.flattened_search',
1926 egCore.auth.token(), provider.idlClass,
1927 queryFields, provider.query,
1928 { sort : provider.sort,
1934 //provider.itemFieldValue = provider.flatItemFieldValue;
1941 .directive('egGridColumnDragSource', function() {
1944 require : '^egGrid',
1945 link : function(scope, element, attrs, egGridCtrl) {
1946 angular.element(element).attr('draggable', 'true');
1948 element.bind('dragstart', function(e) {
1949 egGridCtrl.dragColumn = attrs.column;
1950 egGridCtrl.dragType = attrs.dragType || 'move'; // or resize
1951 egGridCtrl.colResizeDir = 0;
1953 if (egGridCtrl.dragType == 'move') {
1954 // style the column getting moved
1955 angular.element(e.target).addClass(
1956 'eg-grid-column-move-handle-active');
1960 element.bind('dragend', function(e) {
1961 if (egGridCtrl.dragType == 'move') {
1962 angular.element(e.target).removeClass(
1963 'eg-grid-column-move-handle-active');
1970 .directive('egGridColumnDragDest', function() {
1973 require : '^egGrid',
1974 link : function(scope, element, attrs, egGridCtrl) {
1976 element.bind('dragover', function(e) { // required for drop
1977 e.stopPropagation();
1979 e.dataTransfer.dropEffect = 'move';
1981 if (egGridCtrl.colResizeDir == 0) return; // move
1983 var cols = egGridCtrl.columnsProvider;
1984 var srcCol = egGridCtrl.dragColumn;
1985 var srcColIdx = cols.indexOf(srcCol);
1987 if (egGridCtrl.colResizeDir == -1) {
1988 if (cols.indexOf(attrs.column) <= srcColIdx) {
1989 egGridCtrl.modifyColumnFlex(
1990 egGridCtrl.columnsProvider.findColumn(
1991 egGridCtrl.dragColumn), -1);
1992 if (cols.columns[srcColIdx+1]) {
1993 // source column shrinks by one, column to the
1994 // right grows by one.
1995 egGridCtrl.modifyColumnFlex(
1996 cols.columns[srcColIdx+1], 1);
2001 if (cols.indexOf(attrs.column) > srcColIdx) {
2002 egGridCtrl.modifyColumnFlex(
2003 egGridCtrl.columnsProvider.findColumn(
2004 egGridCtrl.dragColumn), 1);
2005 if (cols.columns[srcColIdx+1]) {
2006 // source column grows by one, column to the
2007 // right grows by one.
2008 egGridCtrl.modifyColumnFlex(
2009 cols.columns[srcColIdx+1], -1);
2017 element.bind('dragenter', function(e) {
2018 e.stopPropagation();
2020 if (egGridCtrl.dragType == 'move') {
2021 angular.element(e.target).addClass('eg-grid-col-hover');
2023 // resize grips are on the right side of each column.
2024 // dragenter will either occur on the source column
2025 // (dragging left) or the column to the right.
2026 if (egGridCtrl.colResizeDir == 0) {
2027 if (egGridCtrl.dragColumn == attrs.column) {
2028 egGridCtrl.colResizeDir = -1; // west
2030 egGridCtrl.colResizeDir = 1; // east
2036 element.bind('dragleave', function(e) {
2037 e.stopPropagation();
2039 if (egGridCtrl.dragType == 'move') {
2040 angular.element(e.target).removeClass('eg-grid-col-hover');
2044 element.bind('drop', function(e) {
2045 e.stopPropagation();
2047 egGridCtrl.colResizeDir = 0;
2048 if (egGridCtrl.dragType == 'move') {
2049 angular.element(e.target).removeClass('eg-grid-col-hover');
2050 egGridCtrl.onColumnDrop(attrs.column); // move the column
2057 .directive('egGridMenuItem', function() {
2060 require : '^egGrid',
2066 handler : '=', // onclick handler function
2067 divider : '=', // if true, show a divider only
2068 handlerData : '=', // if set, passed as second argument to handler
2069 disabled : '=', // function
2070 hidden : '=' // function
2072 link : function(scope, element, attrs, egGridCtrl) {
2073 egGridCtrl.addMenuItem({
2074 checkbox : scope.checkbox,
2075 checked : scope.checked ? true : false,
2076 label : scope.label,
2077 standalone : scope.standalone ? true : false,
2078 handler : scope.handler,
2079 divider : scope.divider,
2080 disabled : scope.disabled,
2081 hidden : scope.hidden,
2082 handlerData : scope.handlerData
2089 /* https://stackoverflow.com/questions/17343696/adding-an-ng-click-event-inside-a-filter/17344875#17344875 */
2090 .directive('compile', ['$compile', function ($compile) {
2091 return function(scope, element, attrs) {
2092 // pass through column defs from grid cell's scope
2093 scope.col = scope.$parent.col;
2096 // watch the 'compile' expression for changes
2097 return scope.$eval(attrs.compile);
2100 // when the 'compile' expression changes
2101 // assign it into the current DOM
2102 element.html(value);
2104 // compile the new DOM and link it to the current
2106 // NOTE: we only compile .childNodes so that
2107 // we don't get into infinite loop compiling ourselves
2108 $compile(element.contents())(scope);
2117 * Translates bare IDL object values into display values.
2118 * 1. Passes dates through the angular date filter
2119 * 2. Translates bools to Booleans so the browser can display translated
2120 * value. (Though we could manually translate instead..)
2121 * Others likely to follow...
2123 .filter('egGridValueFilter', ['$filter','egCore', function($filter,egCore) {
2124 function traversePath(obj,path) {
2125 var list = path.split('.');
2126 for (var part in path) {
2127 if (obj[path]) obj = obj[path]
2133 var GVF = function(value, column, item) {
2134 switch(column.datatype) {
2137 // Browser will translate true/false for us
2139 case '1' : // legacy
2143 case '0' : // legacy
2146 // value may be null, '', etc.
2147 default : return '';
2150 var interval = angular.isFunction(item[column.dateonlyinterval])
2151 ? item[column.dateonlyinterval]()
2152 : item[column.dateonlyinterval];
2154 if (column.dateonlyinterval && !interval) // try it as a dotted path
2155 interval = traversePath(item, column.dateonlyinterval);
2157 var context = angular.isFunction(item[column.datecontext])
2158 ? item[column.datecontext]()
2159 : item[column.datecontext];
2161 if (column.datecontext && !context) // try it as a dotted path
2162 context = traversePath(item, column.datecontext);
2164 var date_filter = column.datefilter || 'egOrgDateInContext';
2166 return $filter(date_filter)(value, column.dateformat, context, interval);
2168 return $filter('currency')(value);
2174 GVF.$stateful = true;