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 // Hash of control functions.
68 // These functions are defined by the calling scope and
69 // invoked as-is by the grid w/ the specified parameters.
71 // collectStarted : function() {}
72 // itemRetrieved : function(item) {}
73 // allItemsRetrieved : function() {}
76 // If defined, the grid will watch the return value from
77 // the function defined at watchQuery on each digest and
78 // re-draw the grid when query changes occur.
80 // watchQuery : function() { /* return grid query */ }
83 // These functions are defined by the grid and thus
84 // replace any values defined for these attributes from the
87 // activateItem : function(item) {}
88 // allItems : function(allItems) {}
89 // selectedItems : function(selected) {}
90 // selectItems : function(ids) {}
91 // setQuery : function(queryStruct) {} // causes reload
92 // setSort : function(sortSturct) {} // causes reload
96 // TODO: avoid hard-coded url
97 templateUrl : '/eg/staff/share/t_autogrid',
99 link : function(scope, element, attrs) {
100 // link() is called after page compilation, which means our
101 // eg-grid-field's have been parsed and loaded. Now it's
102 // safe to perform our initial page load.
104 // load auto fields after eg-grid-field's so they are not clobbered
105 scope.handleAutoFields();
108 scope.grid_element = element;
110 .find('.eg-grid-content-body')
111 .bind('contextmenu', scope.showActionContextMenu);
115 '$scope','$q','egCore','egGridFlatDataProvider','$location',
116 'egGridColumnsProvider','$filter','$window','$sce','$timeout',
117 function($scope, $q , egCore, egGridFlatDataProvider , $location,
118 egGridColumnsProvider , $filter , $window , $sce , $timeout) {
122 grid.init = function() {
125 $scope.showGridConf = false;
126 grid.totalCount = -1;
127 $scope.selected = {};
128 $scope.actionGroups = [{actions:[]}]; // Grouped actions for selected items
129 $scope.menuItems = []; // global actions
131 // returns true if any rows are selected.
132 $scope.hasSelected = function() {
133 return grid.getSelectedItems().length > 0 };
135 var features = ($scope.features) ?
136 $scope.features.split(',') : [];
137 delete $scope.features;
139 $scope.showIndex = (features.indexOf('-index') == -1);
141 $scope.allowAll = (features.indexOf('allowAll') > -1);
142 $scope.startSelected = $scope.selectAll = (features.indexOf('startSelected') > -1);
143 $scope.showActions = (features.indexOf('-actions') == -1);
144 $scope.showPagination = (features.indexOf('-pagination') == -1);
145 $scope.showPicker = (features.indexOf('-picker') == -1);
147 $scope.showMenu = (features.indexOf('-menu') == -1);
149 // remove some unneeded values from the scope to reduce bloat
151 grid.idlClass = $scope.idlClass;
152 delete $scope.idlClass;
154 grid.persistKey = $scope.persistKey;
155 delete $scope.persistKey;
157 var stored_limit = 0;
158 if ($scope.showPagination) {
159 if (grid.persistKey) {
160 var stored_limit = Number(
161 egCore.hatch.getLocalItem('eg.grid.' + grid.persistKey + '.limit')
165 stored_limit = 10000; // maybe support "Inf"?
168 grid.limit = Number(stored_limit) || Number($scope.pageSize) || 25;
170 grid.indexField = $scope.idField;
171 delete $scope.idField;
173 grid.dataProvider = $scope.itemsProvider;
175 if (!grid.indexField && grid.idlClass)
176 grid.indexField = egCore.idl.classes[grid.idlClass].pkey;
178 grid.columnsProvider = egGridColumnsProvider.instance({
179 idlClass : grid.idlClass,
180 defaultToHidden : (features.indexOf('-display') > -1),
181 defaultToNoSort : (features.indexOf('-sort') > -1),
182 defaultToNoMultiSort : (features.indexOf('-multisort') > -1)
184 $scope.canMultiSelect = (features.indexOf('-multiselect') == -1);
186 $scope.handleAutoFields = function() {
187 if ($scope.autoFields) {
188 if (grid.autoLabel) {
190 egCore.idl.classes[grid.idlClass].label;
192 grid.columnsProvider.compileAutoColumns();
193 delete $scope.autoFields;
197 if (!grid.dataProvider) {
198 // no provider, um, provided.
199 // Use a flat data provider
201 grid.selfManagedData = true;
202 grid.dataProvider = egGridFlatDataProvider.instance({
203 indexField : grid.indexField,
204 idlClass : grid.idlClass,
205 columnsProvider : grid.columnsProvider,
210 $scope.itemFieldValue = grid.dataProvider.itemFieldValue;
211 $scope.indexValue = function(item) {
212 return grid.indexValue(item)
215 grid.applyControlFunctions();
217 grid.loadConfig().then(function() {
218 // link columns to scope after loadConfig(), since it
219 // replaces the columns array.
220 $scope.columns = grid.columnsProvider.columns;
223 // NOTE: grid.collect() is first called from link(), not here.
226 // link our control functions into the gridControls
227 // scope object so the caller can access them.
228 grid.applyControlFunctions = function() {
230 // we use some of these controls internally, so sett
231 // them up even if the caller doesn't request them.
232 var controls = $scope.gridControls || {};
234 controls.columnMap = function() {
236 angular.forEach(grid.columnsProvider.columns, function (c) {
242 controls.columnsProvider = function() {
243 return grid.columnsProvider;
246 // link in the control functions
247 controls.selectedItems = function() {
248 return grid.getSelectedItems()
251 controls.allItems = function() {
255 controls.selectItems = function(ids) {
257 $scope.selected = {};
258 angular.forEach(ids, function(i) {
259 $scope.selected[''+i] = true;
263 // if the caller provided a functional setQuery,
264 // extract the value before replacing it
265 if (controls.setQuery) {
266 grid.dataProvider.query =
270 controls.setQuery = function(query) {
271 grid.dataProvider.query = query;
275 if (controls.watchQuery) {
276 // capture the initial query value
277 grid.dataProvider.query = controls.watchQuery();
280 $scope.gridWatchQuery = controls.watchQuery;
281 $scope.$watch('gridWatchQuery()', function(newv) {
282 controls.setQuery(newv);
286 // if the caller provided a functional setSort
287 // extract the value before replacing it
288 grid.dataProvider.sort =
289 controls.setSort ? controls.setSort() : [];
291 controls.setSort = function(sort) {
295 controls.refresh = function(noReset) {
296 if (!noReset) grid.offset = 0;
300 controls.setLimit = function(limit,forget) {
301 if (!forget && grid.persistKey)
302 egCore.hatch.setLocalItem('eg.grid.' + grid.persistKey + '.limit', limit);
305 controls.getLimit = function() {
308 controls.setOffset = function(offset) {
309 grid.offset = offset;
311 controls.getOffset = function() {
315 controls.saveConfig = function () {
316 return $scope.saveConfig();
319 grid.dataProvider.refresh = controls.refresh;
320 grid.controls = controls;
323 // If a menu item provides its own HTML template, translate it,
324 // using the menu item for the template scope.
325 // note: $sce is required to avoid security restrictions and
326 // is OK here, since the template comes directly from a
327 // local HTML template (not user input).
328 $scope.translateMenuItemTemplate = function(item) {
329 var html = egCore.strings.$replace(item.template, {item : item});
330 return $sce.trustAsHtml(html);
333 // add a new (global) grid menu item
334 grid.addMenuItem = function(item) {
335 $scope.menuItems.push(item);
336 var handler = item.handler;
337 item.handler = function() {
338 $scope.gridMenuIsOpen = false; // close menu
341 item.handlerData, grid.getSelectedItems());
346 // add a selected-items action
347 grid.addAction = function(act) {
349 $scope.actionGroups.forEach(function(g){
350 if (g.label === act.group) {
356 $scope.actionGroups.push({
363 // remove the stored column configuration preferenc, then recover
364 // the column visibility information from the initial page load.
365 $scope.resetColumns = function() {
366 $scope.gridColumnPickerIsOpen = false;
367 egCore.hatch.removeItem('eg.grid.' + grid.persistKey)
369 grid.columnsProvider.reset();
370 if (grid.selfManagedData) grid.collect();
374 $scope.showAllColumns = function() {
375 $scope.gridColumnPickerIsOpen = false;
376 grid.columnsProvider.showAllColumns();
377 if (grid.selfManagedData) grid.collect();
380 $scope.hideAllColumns = function() {
381 $scope.gridColumnPickerIsOpen = false;
382 grid.columnsProvider.hideAllColumns();
383 // note: no need to fetch new data if no columns are visible
386 $scope.toggleColumnVisibility = function(col) {
387 $scope.gridColumnPickerIsOpen = false;
388 col.visible = !col.visible;
390 // egGridFlatDataProvider only retrieves data to be
391 // displayed. When column visibility changes, it's
392 // necessary to fetch the newly visible column data.
393 if (grid.selfManagedData) grid.collect();
396 // save the columns configuration (position, sort, width) to
397 // eg.grid.<persist-key>
398 $scope.saveConfig = function() {
399 $scope.gridColumnPickerIsOpen = false;
401 if (!grid.persistKey) {
403 "Cannot save settings without a grid persist-key");
407 // only store information about visible columns.
408 var conf = grid.columnsProvider.columns.filter(
409 function(col) {return Boolean(col.visible) });
411 // now scrunch the data down to just the needed info
412 conf = conf.map(function(col) {
413 var c = {name : col.name}
414 // Apart from the name, only store non-default values.
415 // No need to store col.visible, since that's implicit
416 if (col.align != 'left') c.align = col.align;
417 if (col.flex != 2) c.flex = col.flex;
418 if (Number(col.sort)) c.sort = Number(c.sort);
422 egCore.hatch.setItem('eg.grid.' + grid.persistKey, conf)
424 // Save operation performed from the grid configuration UI.
425 // Hide the configuration UI and re-draw w/ sort applied
426 if ($scope.showGridConf)
427 $scope.toggleConfDisplay();
432 // load the columns configuration (position, sort, width) from
433 // eg.grid.<persist-key> and apply the loaded settings to the
434 // columns on our columnsProvider
435 grid.loadConfig = function() {
436 if (!grid.persistKey) return $q.when();
438 return egCore.hatch.getItem('eg.grid.' + grid.persistKey)
439 .then(function(conf) {
442 var columns = grid.columnsProvider.columns;
445 angular.forEach(conf, function(col) {
446 var grid_col = columns.filter(
447 function(c) {return c.name == col.name})[0];
450 // saved column does not match a column in the
451 // current grid. skip it.
455 grid_col.align = col.align || 'left';
456 grid_col.flex = col.flex || 2;
457 grid_col.sort = col.sort || 0;
458 // all saved columns are assumed to be true
459 grid_col.visible = true;
461 .filter(function (c) {
462 return c.name == grid_col.name;
465 new_cols.push(grid_col);
468 // columns which are not expressed within the saved
469 // configuration are marked as non-visible and
470 // appended to the end of the new list of columns.
471 angular.forEach(columns, function(col) {
472 var found = conf.filter(
473 function(c) {return (c.name == col.name)})[0];
480 grid.columnsProvider.columns = new_cols;
486 $scope.onContextMenu = function($event) {
487 var col = angular.element($event.target).attr('column');
488 console.log('selected column ' + col);
491 $scope.page = function() {
492 return (grid.offset / grid.limit) + 1;
495 $scope.goToPage = function(page) {
497 if (angular.isNumber(page) && page > 0) {
498 grid.offset = (page - 1) * grid.limit;
503 $scope.offset = function(o) {
504 if (angular.isNumber(o))
509 $scope.limit = function(l) {
510 if (angular.isNumber(l)) {
512 egCore.hatch.setLocalItem('eg.grid.' + grid.persistKey + '.limit', l);
518 $scope.onFirstPage = function() {
519 return grid.offset == 0;
522 $scope.hasNextPage = function() {
523 // we have less data than requested, there must
524 // not be any more pages
525 if (grid.count() < grid.limit) return false;
527 // if the total count is not known, assume that a full
528 // page of data implies more pages are available.
529 if (grid.totalCount == -1) return true;
531 // we have a full page of data, but is there more?
532 return grid.totalCount > (grid.offset + grid.count());
535 $scope.incrementPage = function() {
536 grid.offset += grid.limit;
540 $scope.decrementPage = function() {
541 if (grid.offset < grid.limit) {
544 grid.offset -= grid.limit;
549 // number of items loaded for the current page of results
550 grid.count = function() {
551 return $scope.items.length;
554 // returns the unique identifier value for the provided item
555 // for internal consistency, indexValue is always coerced
557 grid.indexValue = function(item) {
558 if (angular.isObject(item)) {
560 if (angular.isFunction(item[grid.indexField]))
561 return ''+item[grid.indexField]();
562 return ''+item[grid.indexField]; // flat data
565 // passed a non-object; assume it's an index
569 // fires the hide handler function for a context action
570 $scope.actionHide = function(action) {
571 if (typeof action.hide == 'undefined') {
574 if (angular.isFunction(action.hide))
575 return action.hide(action);
579 // fires the disable handler function for a context action
580 $scope.actionDisable = function(action) {
581 if (typeof action.disabled == 'undefined') {
584 if (angular.isFunction(action.disabled))
585 return action.disabled(action);
586 return action.disabled;
589 // fires the action handler function for a context action
590 $scope.actionLauncher = function(action) {
591 if (!action.handler) {
593 'No handler specified for "' + action.label + '"');
597 action.handler(grid.getSelectedItems());
599 console.error('Error executing handler for "'
600 + action.label + '" => ' + E + "\n" + E.stack);
603 if ($scope.action_context_showing) $scope.hideActionContextMenu();
608 $scope.hideActionContextMenu = function () {
609 $($scope.menu_dom).css({
611 width: $scope.action_context_width,
612 top: $scope.action_context_y,
613 left: $scope.action_context_x
615 $($scope.action_context_parent).append($scope.menu_dom);
616 $scope.action_context_oldy = $scope.action_context_oldx = 0;
617 $('body').unbind('click.remove_context_menu_'+$scope.action_context_index);
618 $scope.action_context_showing = false;
621 $scope.action_context_showing = false;
622 $scope.showActionContextMenu = function ($event) {
624 // Have to gather these here, instead of inside link()
625 if (!$scope.menu_dom) $scope.menu_dom = $($scope.grid_element).find('.grid-action-dropdown')[0];
626 if (!$scope.action_context_parent) $scope.action_context_parent = $($scope.menu_dom).parent();
628 if (!grid.getSelectedItems().length) // Nothing selected, fire the click event
629 $event.target.click();
631 if (!$scope.action_context_showing) {
632 $scope.action_context_width = $($scope.menu_dom).css('width');
633 $scope.action_context_y = $($scope.menu_dom).css('top');
634 $scope.action_context_x = $($scope.menu_dom).css('left');
635 $scope.action_context_showing = true;
636 $scope.action_context_index = Math.floor((Math.random() * 1000) + 1);
638 $('body').append($($scope.menu_dom));
639 $('body').bind('click.remove_context_menu_'+$scope.action_context_index, $scope.hideActionContextMenu);
642 $($scope.menu_dom).css({
644 width: $scope.action_context_width,
652 // returns the list of selected item objects
653 grid.getSelectedItems = function() {
654 return $scope.items.filter(
656 return Boolean($scope.selected[grid.indexValue(item)]);
661 grid.getItemByIndex = function(index) {
662 for (var i = 0; i < $scope.items.length; i++) {
663 var item = $scope.items[i];
664 if (grid.indexValue(item) == index)
669 // selects one row after deselecting all of the others
670 grid.selectOneItem = function(index) {
671 $scope.selected = {};
672 $scope.selected[index] = true;
675 // selects or deselects an item, without affecting the others.
676 // returns true if the item is selected; false if de-selected.
677 // we overwrite the object so that we can watch $scope.selected
678 grid.toggleSelectOneItem = function(index) {
679 if ($scope.selected[index]) {
680 delete $scope.selected[index];
681 $scope.selected = angular.copy($scope.selected);
684 $scope.selected[index] = true;
685 $scope.selected = angular.copy($scope.selected);
690 $scope.updateSelected = function () {
691 return $scope.selected = angular.copy($scope.selected);
694 grid.selectAllItems = function() {
695 angular.forEach($scope.items, function(item) {
696 $scope.selected[grid.indexValue(item)] = true
698 $scope.selected = angular.copy($scope.selected);
701 $scope.$watch('selectAll', function(newVal) {
703 grid.selectAllItems();
705 $scope.selected = {};
709 if ($scope.onSelect) {
710 $scope.$watch('selected', function(newVal) {
711 $scope.onSelect(grid.getSelectedItems());
712 if ($scope.afterSelect) $scope.afterSelect();
716 // returns true if item1 appears in the list before item2;
717 // false otherwise. this is slightly more efficient that
718 // finding the position of each then comparing them.
719 // item1 / item2 may be an item or an item index
720 grid.itemComesBefore = function(itemOrIndex1, itemOrIndex2) {
721 var idx1 = grid.indexValue(itemOrIndex1);
722 var idx2 = grid.indexValue(itemOrIndex2);
724 // use for() for early exit
725 for (var i = 0; i < $scope.items.length; i++) {
726 var idx = grid.indexValue($scope.items[i]);
727 if (idx == idx1) return true;
728 if (idx == idx2) return false;
733 // 0-based position of item in the current data set
734 grid.indexOf = function(item) {
735 var idx = grid.indexValue(item);
736 for (var i = 0; i < $scope.items.length; i++) {
737 if (grid.indexValue($scope.items[i]) == idx)
743 grid.modifyColumnFlex = function(column, val) {
745 // prevent flex:0; use hiding instead
749 $scope.modifyColumnFlex = function(col, val) {
750 $scope.lastModColumn = col.name;
751 grid.modifyColumnFlex(col, val);
754 grid.modifyColumnPos = function(col, diff) {
755 var srcIdx, targetIdx;
756 angular.forEach(grid.columnsProvider.columns,
757 function(c, i) { if (c.name == col.name) srcIdx = i });
759 targetIdx = srcIdx + diff;
762 } else if (targetIdx >= grid.columnsProvider.columns.length) {
763 // Target index follows the last visible column.
765 angular.forEach(grid.columnsProvider.columns,
766 function(column, idx) {
767 if (column.visible) lastVisible = idx;
770 targetIdx = lastVisible + 1;
773 // Splice column out of old position, insert at new position.
774 grid.columnsProvider.columns.splice(srcIdx, 1);
775 grid.columnsProvider.columns.splice(targetIdx, 0, col);
778 $scope.modifyColumnPos = function(col, diff) {
779 $scope.lastModColumn = col.name;
780 return grid.modifyColumnPos(col, diff);
784 // handles click, control-click, and shift-click
785 $scope.handleRowClick = function($event, item) {
786 var index = grid.indexValue(item);
788 var origSelected = Object.keys($scope.selected);
790 if (!$scope.canMultiSelect) {
791 grid.selectOneItem(index);
792 grid.lastSelectedItemIndex = index;
796 if ($event.ctrlKey || $event.metaKey /* mac command */) {
798 if (grid.toggleSelectOneItem(index))
799 grid.lastSelectedItemIndex = index;
801 } else if ($event.shiftKey) {
804 if (!grid.lastSelectedItemIndex ||
805 index == grid.lastSelectedItemIndex) {
806 grid.selectOneItem(index);
807 grid.lastSelectedItemIndex = index;
811 var selecting = false;
812 var ascending = grid.itemComesBefore(
813 grid.lastSelectedItemIndex, item);
815 grid.indexOf(grid.lastSelectedItemIndex);
817 // update to new last-selected
818 grid.lastSelectedItemIndex = index;
820 // select each row between the last selected and
821 // currently selected items
823 startPos += ascending ? 1 : -1;
824 var curItem = $scope.items[startPos];
826 var curIdx = grid.indexValue(curItem);
827 $scope.selected[curIdx] = true;
828 if (curIdx == index) break; // all done
830 $scope.selected = angular.copy($scope.selected);
834 grid.selectOneItem(index);
835 grid.lastSelectedItemIndex = index;
839 // Builds a sort expression from column sort priorities.
840 // called on page load and any time the priorities are modified.
841 grid.compileSort = function() {
842 var sortList = grid.columnsProvider.columns.filter(
843 function(col) { return Number(col.sort) != 0 }
846 if (Math.abs(a.sort) < Math.abs(b.sort))
852 if (sortList.length) {
853 grid.dataProvider.sort = sortList.map(function(col) {
855 blob[col.name] = col.sort < 0 ? 'desc' : 'asc';
861 // builds a sort expression using a single column,
862 // toggling between ascending and descending sort.
863 $scope.quickSort = function(col_name) {
864 var sort = grid.dataProvider.sort;
865 if (sort && sort.length &&
866 sort[0] == col_name) {
868 blob[col_name] = 'desc';
869 grid.dataProvider.sort = [blob];
871 grid.dataProvider.sort = [col_name];
878 // show / hide the grid configuration row
879 $scope.toggleConfDisplay = function() {
880 if ($scope.showGridConf) {
881 $scope.showGridConf = false;
882 if (grid.columnsProvider.hasSortableColumn()) {
883 // only refresh the grid if the user has the
884 // ability to modify the sort priorities.
890 $scope.showGridConf = true;
893 delete $scope.lastModColumn;
894 $scope.gridColumnPickerIsOpen = false;
897 // called when a dragged column is dropped onto itself
898 // or any other column
899 grid.onColumnDrop = function(target) {
900 if (angular.isUndefined(target)) return;
901 if (target == grid.dragColumn) return;
902 var srcIdx, targetIdx, srcCol;
903 angular.forEach(grid.columnsProvider.columns,
905 if (col.name == grid.dragColumn) {
908 } else if (col.name == target) {
914 if (srcIdx < targetIdx) targetIdx--;
916 // move src column from old location to new location in
917 // the columns array, then force a page refresh
918 grid.columnsProvider.columns.splice(srcIdx, 1);
919 grid.columnsProvider.columns.splice(targetIdx, 0, srcCol);
923 // prepares a string for inclusion within a CSV document
924 // by escaping commas and quotes and removing newlines.
925 grid.csvDatum = function(str) {
928 str = str.replace(/\n/g, '');
929 if (str.match(/\,/) || str.match(/"/)) {
930 str = str.replace(/"/g, '""');
931 str = '"' + str + '"';
936 // sets the download file name and inserts the current CSV
937 // into a Blob URL for browser download.
938 $scope.generateCSVExportURL = function() {
939 $scope.gridColumnPickerIsOpen = false;
941 // let the file name describe the grid
942 $scope.csvExportFileName =
943 ($scope.mainLabel || grid.persistKey || 'eg_grid_data')
944 .replace(/\s+/g, '_') + '_' + $scope.page();
946 // toss the CSV into a Blob and update the export URL
947 var csv = grid.generateCSV();
948 var blob = new Blob([csv], {type : 'text/plain'});
949 $scope.csvExportURL =
950 ($window.URL || $window.webkitURL).createObjectURL(blob);
953 $scope.printCSV = function() {
954 $scope.gridColumnPickerIsOpen = false;
957 content : grid.generateCSV(),
958 content_type : 'text/plain'
962 // generates CSV for the currently visible grid contents
963 grid.generateCSV = function() {
965 var colCount = grid.columnsProvider.columns.length;
968 angular.forEach(grid.columnsProvider.columns,
970 if (!col.visible) return;
971 csvStr += grid.csvDatum(col.label);
976 csvStr = csvStr.replace(/,$/,'\n');
979 angular.forEach($scope.items, function(item) {
980 angular.forEach(grid.columnsProvider.columns,
982 if (!col.visible) return;
984 var val = grid.dataProvider.itemFieldValue(item, col);
985 // filtered value (dates, etc.)
986 val = $filter('egGridValueFilter')(val, col);
987 csvStr += grid.csvDatum(val);
991 csvStr = csvStr.replace(/,$/,'\n');
997 // Interpolate the value for column.linkpath within the context
998 // of the row item to generate the final link URL.
999 $scope.generateLinkPath = function(col, item) {
1000 return egCore.strings.$replace(col.linkpath, {item : item});
1003 // If a column provides its own HTML template, translate it,
1004 // using the current item for the template scope.
1005 // note: $sce is required to avoid security restrictions and
1006 // is OK here, since the template comes directly from a
1007 // local HTML template (not user input).
1008 $scope.translateCellTemplate = function(col, item) {
1009 var html = egCore.strings.$replace(col.template, {item : item});
1010 return $sce.trustAsHtml(html);
1013 $scope.collect = function() { grid.collect() }
1015 // asks the dataProvider for a page of data
1016 grid.collect = function() {
1018 // avoid firing the collect if there is nothing to collect.
1019 if (grid.selfManagedData && !grid.dataProvider.query) return;
1021 if (grid.collecting) return; // avoid parallel collect()
1022 grid.collecting = true;
1024 console.debug('egGrid.collect() offset='
1025 + grid.offset + '; limit=' + grid.limit);
1027 // ensure all of our dropdowns are closed
1028 // TODO: git rid of these and just use dropdown-toggle,
1029 // which is more reliable.
1030 $scope.gridColumnPickerIsOpen = false;
1031 $scope.gridRowCountIsOpen = false;
1032 $scope.gridPageSelectIsOpen = false;
1035 $scope.selected = {};
1037 // Inform the caller we've asked the data provider
1038 // for data. This is useful for knowing when collection
1039 // has started (e.g. to display a progress dialg) when
1040 // using the stock (flattener) data provider, where the
1041 // user is not directly defining a get() handler.
1042 if (grid.controls.collectStarted)
1043 grid.controls.collectStarted(grid.offset, grid.limit);
1045 grid.dataProvider.get(grid.offset, grid.limit).then(
1047 if (grid.controls.allItemsRetrieved)
1048 grid.controls.allItemsRetrieved();
1053 $scope.items.push(item)
1054 if (grid.controls.itemRetrieved)
1055 grid.controls.itemRetrieved(item);
1056 if ($scope.selectAll)
1057 $scope.selected[grid.indexValue(item)] = true
1059 }).finally(function() {
1060 console.debug('egGrid.collect() complete');
1061 grid.collecting = false
1062 $scope.selected = angular.copy($scope.selected);
1072 * eg-grid-field : used for collecting custom field data from the templates.
1073 * This directive does not direct display, it just passes data up to the
1076 .directive('egGridField', function() {
1078 require : '^egGrid',
1081 flesher: '=', // optional; function that can flesh a linked field, given the value
1082 name : '@', // required; unique name
1083 path : '@', // optional; flesh path
1084 ignore: '@', // optional; fields to ignore when path is a wildcard
1085 label : '@', // optional; display label
1086 flex : '@', // optional; default flex width
1087 align : '@', // optional; default alignment, left/center/right
1088 dateformat : '@', // optional: passed down to egGridValueFilter
1090 // if a field is part of an IDL object, but we are unable to
1091 // determine the class, because it's nested within a hash
1092 // (i.e. we can't navigate directly to the object via the IDL),
1093 // idlClass lets us specify the class. This is particularly
1094 // useful for nested wildcard fields.
1095 parentIdlClass : '@',
1097 // optional: for non-IDL columns, specifying a datatype
1098 // lets the caller control which display filter is used.
1099 // datatype should match the standard IDL datatypes.
1102 link : function(scope, element, attrs, egGridCtrl) {
1104 // boolean fields are presented as value-less attributes
1113 'required' // if set, always fetch data for this column
1116 if (angular.isDefined(attrs[field]))
1117 scope[field] = true;
1121 // any HTML content within the field is its custom template
1122 var tmpl = element.html();
1123 if (tmpl && !tmpl.match(/^\s*$/))
1124 scope.template = tmpl
1126 egGridCtrl.columnsProvider.add(scope);
1133 * eg-grid-action : used for specifying actions which may be applied
1134 * to items within the grid.
1136 .directive('egGridAction', function() {
1138 require : '^egGrid',
1142 group : '@', // Action group, ungrouped if not set
1143 label : '@', // Action label
1144 handler : '=', // Action function handler
1146 disabled : '=', // function
1149 link : function(scope, element, attrs, egGridCtrl) {
1150 egGridCtrl.addAction({
1152 group : scope.group,
1153 label : scope.label,
1154 divider : scope.divider,
1155 handler : scope.handler,
1156 disabled : scope.disabled,
1163 .factory('egGridColumnsProvider', ['egCore', function(egCore) {
1165 function ColumnsProvider(args) {
1168 cols.stockVisible = [];
1169 cols.idlClass = args.idlClass;
1170 cols.defaultToHidden = args.defaultToHidden;
1171 cols.defaultToNoSort = args.defaultToNoSort;
1172 cols.defaultToNoMultiSort = args.defaultToNoMultiSort;
1174 // resets column width, visibility, and sort behavior
1175 // Visibility resets to the visibility settings defined in the
1176 // template (i.e. the original egGridField values).
1177 cols.reset = function() {
1178 angular.forEach(cols.columns, function(col) {
1182 if (cols.stockVisible.indexOf(col.name) > -1) {
1185 col.visible = false;
1190 // returns true if any columns are sortable
1191 cols.hasSortableColumn = function() {
1192 return cols.columns.filter(
1194 return col.sortable || col.multisortable;
1199 cols.showAllColumns = function() {
1200 angular.forEach(cols.columns, function(column) {
1201 column.visible = true;
1205 cols.hideAllColumns = function() {
1206 angular.forEach(cols.columns, function(col) {
1211 cols.indexOf = function(name) {
1212 for (var i = 0; i < cols.columns.length; i++) {
1213 if (cols.columns[i].name == name)
1219 cols.findColumn = function(name) {
1220 return cols.columns[cols.indexOf(name)];
1223 cols.compileAutoColumns = function() {
1224 var idl_class = egCore.idl.classes[cols.idlClass];
1229 if (field.virtual) return;
1230 if (field.datatype == 'link' || field.datatype == 'org_unit') {
1231 // if the field is a link and the linked class has a
1232 // "selector" field specified, use the selector field
1233 // as the display field for the columns.
1234 // flattener will take care of the fleshing.
1235 if (field['class']) {
1236 var selector_field = egCore.idl.classes[field['class']].fields
1237 .filter(function(f) { return Boolean(f.selector) })[0];
1238 if (selector_field) {
1239 field.path = field.name + '.' + selector_field.selector;
1243 cols.add(field, true);
1248 // if a column definition has a path with a wildcard, create
1249 // columns for all non-virtual fields at the specified
1250 // position in the path.
1251 cols.expandPath = function(colSpec) {
1253 var ignoreList = [];
1255 ignoreList = colSpec.ignore.split(' ');
1257 var dotpath = colSpec.path.replace(/\.?\*$/,'');
1261 if (colSpec.parentIdlClass) {
1262 class_obj = egCore.idl.classes[colSpec.parentIdlClass];
1264 class_obj = egCore.idl.classes[cols.idlClass];
1266 var idl_parent = class_obj;
1267 var old_field_label = '';
1269 if (!class_obj) return;
1271 console.debug('egGrid: auto dotpath is: ' + dotpath);
1272 var path_parts = dotpath.split(/\./);
1274 // find the IDL class definition for the last element in the
1275 // path before the .*
1276 // an empty path_parts means expand the root class
1279 for (var path_idx in path_parts) {
1280 old_field = idl_field;
1282 var part = path_parts[path_idx];
1283 idl_field = class_obj.field_map[part];
1285 // unless we're at the end of the list, this field should
1286 // link to another class.
1287 if (idl_field && idl_field['class'] && (
1288 idl_field.datatype == 'link' ||
1289 idl_field.datatype == 'org_unit')) {
1290 if (old_field_label) old_field_label += ' : ';
1291 old_field_label += idl_field.label;
1292 class_obj = egCore.idl.classes[idl_field['class']];
1293 if (old_field) idl_parent = old_field;
1295 if (path_idx < (path_parts.length - 1)) {
1296 // we ran out of classes to hop through before
1297 // we ran out of path components
1298 console.error("egGrid: invalid IDL path: " + dotpath);
1305 angular.forEach(class_obj.fields, function(field) {
1307 // Only show wildcard fields where we have data to show
1308 // Virtual and un-fleshed links will not have any data.
1309 if (field.virtual ||
1310 (field.datatype == 'link' || field.datatype == 'org_unit') ||
1311 ignoreList.indexOf(field.name) > -1
1315 var col = cols.cloneFromScope(colSpec);
1316 col.path = (dotpath ? dotpath + '.' + field.name : field.name);
1318 // log line below is very chatty. disable until needed.
1319 // console.debug('egGrid: field: ' +field.name + '; parent field: ' + js2JSON(idl_parent));
1320 cols.add(col, false, true,
1321 {idl_parent : idl_parent, idl_field : field, idl_class : class_obj, field_parent_label : old_field_label });
1324 cols.columns = cols.columns.sort(
1326 if (a.explicit) return -1;
1327 if (b.explicit) return 1;
1329 if (a.idlclass && b.idlclass) {
1330 if (a.idlclass < b.idlclass) return -1;
1331 if (b.idlclass < a.idlclass) return 1;
1334 if (a.path && b.path && a.path.lastIndexOf('.') && b.path.lastIndexOf('.')) {
1335 if (a.path.substring(0, a.path.lastIndexOf('.')) < b.path.substring(0, b.path.lastIndexOf('.'))) return -1;
1336 if (b.path.substring(0, b.path.lastIndexOf('.')) < a.path.substring(0, a.path.lastIndexOf('.'))) return 1;
1339 if (a.label && b.label) {
1340 if (a.label < b.label) return -1;
1341 if (b.label < a.label) return 1;
1344 return a.name < b.name ? -1 : 1;
1351 "egGrid: wildcard path does not resolve to an object: "
1356 // angular.clone(scopeObject) is not permittable. Manually copy
1357 // the fields over that we need (so the scope object can go away).
1358 cols.cloneFromScope = function(colSpec) {
1360 flesher : colSpec.flesher,
1361 name : colSpec.name,
1362 label : colSpec.label,
1363 path : colSpec.path,
1364 align : colSpec.align || 'left',
1365 flex : Number(colSpec.flex) || 2,
1366 sort : Number(colSpec.sort) || 0,
1367 required : colSpec.required,
1368 linkpath : colSpec.linkpath,
1369 template : colSpec.template,
1370 visible : colSpec.visible,
1371 hidden : colSpec.hidden,
1372 datatype : colSpec.datatype,
1373 sortable : colSpec.sortable,
1374 nonsortable : colSpec.nonsortable,
1375 multisortable : colSpec.multisortable,
1376 nonmultisortable : colSpec.nonmultisortable,
1377 dateformat : colSpec.dateformat,
1378 parentIdlClass : colSpec.parentIdlClass
1383 // Add a column to the columns collection.
1384 // Columns may come from a slim eg-columns-field or
1385 // directly from the IDL.
1386 cols.add = function(colSpec, fromIDL, fromExpand, idl_info) {
1388 // First added column with the specified path takes precedence.
1389 // This allows for specific definitions followed by wildcard
1390 // definitions. If a match is found, back out.
1391 if (cols.columns.filter(function(c) {
1392 return (c.path == colSpec.path) })[0]) {
1393 console.debug('skipping pre-existing column ' + colSpec.path);
1397 var column = fromExpand ? colSpec : cols.cloneFromScope(colSpec);
1399 if (column.path && column.path.match(/\*$/))
1400 return cols.expandPath(colSpec);
1402 if (!fromExpand) column.explicit = true;
1404 if (!column.name) column.name = column.path;
1405 if (!column.path) column.path = column.name;
1407 if (column.visible || (!cols.defaultToHidden && !column.hidden))
1408 column.visible = true;
1410 if (column.sortable || (!cols.defaultToNoSort && !column.nonsortable))
1411 column.sortable = true;
1413 if (column.multisortable ||
1414 (!cols.defaultToNoMultiSort && !column.nonmultisortable))
1415 column.multisortable = true;
1417 cols.columns.push(column);
1419 // Track which columns are visible by default in case we
1420 // need to reset column visibility
1422 cols.stockVisible.push(column.name);
1424 if (fromIDL) return; // directly from egIDL. nothing left to do.
1426 // lookup the matching IDL field
1427 if (!idl_info && cols.idlClass)
1428 idl_info = cols.idlFieldFromPath(column.path);
1431 // column is not represented within the IDL
1432 column.adhoc = true;
1436 column.datatype = idl_info.idl_field.datatype;
1438 if (!column.label) {
1439 column.label = idl_info.idl_field.label || column.name;
1442 if (fromExpand && idl_info.idl_class) {
1443 column.idlclass = '';
1444 if (idl_info.field_parent_label && idl_info.idl_parent.label != idl_info.idl_class.label) {
1445 column.idlclass = (idl_info.field_parent_label || idl_info.idl_parent.label || idl_info.idl_parent.name);
1447 column.idlclass += idl_info.idl_class.label || idl_info.idl_class.name;
1452 // finds the IDL field from the dotpath, using the columns
1453 // idlClass as the base.
1454 cols.idlFieldFromPath = function(dotpath) {
1455 var class_obj = egCore.idl.classes[cols.idlClass];
1456 var path_parts = dotpath.split(/\./);
1460 for (var path_idx in path_parts) {
1461 var part = path_parts[path_idx];
1462 idl_parent = idl_field;
1463 idl_field = class_obj.field_map[part];
1466 if (idl_field['class'] && (
1467 idl_field.datatype == 'link' ||
1468 idl_field.datatype == 'org_unit')) {
1469 class_obj = egCore.idl.classes[idl_field['class']];
1477 idl_parent: idl_parent,
1478 idl_field : idl_field,
1479 idl_class : class_obj
1485 instance : function(args) { return new ColumnsProvider(args) }
1491 * Generic data provider template class. This is basically an abstract
1492 * class factory service whose instances can be locally modified to
1493 * meet the needs of each individual grid.
1495 .factory('egGridDataProvider',
1496 ['$q','$timeout','$filter','egCore',
1497 function($q , $timeout , $filter , egCore) {
1499 function GridDataProvider(args) {
1500 var gridData = this;
1501 if (!args) args = {};
1504 gridData.get = args.get;
1505 gridData.query = args.query;
1506 gridData.idlClass = args.idlClass;
1507 gridData.columnsProvider = args.columnsProvider;
1509 // Delivers a stream of array data via promise.notify()
1510 // Useful for passing an array of data to egGrid.get()
1511 // If a count is provided, the array will be trimmed to
1512 // the range defined by count and offset
1513 gridData.arrayNotifier = function(arr, offset, count) {
1514 if (!arr || arr.length == 0) return $q.when();
1515 if (count) arr = arr.slice(offset, offset + count);
1516 var def = $q.defer();
1517 // promise notifications are only witnessed when delivered
1518 // after the caller has his hands on the promise object
1519 $timeout(function() {
1520 angular.forEach(arr, def.notify);
1526 // Calls the grid refresh function. Once instantiated, the
1527 // grid will replace this function with it's own refresh()
1528 gridData.refresh = function(noReset) { }
1530 if (!gridData.get) {
1531 // returns a promise whose notify() delivers items
1532 gridData.get = function(index, count) {
1533 console.error("egGridDataProvider.get() not implemented");
1537 // attempts a flat field lookup first. If the column is not
1538 // found on the top-level object, attempts a nested lookup
1539 // TODO: consider a caching layer to speed up template
1540 // rendering, particularly for nested objects?
1541 gridData.itemFieldValue = function(item, column) {
1543 if (column.name in item) {
1544 if (typeof item[column.name] == 'function') {
1545 val = item[column.name]();
1547 val = item[column.name];
1550 val = gridData.nestedItemFieldValue(item, column);
1556 // TODO: deprecate me
1557 gridData.flatItemFieldValue = function(item, column) {
1558 console.warn('gridData.flatItemFieldValue deprecated; '
1559 + 'leave provider.itemFieldValue unset');
1560 return item[column.name];
1563 // given an object and a dot-separated path to a field,
1564 // extract the value of the field. The path can refer
1565 // to function names or object attributes. If the final
1566 // value is an IDL field, run the value through its
1567 // corresponding output filter.
1568 gridData.nestedItemFieldValue = function(obj, column) {
1569 item = obj; // keep a copy around
1571 if (obj === null || obj === undefined || obj === '') return '';
1572 if (!column.path) return obj;
1575 var parts = column.path.split('.');
1577 angular.forEach(parts, function(step, idx) {
1578 // object is not fleshed to the expected extent
1579 if (typeof obj != 'object') {
1580 if (typeof obj != 'undefined' && column.flesher) {
1581 obj = column.flesher(obj, column, item);
1588 if (!obj) return '';
1590 var cls = obj.classname;
1591 if (cls && (class_obj = egCore.idl.classes[cls])) {
1592 idl_field = class_obj.field_map[step];
1593 obj = obj[step] ? obj[step]() : '';
1595 if (angular.isFunction(obj[step])) {
1603 // We found a nested IDL object which may or may not have
1604 // been configured as a top-level column. Grab the datatype.
1605 if (idl_field && !column.datatype)
1606 column.datatype = idl_field.datatype;
1608 if (obj === null || obj === undefined || obj === '') return '';
1614 instance : function(args) {
1615 return new GridDataProvider(args);
1622 // Factory service for egGridDataManager instances, which are
1623 // responsible for collecting flattened grid data.
1624 .factory('egGridFlatDataProvider',
1625 ['$q','egCore','egGridDataProvider',
1626 function($q , egCore , egGridDataProvider) {
1629 instance : function(args) {
1630 var provider = egGridDataProvider.instance(args);
1632 provider.get = function(offset, count) {
1634 // no query means no call
1635 if (!provider.query ||
1636 angular.equals(provider.query, {}))
1639 // find all of the currently visible columns
1640 var queryFields = {}
1641 angular.forEach(provider.columnsProvider.columns,
1643 // only query IDL-tracked columns
1644 if (!col.adhoc && (col.required || col.visible))
1645 queryFields[col.name] = col.path;
1649 return egCore.net.request(
1651 'open-ils.fielder.flattened_search',
1652 egCore.auth.token(), provider.idlClass,
1653 queryFields, provider.query,
1654 { sort : provider.sort,
1660 //provider.itemFieldValue = provider.flatItemFieldValue;
1667 .directive('egGridColumnDragSource', function() {
1670 require : '^egGrid',
1671 link : function(scope, element, attrs, egGridCtrl) {
1672 angular.element(element).attr('draggable', 'true');
1674 element.bind('dragstart', function(e) {
1675 egGridCtrl.dragColumn = attrs.column;
1676 egGridCtrl.dragType = attrs.dragType || 'move'; // or resize
1677 egGridCtrl.colResizeDir = 0;
1679 if (egGridCtrl.dragType == 'move') {
1680 // style the column getting moved
1681 angular.element(e.target).addClass(
1682 'eg-grid-column-move-handle-active');
1686 element.bind('dragend', function(e) {
1687 if (egGridCtrl.dragType == 'move') {
1688 angular.element(e.target).removeClass(
1689 'eg-grid-column-move-handle-active');
1696 .directive('egGridColumnDragDest', function() {
1699 require : '^egGrid',
1700 link : function(scope, element, attrs, egGridCtrl) {
1702 element.bind('dragover', function(e) { // required for drop
1703 e.stopPropagation();
1705 e.dataTransfer.dropEffect = 'move';
1707 if (egGridCtrl.colResizeDir == 0) return; // move
1709 var cols = egGridCtrl.columnsProvider;
1710 var srcCol = egGridCtrl.dragColumn;
1711 var srcColIdx = cols.indexOf(srcCol);
1713 if (egGridCtrl.colResizeDir == -1) {
1714 if (cols.indexOf(attrs.column) <= srcColIdx) {
1715 egGridCtrl.modifyColumnFlex(
1716 egGridCtrl.columnsProvider.findColumn(
1717 egGridCtrl.dragColumn), -1);
1718 if (cols.columns[srcColIdx+1]) {
1719 // source column shrinks by one, column to the
1720 // right grows by one.
1721 egGridCtrl.modifyColumnFlex(
1722 cols.columns[srcColIdx+1], 1);
1727 if (cols.indexOf(attrs.column) > srcColIdx) {
1728 egGridCtrl.modifyColumnFlex(
1729 egGridCtrl.columnsProvider.findColumn(
1730 egGridCtrl.dragColumn), 1);
1731 if (cols.columns[srcColIdx+1]) {
1732 // source column grows by one, column to the
1733 // right grows by one.
1734 egGridCtrl.modifyColumnFlex(
1735 cols.columns[srcColIdx+1], -1);
1743 element.bind('dragenter', function(e) {
1744 e.stopPropagation();
1746 if (egGridCtrl.dragType == 'move') {
1747 angular.element(e.target).addClass('eg-grid-col-hover');
1749 // resize grips are on the right side of each column.
1750 // dragenter will either occur on the source column
1751 // (dragging left) or the column to the right.
1752 if (egGridCtrl.colResizeDir == 0) {
1753 if (egGridCtrl.dragColumn == attrs.column) {
1754 egGridCtrl.colResizeDir = -1; // west
1756 egGridCtrl.colResizeDir = 1; // east
1762 element.bind('dragleave', function(e) {
1763 e.stopPropagation();
1765 if (egGridCtrl.dragType == 'move') {
1766 angular.element(e.target).removeClass('eg-grid-col-hover');
1770 element.bind('drop', function(e) {
1771 e.stopPropagation();
1773 egGridCtrl.colResizeDir = 0;
1774 if (egGridCtrl.dragType == 'move') {
1775 angular.element(e.target).removeClass('eg-grid-col-hover');
1776 egGridCtrl.onColumnDrop(attrs.column); // move the column
1783 .directive('egGridMenuItem', function() {
1786 require : '^egGrid',
1792 handler : '=', // onclick handler function
1793 divider : '=', // if true, show a divider only
1794 handlerData : '=', // if set, passed as second argument to handler
1795 disabled : '=', // function
1796 hidden : '=' // function
1798 link : function(scope, element, attrs, egGridCtrl) {
1799 egGridCtrl.addMenuItem({
1800 checkbox : scope.checkbox,
1801 checked : scope.checked ? true : false,
1802 label : scope.label,
1803 standalone : scope.standalone ? true : false,
1804 handler : scope.handler,
1805 divider : scope.divider,
1806 disabled : scope.disabled,
1807 hidden : scope.hidden,
1808 handlerData : scope.handlerData
1818 * Translates bare IDL object values into display values.
1819 * 1. Passes dates through the angular date filter
1820 * 2. Translates bools to Booleans so the browser can display translated
1821 * value. (Though we could manually translate instead..)
1822 * Others likely to follow...
1824 .filter('egGridValueFilter', ['$filter', function($filter) {
1825 return function(value, column) {
1826 switch(column.datatype) {
1829 // Browser will translate true/false for us
1831 case '1' : // legacy
1835 case '0' : // legacy
1838 // value may be null, '', etc.
1839 default : return '';
1842 // canned angular date filter FTW
1843 if (!column.dateformat)
1844 column.dateformat = 'shortDate';
1845 return $filter('date')(value, column.dateformat);
1847 return $filter('currency')(value);