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 // itemRetrieved : function(item) {}
72 // allItemsRetrieved : function() {}
75 // If defined, the grid will watch the return value from
76 // the function defined at watchQuery on each digest and
77 // re-draw the grid when query changes occur.
79 // watchQuery : function() { /* return grid query */ }
82 // These functions are defined by the grid and thus
83 // replace any values defined for these attributes from the
86 // activateItem : function(item) {}
87 // allItems : function(allItems) {}
88 // selectedItems : function(selected) {}
89 // selectItems : function(ids) {}
90 // setQuery : function(queryStruct) {} // causes reload
91 // setSort : function(sortSturct) {} // causes reload
95 // TODO: avoid hard-coded url
96 templateUrl : '/eg/staff/share/t_autogrid',
98 link : function(scope, element, attrs) {
99 // link() is called after page compilation, which means our
100 // eg-grid-field's have been parsed and loaded. Now it's
101 // safe to perform our initial page load.
103 // load auto fields after eg-grid-field's so they are not clobbered
104 scope.handleAutoFields();
107 scope.grid_element = element;
109 .find('.eg-grid-content-body')
110 .bind('contextmenu', scope.showActionContextMenu);
114 '$scope','$q','egCore','egGridFlatDataProvider','$location',
115 'egGridColumnsProvider','$filter','$window','$sce','$timeout',
116 function($scope, $q , egCore, egGridFlatDataProvider , $location,
117 egGridColumnsProvider , $filter , $window , $sce , $timeout) {
121 grid.init = function() {
124 $scope.showGridConf = false;
125 grid.totalCount = -1;
126 $scope.selected = {};
127 $scope.actionGroups = [{actions:[]}]; // Grouped actions for selected items
128 $scope.menuItems = []; // global actions
130 // returns true if any rows are selected.
131 $scope.hasSelected = function() {
132 return grid.getSelectedItems().length > 0 };
134 var features = ($scope.features) ?
135 $scope.features.split(',') : [];
136 delete $scope.features;
138 $scope.showIndex = (features.indexOf('-index') == -1);
140 $scope.allowAll = (features.indexOf('allowAll') > -1);
141 $scope.startSelected = $scope.selectAll = (features.indexOf('startSelected') > -1);
142 $scope.showActions = (features.indexOf('-actions') == -1);
143 $scope.showPagination = (features.indexOf('-pagination') == -1);
144 $scope.showPicker = (features.indexOf('-picker') == -1);
146 $scope.showMenu = (features.indexOf('-menu') == -1);
148 // remove some unneeded values from the scope to reduce bloat
150 grid.idlClass = $scope.idlClass;
151 delete $scope.idlClass;
153 grid.persistKey = $scope.persistKey;
154 delete $scope.persistKey;
156 var stored_limit = 0;
157 if ($scope.showPagination) {
158 if (grid.persistKey) {
159 var stored_limit = Number(
160 egCore.hatch.getLocalItem('eg.grid.' + grid.persistKey + '.limit')
164 stored_limit = 10000; // maybe support "Inf"?
167 grid.limit = Number(stored_limit) || Number($scope.pageSize) || 25;
169 grid.indexField = $scope.idField;
170 delete $scope.idField;
172 grid.dataProvider = $scope.itemsProvider;
174 if (!grid.indexField && grid.idlClass)
175 grid.indexField = egCore.idl.classes[grid.idlClass].pkey;
177 grid.columnsProvider = egGridColumnsProvider.instance({
178 idlClass : grid.idlClass,
179 defaultToHidden : (features.indexOf('-display') > -1),
180 defaultToNoSort : (features.indexOf('-sort') > -1),
181 defaultToNoMultiSort : (features.indexOf('-multisort') > -1)
183 $scope.canMultiSelect = (features.indexOf('-multiselect') == -1);
185 $scope.handleAutoFields = function() {
186 if ($scope.autoFields) {
187 if (grid.autoLabel) {
189 egCore.idl.classes[grid.idlClass].label;
191 grid.columnsProvider.compileAutoColumns();
192 delete $scope.autoFields;
196 if (!grid.dataProvider) {
197 // no provider, um, provided.
198 // Use a flat data provider
200 grid.selfManagedData = true;
201 grid.dataProvider = egGridFlatDataProvider.instance({
202 indexField : grid.indexField,
203 idlClass : grid.idlClass,
204 columnsProvider : grid.columnsProvider,
209 $scope.itemFieldValue = grid.dataProvider.itemFieldValue;
210 $scope.indexValue = function(item) {
211 return grid.indexValue(item)
214 grid.applyControlFunctions();
216 grid.loadConfig().then(function() {
217 // link columns to scope after loadConfig(), since it
218 // replaces the columns array.
219 $scope.columns = grid.columnsProvider.columns;
222 // NOTE: grid.collect() is first called from link(), not here.
225 // link our control functions into the gridControls
226 // scope object so the caller can access them.
227 grid.applyControlFunctions = function() {
229 // we use some of these controls internally, so sett
230 // them up even if the caller doesn't request them.
231 var controls = $scope.gridControls || {};
233 controls.columnMap = function() {
235 angular.forEach(grid.columnsProvider.columns, function (c) {
241 controls.columnsProvider = function() {
242 return grid.columnsProvider;
245 // link in the control functions
246 controls.selectedItems = function() {
247 return grid.getSelectedItems()
250 controls.allItems = function() {
254 controls.selectItems = function(ids) {
256 $scope.selected = {};
257 angular.forEach(ids, function(i) {
258 $scope.selected[''+i] = true;
262 // if the caller provided a functional setQuery,
263 // extract the value before replacing it
264 if (controls.setQuery) {
265 grid.dataProvider.query =
269 controls.setQuery = function(query) {
270 grid.dataProvider.query = query;
274 if (controls.watchQuery) {
275 // capture the initial query value
276 grid.dataProvider.query = controls.watchQuery();
279 $scope.gridWatchQuery = controls.watchQuery;
280 $scope.$watch('gridWatchQuery()', function(newv) {
281 controls.setQuery(newv);
285 // if the caller provided a functional setSort
286 // extract the value before replacing it
287 grid.dataProvider.sort =
288 controls.setSort ? controls.setSort() : [];
290 controls.setSort = function(sort) {
294 controls.refresh = function(noReset) {
295 if (!noReset) grid.offset = 0;
299 controls.setLimit = function(limit,forget) {
300 if (!forget && grid.persistKey)
301 egCore.hatch.setLocalItem('eg.grid.' + grid.persistKey + '.limit', limit);
304 controls.getLimit = function() {
307 controls.setOffset = function(offset) {
308 grid.offset = offset;
310 controls.getOffset = function() {
314 controls.saveConfig = function () {
315 return $scope.saveConfig();
318 grid.dataProvider.refresh = controls.refresh;
319 grid.controls = controls;
322 // If a menu item provides its own HTML template, translate it,
323 // using the menu item for the template scope.
324 // note: $sce is required to avoid security restrictions and
325 // is OK here, since the template comes directly from a
326 // local HTML template (not user input).
327 $scope.translateMenuItemTemplate = function(item) {
328 var html = egCore.strings.$replace(item.template, {item : item});
329 return $sce.trustAsHtml(html);
332 // add a new (global) grid menu item
333 grid.addMenuItem = function(item) {
334 $scope.menuItems.push(item);
335 var handler = item.handler;
336 item.handler = function() {
337 $scope.gridMenuIsOpen = false; // close menu
340 item.handlerData, grid.getSelectedItems());
345 // add a selected-items action
346 grid.addAction = function(act) {
348 $scope.actionGroups.forEach(function(g){
349 if (g.label === act.group) {
355 $scope.actionGroups.push({
362 // remove the stored column configuration preferenc, then recover
363 // the column visibility information from the initial page load.
364 $scope.resetColumns = function() {
365 $scope.gridColumnPickerIsOpen = false;
366 egCore.hatch.removeItem('eg.grid.' + grid.persistKey)
368 grid.columnsProvider.reset();
369 if (grid.selfManagedData) grid.collect();
373 $scope.showAllColumns = function() {
374 $scope.gridColumnPickerIsOpen = false;
375 grid.columnsProvider.showAllColumns();
376 if (grid.selfManagedData) grid.collect();
379 $scope.hideAllColumns = function() {
380 $scope.gridColumnPickerIsOpen = false;
381 grid.columnsProvider.hideAllColumns();
382 // note: no need to fetch new data if no columns are visible
385 $scope.toggleColumnVisibility = function(col) {
386 $scope.gridColumnPickerIsOpen = false;
387 col.visible = !col.visible;
389 // egGridFlatDataProvider only retrieves data to be
390 // displayed. When column visibility changes, it's
391 // necessary to fetch the newly visible column data.
392 if (grid.selfManagedData) grid.collect();
395 // save the columns configuration (position, sort, width) to
396 // eg.grid.<persist-key>
397 $scope.saveConfig = function() {
398 $scope.gridColumnPickerIsOpen = false;
400 if (!grid.persistKey) {
402 "Cannot save settings without a grid persist-key");
406 // only store information about visible columns.
407 var conf = grid.columnsProvider.columns.filter(
408 function(col) {return Boolean(col.visible) });
410 // now scrunch the data down to just the needed info
411 conf = conf.map(function(col) {
412 var c = {name : col.name}
413 // Apart from the name, only store non-default values.
414 // No need to store col.visible, since that's implicit
415 if (col.align != 'left') c.align = col.align;
416 if (col.flex != 2) c.flex = col.flex;
417 if (Number(col.sort)) c.sort = Number(c.sort);
421 egCore.hatch.setItem('eg.grid.' + grid.persistKey, conf)
423 // Save operation performed from the grid configuration UI.
424 // Hide the configuration UI and re-draw w/ sort applied
425 if ($scope.showGridConf)
426 $scope.toggleConfDisplay();
431 // load the columns configuration (position, sort, width) from
432 // eg.grid.<persist-key> and apply the loaded settings to the
433 // columns on our columnsProvider
434 grid.loadConfig = function() {
435 if (!grid.persistKey) return $q.when();
437 return egCore.hatch.getItem('eg.grid.' + grid.persistKey)
438 .then(function(conf) {
441 var columns = grid.columnsProvider.columns;
444 angular.forEach(conf, function(col) {
445 var grid_col = columns.filter(
446 function(c) {return c.name == col.name})[0];
449 // saved column does not match a column in the
450 // current grid. skip it.
454 grid_col.align = col.align || 'left';
455 grid_col.flex = col.flex || 2;
456 grid_col.sort = col.sort || 0;
457 // all saved columns are assumed to be true
458 grid_col.visible = true;
460 .filter(function (c) {
461 return c.name == grid_col.name;
464 new_cols.push(grid_col);
467 // columns which are not expressed within the saved
468 // configuration are marked as non-visible and
469 // appended to the end of the new list of columns.
470 angular.forEach(columns, function(col) {
471 var found = conf.filter(
472 function(c) {return (c.name == col.name)})[0];
479 grid.columnsProvider.columns = new_cols;
485 $scope.onContextMenu = function($event) {
486 var col = angular.element($event.target).attr('column');
487 console.log('selected column ' + col);
490 $scope.page = function() {
491 return (grid.offset / grid.limit) + 1;
494 $scope.goToPage = function(page) {
496 if (angular.isNumber(page) && page > 0) {
497 grid.offset = (page - 1) * grid.limit;
502 $scope.offset = function(o) {
503 if (angular.isNumber(o))
508 $scope.limit = function(l) {
509 if (angular.isNumber(l)) {
511 egCore.hatch.setLocalItem('eg.grid.' + grid.persistKey + '.limit', l);
517 $scope.onFirstPage = function() {
518 return grid.offset == 0;
521 $scope.hasNextPage = function() {
522 // we have less data than requested, there must
523 // not be any more pages
524 if (grid.count() < grid.limit) return false;
526 // if the total count is not known, assume that a full
527 // page of data implies more pages are available.
528 if (grid.totalCount == -1) return true;
530 // we have a full page of data, but is there more?
531 return grid.totalCount > (grid.offset + grid.count());
534 $scope.incrementPage = function() {
535 grid.offset += grid.limit;
539 $scope.decrementPage = function() {
540 if (grid.offset < grid.limit) {
543 grid.offset -= grid.limit;
548 // number of items loaded for the current page of results
549 grid.count = function() {
550 return $scope.items.length;
553 // returns the unique identifier value for the provided item
554 // for internal consistency, indexValue is always coerced
556 grid.indexValue = function(item) {
557 if (angular.isObject(item)) {
559 if (angular.isFunction(item[grid.indexField]))
560 return ''+item[grid.indexField]();
561 return ''+item[grid.indexField]; // flat data
564 // passed a non-object; assume it's an index
568 // fires the hide handler function for a context action
569 $scope.actionHide = function(action) {
570 if (typeof action.hide == 'undefined') {
573 if (angular.isFunction(action.hide))
574 return action.hide(action);
578 // fires the disable handler function for a context action
579 $scope.actionDisable = function(action) {
580 if (typeof action.disabled == 'undefined') {
583 if (angular.isFunction(action.disabled))
584 return action.disabled(action);
585 return action.disabled;
588 // fires the action handler function for a context action
589 $scope.actionLauncher = function(action) {
590 if (!action.handler) {
592 'No handler specified for "' + action.label + '"');
596 action.handler(grid.getSelectedItems());
598 console.error('Error executing handler for "'
599 + action.label + '" => ' + E + "\n" + E.stack);
602 if ($scope.action_context_showing) $scope.hideActionContextMenu();
607 $scope.hideActionContextMenu = function () {
608 $($scope.menu_dom).css({
610 width: $scope.action_context_width,
611 top: $scope.action_context_y,
612 left: $scope.action_context_x
614 $($scope.action_context_parent).append($scope.menu_dom);
615 $scope.action_context_oldy = $scope.action_context_oldx = 0;
616 $('body').unbind('click.remove_context_menu_'+$scope.action_context_index);
617 $scope.action_context_showing = false;
620 $scope.action_context_showing = false;
621 $scope.showActionContextMenu = function ($event) {
623 // Have to gather these here, instead of inside link()
624 if (!$scope.menu_dom) $scope.menu_dom = $($scope.grid_element).find('.grid-action-dropdown')[0];
625 if (!$scope.action_context_parent) $scope.action_context_parent = $($scope.menu_dom).parent();
627 if (!grid.getSelectedItems().length) // Nothing selected, fire the click event
628 $event.target.click();
630 if (!$scope.action_context_showing) {
631 $scope.action_context_width = $($scope.menu_dom).css('width');
632 $scope.action_context_y = $($scope.menu_dom).css('top');
633 $scope.action_context_x = $($scope.menu_dom).css('left');
634 $scope.action_context_showing = true;
635 $scope.action_context_index = Math.floor((Math.random() * 1000) + 1);
637 $('body').append($($scope.menu_dom));
638 $('body').bind('click.remove_context_menu_'+$scope.action_context_index, $scope.hideActionContextMenu);
641 $($scope.menu_dom).css({
643 width: $scope.action_context_width,
651 // returns the list of selected item objects
652 grid.getSelectedItems = function() {
653 return $scope.items.filter(
655 return Boolean($scope.selected[grid.indexValue(item)]);
660 grid.getItemByIndex = function(index) {
661 for (var i = 0; i < $scope.items.length; i++) {
662 var item = $scope.items[i];
663 if (grid.indexValue(item) == index)
668 // selects one row after deselecting all of the others
669 grid.selectOneItem = function(index) {
670 $scope.selected = {};
671 $scope.selected[index] = true;
674 // selects or deselects an item, without affecting the others.
675 // returns true if the item is selected; false if de-selected.
676 // we overwrite the object so that we can watch $scope.selected
677 grid.toggleSelectOneItem = function(index) {
678 if ($scope.selected[index]) {
679 delete $scope.selected[index];
680 $scope.selected = angular.copy($scope.selected);
683 $scope.selected[index] = true;
684 $scope.selected = angular.copy($scope.selected);
689 $scope.updateSelected = function () {
690 return $scope.selected = angular.copy($scope.selected);
693 grid.selectAllItems = function() {
694 angular.forEach($scope.items, function(item) {
695 $scope.selected[grid.indexValue(item)] = true
697 $scope.selected = angular.copy($scope.selected);
700 $scope.$watch('selectAll', function(newVal) {
702 grid.selectAllItems();
704 $scope.selected = {};
708 if ($scope.onSelect) {
709 $scope.$watch('selected', function(newVal) {
710 $scope.onSelect(grid.getSelectedItems());
711 if ($scope.afterSelect) $scope.afterSelect();
715 // returns true if item1 appears in the list before item2;
716 // false otherwise. this is slightly more efficient that
717 // finding the position of each then comparing them.
718 // item1 / item2 may be an item or an item index
719 grid.itemComesBefore = function(itemOrIndex1, itemOrIndex2) {
720 var idx1 = grid.indexValue(itemOrIndex1);
721 var idx2 = grid.indexValue(itemOrIndex2);
723 // use for() for early exit
724 for (var i = 0; i < $scope.items.length; i++) {
725 var idx = grid.indexValue($scope.items[i]);
726 if (idx == idx1) return true;
727 if (idx == idx2) return false;
732 // 0-based position of item in the current data set
733 grid.indexOf = function(item) {
734 var idx = grid.indexValue(item);
735 for (var i = 0; i < $scope.items.length; i++) {
736 if (grid.indexValue($scope.items[i]) == idx)
742 grid.modifyColumnFlex = function(column, val) {
744 // prevent flex:0; use hiding instead
748 $scope.modifyColumnFlex = function(col, val) {
749 grid.modifyColumnFlex(col, val);
752 // handles click, control-click, and shift-click
753 $scope.handleRowClick = function($event, item) {
754 var index = grid.indexValue(item);
756 var origSelected = Object.keys($scope.selected);
758 if (!$scope.canMultiSelect) {
759 grid.selectOneItem(index);
760 grid.lastSelectedItemIndex = index;
764 if ($event.ctrlKey || $event.metaKey /* mac command */) {
766 if (grid.toggleSelectOneItem(index))
767 grid.lastSelectedItemIndex = index;
769 } else if ($event.shiftKey) {
772 if (!grid.lastSelectedItemIndex ||
773 index == grid.lastSelectedItemIndex) {
774 grid.selectOneItem(index);
775 grid.lastSelectedItemIndex = index;
779 var selecting = false;
780 var ascending = grid.itemComesBefore(
781 grid.lastSelectedItemIndex, item);
783 grid.indexOf(grid.lastSelectedItemIndex);
785 // update to new last-selected
786 grid.lastSelectedItemIndex = index;
788 // select each row between the last selected and
789 // currently selected items
791 startPos += ascending ? 1 : -1;
792 var curItem = $scope.items[startPos];
794 var curIdx = grid.indexValue(curItem);
795 $scope.selected[curIdx] = true;
796 if (curIdx == index) break; // all done
798 $scope.selected = angular.copy($scope.selected);
802 grid.selectOneItem(index);
803 grid.lastSelectedItemIndex = index;
807 // Builds a sort expression from column sort priorities.
808 // called on page load and any time the priorities are modified.
809 grid.compileSort = function() {
810 var sortList = grid.columnsProvider.columns.filter(
811 function(col) { return Number(col.sort) != 0 }
814 if (Math.abs(a.sort) < Math.abs(b.sort))
820 if (sortList.length) {
821 grid.dataProvider.sort = sortList.map(function(col) {
823 blob[col.name] = col.sort < 0 ? 'desc' : 'asc';
829 // builds a sort expression using a single column,
830 // toggling between ascending and descending sort.
831 $scope.quickSort = function(col_name) {
832 var sort = grid.dataProvider.sort;
833 if (sort && sort.length &&
834 sort[0] == col_name) {
836 blob[col_name] = 'desc';
837 grid.dataProvider.sort = [blob];
839 grid.dataProvider.sort = [col_name];
846 // show / hide the grid configuration row
847 $scope.toggleConfDisplay = function() {
848 if ($scope.showGridConf) {
849 $scope.showGridConf = false;
850 if (grid.columnsProvider.hasSortableColumn()) {
851 // only refresh the grid if the user has the
852 // ability to modify the sort priorities.
858 $scope.showGridConf = true;
861 $scope.gridColumnPickerIsOpen = false;
864 // called when a dragged column is dropped onto itself
865 // or any other column
866 grid.onColumnDrop = function(target) {
867 if (angular.isUndefined(target)) return;
868 if (target == grid.dragColumn) return;
869 var srcIdx, targetIdx, srcCol;
870 angular.forEach(grid.columnsProvider.columns,
872 if (col.name == grid.dragColumn) {
875 } else if (col.name == target) {
881 if (srcIdx < targetIdx) targetIdx--;
883 // move src column from old location to new location in
884 // the columns array, then force a page refresh
885 grid.columnsProvider.columns.splice(srcIdx, 1);
886 grid.columnsProvider.columns.splice(targetIdx, 0, srcCol);
890 // prepares a string for inclusion within a CSV document
891 // by escaping commas and quotes and removing newlines.
892 grid.csvDatum = function(str) {
895 str = str.replace(/\n/g, '');
896 if (str.match(/\,/) || str.match(/"/)) {
897 str = str.replace(/"/g, '""');
898 str = '"' + str + '"';
903 // sets the download file name and inserts the current CSV
904 // into a Blob URL for browser download.
905 $scope.generateCSVExportURL = function() {
906 $scope.gridColumnPickerIsOpen = false;
908 // let the file name describe the grid
909 $scope.csvExportFileName =
910 ($scope.mainLabel || grid.persistKey || 'eg_grid_data')
911 .replace(/\s+/g, '_') + '_' + $scope.page();
913 // toss the CSV into a Blob and update the export URL
914 var csv = grid.generateCSV();
915 var blob = new Blob([csv], {type : 'text/plain'});
916 $scope.csvExportURL =
917 ($window.URL || $window.webkitURL).createObjectURL(blob);
920 $scope.printCSV = function() {
921 $scope.gridColumnPickerIsOpen = false;
924 content : grid.generateCSV(),
925 content_type : 'text/plain'
929 // generates CSV for the currently visible grid contents
930 grid.generateCSV = function() {
932 var colCount = grid.columnsProvider.columns.length;
935 angular.forEach(grid.columnsProvider.columns,
937 if (!col.visible) return;
938 csvStr += grid.csvDatum(col.label);
943 csvStr = csvStr.replace(/,$/,'\n');
946 angular.forEach($scope.items, function(item) {
947 angular.forEach(grid.columnsProvider.columns,
949 if (!col.visible) return;
951 var val = grid.dataProvider.itemFieldValue(item, col);
952 // filtered value (dates, etc.)
953 val = $filter('egGridValueFilter')(val, col);
954 csvStr += grid.csvDatum(val);
958 csvStr = csvStr.replace(/,$/,'\n');
964 // Interpolate the value for column.linkpath within the context
965 // of the row item to generate the final link URL.
966 $scope.generateLinkPath = function(col, item) {
967 return egCore.strings.$replace(col.linkpath, {item : item});
970 // If a column provides its own HTML template, translate it,
971 // using the current item for the template scope.
972 // note: $sce is required to avoid security restrictions and
973 // is OK here, since the template comes directly from a
974 // local HTML template (not user input).
975 $scope.translateCellTemplate = function(col, item) {
976 var html = egCore.strings.$replace(col.template, {item : item});
977 return $sce.trustAsHtml(html);
980 $scope.collect = function() { grid.collect() }
982 // asks the dataProvider for a page of data
983 grid.collect = function() {
985 // avoid firing the collect if there is nothing to collect.
986 if (grid.selfManagedData && !grid.dataProvider.query) return;
988 if (grid.collecting) return; // avoid parallel collect()
989 grid.collecting = true;
991 console.debug('egGrid.collect() offset='
992 + grid.offset + '; limit=' + grid.limit);
994 // ensure all of our dropdowns are closed
995 // TODO: git rid of these and just use dropdown-toggle,
996 // which is more reliable.
997 $scope.gridColumnPickerIsOpen = false;
998 $scope.gridRowCountIsOpen = false;
999 $scope.gridPageSelectIsOpen = false;
1002 $scope.selected = {};
1003 grid.dataProvider.get(grid.offset, grid.limit).then(
1005 if (grid.controls.allItemsRetrieved)
1006 grid.controls.allItemsRetrieved();
1011 $scope.items.push(item)
1012 if (grid.controls.itemRetrieved)
1013 grid.controls.itemRetrieved(item);
1014 if ($scope.selectAll)
1015 $scope.selected[grid.indexValue(item)] = true
1017 }).finally(function() {
1018 console.debug('egGrid.collect() complete');
1019 grid.collecting = false
1020 $scope.selected = angular.copy($scope.selected);
1030 * eg-grid-field : used for collecting custom field data from the templates.
1031 * This directive does not direct display, it just passes data up to the
1034 .directive('egGridField', function() {
1036 require : '^egGrid',
1039 flesher: '=', // optional; function that can flesh a linked field, given the value
1040 name : '@', // required; unique name
1041 path : '@', // optional; flesh path
1042 ignore: '@', // optional; fields to ignore when path is a wildcard
1043 label : '@', // optional; display label
1044 flex : '@', // optional; default flex width
1045 align : '@', // optional; default alignment, left/center/right
1046 dateformat : '@', // optional: passed down to egGridValueFilter
1048 // if a field is part of an IDL object, but we are unable to
1049 // determine the class, because it's nested within a hash
1050 // (i.e. we can't navigate directly to the object via the IDL),
1051 // idlClass lets us specify the class. This is particularly
1052 // useful for nested wildcard fields.
1053 parentIdlClass : '@',
1055 // optional: for non-IDL columns, specifying a datatype
1056 // lets the caller control which display filter is used.
1057 // datatype should match the standard IDL datatypes.
1060 link : function(scope, element, attrs, egGridCtrl) {
1062 // boolean fields are presented as value-less attributes
1071 'required' // if set, always fetch data for this column
1074 if (angular.isDefined(attrs[field]))
1075 scope[field] = true;
1079 // any HTML content within the field is its custom template
1080 var tmpl = element.html();
1081 if (tmpl && !tmpl.match(/^\s*$/))
1082 scope.template = tmpl
1084 egGridCtrl.columnsProvider.add(scope);
1091 * eg-grid-action : used for specifying actions which may be applied
1092 * to items within the grid.
1094 .directive('egGridAction', function() {
1096 require : '^egGrid',
1100 group : '@', // Action group, ungrouped if not set
1101 label : '@', // Action label
1102 handler : '=', // Action function handler
1104 disabled : '=', // function
1107 link : function(scope, element, attrs, egGridCtrl) {
1108 egGridCtrl.addAction({
1110 group : scope.group,
1111 label : scope.label,
1112 divider : scope.divider,
1113 handler : scope.handler,
1114 disabled : scope.disabled,
1121 .factory('egGridColumnsProvider', ['egCore', function(egCore) {
1123 function ColumnsProvider(args) {
1126 cols.stockVisible = [];
1127 cols.idlClass = args.idlClass;
1128 cols.defaultToHidden = args.defaultToHidden;
1129 cols.defaultToNoSort = args.defaultToNoSort;
1130 cols.defaultToNoMultiSort = args.defaultToNoMultiSort;
1132 // resets column width, visibility, and sort behavior
1133 // Visibility resets to the visibility settings defined in the
1134 // template (i.e. the original egGridField values).
1135 cols.reset = function() {
1136 angular.forEach(cols.columns, function(col) {
1140 if (cols.stockVisible.indexOf(col.name) > -1) {
1143 col.visible = false;
1148 // returns true if any columns are sortable
1149 cols.hasSortableColumn = function() {
1150 return cols.columns.filter(
1152 return col.sortable || col.multisortable;
1157 cols.showAllColumns = function() {
1158 angular.forEach(cols.columns, function(column) {
1159 column.visible = true;
1163 cols.hideAllColumns = function() {
1164 angular.forEach(cols.columns, function(col) {
1169 cols.indexOf = function(name) {
1170 for (var i = 0; i < cols.columns.length; i++) {
1171 if (cols.columns[i].name == name)
1177 cols.findColumn = function(name) {
1178 return cols.columns[cols.indexOf(name)];
1181 cols.compileAutoColumns = function() {
1182 var idl_class = egCore.idl.classes[cols.idlClass];
1187 if (field.virtual) return;
1188 if (field.datatype == 'link' || field.datatype == 'org_unit') {
1189 // if the field is a link and the linked class has a
1190 // "selector" field specified, use the selector field
1191 // as the display field for the columns.
1192 // flattener will take care of the fleshing.
1193 if (field['class']) {
1194 var selector_field = egCore.idl.classes[field['class']].fields
1195 .filter(function(f) { return Boolean(f.selector) })[0];
1196 if (selector_field) {
1197 field.path = field.name + '.' + selector_field.selector;
1201 cols.add(field, true);
1206 // if a column definition has a path with a wildcard, create
1207 // columns for all non-virtual fields at the specified
1208 // position in the path.
1209 cols.expandPath = function(colSpec) {
1211 var ignoreList = [];
1213 ignoreList = colSpec.ignore.split(' ');
1215 var dotpath = colSpec.path.replace(/\.?\*$/,'');
1219 if (colSpec.parentIdlClass) {
1220 class_obj = egCore.idl.classes[colSpec.parentIdlClass];
1222 class_obj = egCore.idl.classes[cols.idlClass];
1224 var idl_parent = class_obj;
1225 var old_field_label = '';
1227 if (!class_obj) return;
1229 console.debug('egGrid: auto dotpath is: ' + dotpath);
1230 var path_parts = dotpath.split(/\./);
1232 // find the IDL class definition for the last element in the
1233 // path before the .*
1234 // an empty path_parts means expand the root class
1237 for (var path_idx in path_parts) {
1238 old_field = idl_field;
1240 var part = path_parts[path_idx];
1241 idl_field = class_obj.field_map[part];
1243 // unless we're at the end of the list, this field should
1244 // link to another class.
1245 if (idl_field && idl_field['class'] && (
1246 idl_field.datatype == 'link' ||
1247 idl_field.datatype == 'org_unit')) {
1248 if (old_field_label) old_field_label += ' : ';
1249 old_field_label += idl_field.label;
1250 class_obj = egCore.idl.classes[idl_field['class']];
1251 if (old_field) idl_parent = old_field;
1253 if (path_idx < (path_parts.length - 1)) {
1254 // we ran out of classes to hop through before
1255 // we ran out of path components
1256 console.error("egGrid: invalid IDL path: " + dotpath);
1263 angular.forEach(class_obj.fields, function(field) {
1265 // Only show wildcard fields where we have data to show
1266 // Virtual and un-fleshed links will not have any data.
1267 if (field.virtual ||
1268 (field.datatype == 'link' || field.datatype == 'org_unit') ||
1269 ignoreList.indexOf(field.name) > -1
1273 var col = cols.cloneFromScope(colSpec);
1274 col.path = (dotpath ? dotpath + '.' + field.name : field.name);
1276 // log line below is very chatty. disable until needed.
1277 // console.debug('egGrid: field: ' +field.name + '; parent field: ' + js2JSON(idl_parent));
1278 cols.add(col, false, true,
1279 {idl_parent : idl_parent, idl_field : field, idl_class : class_obj, field_parent_label : old_field_label });
1282 cols.columns = cols.columns.sort(
1284 if (a.explicit) return -1;
1285 if (b.explicit) return 1;
1287 if (a.idlclass && b.idlclass) {
1288 if (a.idlclass < b.idlclass) return -1;
1289 if (b.idlclass < a.idlclass) return 1;
1292 if (a.path && b.path && a.path.lastIndexOf('.') && b.path.lastIndexOf('.')) {
1293 if (a.path.substring(0, a.path.lastIndexOf('.')) < b.path.substring(0, b.path.lastIndexOf('.'))) return -1;
1294 if (b.path.substring(0, b.path.lastIndexOf('.')) < a.path.substring(0, a.path.lastIndexOf('.'))) return 1;
1297 if (a.label && b.label) {
1298 if (a.label < b.label) return -1;
1299 if (b.label < a.label) return 1;
1302 return a.name < b.name ? -1 : 1;
1309 "egGrid: wildcard path does not resolve to an object: "
1314 // angular.clone(scopeObject) is not permittable. Manually copy
1315 // the fields over that we need (so the scope object can go away).
1316 cols.cloneFromScope = function(colSpec) {
1318 flesher : colSpec.flesher,
1319 name : colSpec.name,
1320 label : colSpec.label,
1321 path : colSpec.path,
1322 align : colSpec.align || 'left',
1323 flex : Number(colSpec.flex) || 2,
1324 sort : Number(colSpec.sort) || 0,
1325 required : colSpec.required,
1326 linkpath : colSpec.linkpath,
1327 template : colSpec.template,
1328 visible : colSpec.visible,
1329 hidden : colSpec.hidden,
1330 datatype : colSpec.datatype,
1331 sortable : colSpec.sortable,
1332 nonsortable : colSpec.nonsortable,
1333 multisortable : colSpec.multisortable,
1334 nonmultisortable : colSpec.nonmultisortable,
1335 dateformat : colSpec.dateformat,
1336 parentIdlClass : colSpec.parentIdlClass
1341 // Add a column to the columns collection.
1342 // Columns may come from a slim eg-columns-field or
1343 // directly from the IDL.
1344 cols.add = function(colSpec, fromIDL, fromExpand, idl_info) {
1346 // First added column with the specified path takes precedence.
1347 // This allows for specific definitions followed by wildcard
1348 // definitions. If a match is found, back out.
1349 if (cols.columns.filter(function(c) {
1350 return (c.path == colSpec.path) })[0]) {
1351 console.debug('skipping pre-existing column ' + colSpec.path);
1355 var column = fromExpand ? colSpec : cols.cloneFromScope(colSpec);
1357 if (column.path && column.path.match(/\*$/))
1358 return cols.expandPath(colSpec);
1360 if (!fromExpand) column.explicit = true;
1362 if (!column.name) column.name = column.path;
1363 if (!column.path) column.path = column.name;
1365 if (column.visible || (!cols.defaultToHidden && !column.hidden))
1366 column.visible = true;
1368 if (column.sortable || (!cols.defaultToNoSort && !column.nonsortable))
1369 column.sortable = true;
1371 if (column.multisortable ||
1372 (!cols.defaultToNoMultiSort && !column.nonmultisortable))
1373 column.multisortable = true;
1375 cols.columns.push(column);
1377 // Track which columns are visible by default in case we
1378 // need to reset column visibility
1380 cols.stockVisible.push(column.name);
1382 if (fromIDL) return; // directly from egIDL. nothing left to do.
1384 // lookup the matching IDL field
1385 if (!idl_info && cols.idlClass)
1386 idl_info = cols.idlFieldFromPath(column.path);
1389 // column is not represented within the IDL
1390 column.adhoc = true;
1394 column.datatype = idl_info.idl_field.datatype;
1396 if (!column.label) {
1397 column.label = idl_info.idl_field.label || column.name;
1400 if (fromExpand && idl_info.idl_class) {
1401 column.idlclass = '';
1402 if (idl_info.field_parent_label && idl_info.idl_parent.label != idl_info.idl_class.label) {
1403 column.idlclass = (idl_info.field_parent_label || idl_info.idl_parent.label || idl_info.idl_parent.name);
1405 column.idlclass += idl_info.idl_class.label || idl_info.idl_class.name;
1410 // finds the IDL field from the dotpath, using the columns
1411 // idlClass as the base.
1412 cols.idlFieldFromPath = function(dotpath) {
1413 var class_obj = egCore.idl.classes[cols.idlClass];
1414 var path_parts = dotpath.split(/\./);
1418 for (var path_idx in path_parts) {
1419 var part = path_parts[path_idx];
1420 idl_parent = idl_field;
1421 idl_field = class_obj.field_map[part];
1423 if (idl_field && idl_field['class'] && (
1424 idl_field.datatype == 'link' ||
1425 idl_field.datatype == 'org_unit')) {
1426 class_obj = egCore.idl.classes[idl_field['class']];
1428 // else, path is not in the IDL, which is fine
1431 if (!idl_field) return null;
1434 idl_parent: idl_parent,
1435 idl_field : idl_field,
1436 idl_class : class_obj
1442 instance : function(args) { return new ColumnsProvider(args) }
1448 * Generic data provider template class. This is basically an abstract
1449 * class factory service whose instances can be locally modified to
1450 * meet the needs of each individual grid.
1452 .factory('egGridDataProvider',
1453 ['$q','$timeout','$filter','egCore',
1454 function($q , $timeout , $filter , egCore) {
1456 function GridDataProvider(args) {
1457 var gridData = this;
1458 if (!args) args = {};
1461 gridData.get = args.get;
1462 gridData.query = args.query;
1463 gridData.idlClass = args.idlClass;
1464 gridData.columnsProvider = args.columnsProvider;
1466 // Delivers a stream of array data via promise.notify()
1467 // Useful for passing an array of data to egGrid.get()
1468 // If a count is provided, the array will be trimmed to
1469 // the range defined by count and offset
1470 gridData.arrayNotifier = function(arr, offset, count) {
1471 if (!arr || arr.length == 0) return $q.when();
1472 if (count) arr = arr.slice(offset, offset + count);
1473 var def = $q.defer();
1474 // promise notifications are only witnessed when delivered
1475 // after the caller has his hands on the promise object
1476 $timeout(function() {
1477 angular.forEach(arr, def.notify);
1483 // Calls the grid refresh function. Once instantiated, the
1484 // grid will replace this function with it's own refresh()
1485 gridData.refresh = function(noReset) { }
1487 if (!gridData.get) {
1488 // returns a promise whose notify() delivers items
1489 gridData.get = function(index, count) {
1490 console.error("egGridDataProvider.get() not implemented");
1494 // attempts a flat field lookup first. If the column is not
1495 // found on the top-level object, attempts a nested lookup
1496 // TODO: consider a caching layer to speed up template
1497 // rendering, particularly for nested objects?
1498 gridData.itemFieldValue = function(item, column) {
1500 if (column.name in item) {
1501 if (typeof item[column.name] == 'function') {
1502 val = item[column.name]();
1504 val = item[column.name];
1507 val = gridData.nestedItemFieldValue(item, column);
1513 // TODO: deprecate me
1514 gridData.flatItemFieldValue = function(item, column) {
1515 console.warn('gridData.flatItemFieldValue deprecated; '
1516 + 'leave provider.itemFieldValue unset');
1517 return item[column.name];
1520 // given an object and a dot-separated path to a field,
1521 // extract the value of the field. The path can refer
1522 // to function names or object attributes. If the final
1523 // value is an IDL field, run the value through its
1524 // corresponding output filter.
1525 gridData.nestedItemFieldValue = function(obj, column) {
1526 item = obj; // keep a copy around
1528 if (obj === null || obj === undefined || obj === '') return '';
1529 if (!column.path) return obj;
1532 var parts = column.path.split('.');
1534 angular.forEach(parts, function(step, idx) {
1535 // object is not fleshed to the expected extent
1536 if (typeof obj != 'object') {
1537 if (typeof obj != 'undefined' && column.flesher) {
1538 obj = column.flesher(obj, column, item);
1545 if (!obj) return '';
1547 var cls = obj.classname;
1548 if (cls && (class_obj = egCore.idl.classes[cls])) {
1549 idl_field = class_obj.field_map[step];
1550 obj = obj[step] ? obj[step]() : '';
1552 if (angular.isFunction(obj[step])) {
1560 // We found a nested IDL object which may or may not have
1561 // been configured as a top-level column. Grab the datatype.
1562 if (idl_field && !column.datatype)
1563 column.datatype = idl_field.datatype;
1565 if (obj === null || obj === undefined || obj === '') return '';
1571 instance : function(args) {
1572 return new GridDataProvider(args);
1579 // Factory service for egGridDataManager instances, which are
1580 // responsible for collecting flattened grid data.
1581 .factory('egGridFlatDataProvider',
1582 ['$q','egCore','egGridDataProvider',
1583 function($q , egCore , egGridDataProvider) {
1586 instance : function(args) {
1587 var provider = egGridDataProvider.instance(args);
1589 provider.get = function(offset, count) {
1591 // no query means no call
1592 if (!provider.query ||
1593 angular.equals(provider.query, {}))
1596 // find all of the currently visible columns
1597 var queryFields = {}
1598 angular.forEach(provider.columnsProvider.columns,
1600 // only query IDL-tracked columns
1601 if (!col.adhoc && (col.required || col.visible))
1602 queryFields[col.name] = col.path;
1606 return egCore.net.request(
1608 'open-ils.fielder.flattened_search',
1609 egCore.auth.token(), provider.idlClass,
1610 queryFields, provider.query,
1611 { sort : provider.sort,
1617 //provider.itemFieldValue = provider.flatItemFieldValue;
1624 .directive('egGridColumnDragSource', function() {
1627 require : '^egGrid',
1628 link : function(scope, element, attrs, egGridCtrl) {
1629 angular.element(element).attr('draggable', 'true');
1631 element.bind('dragstart', function(e) {
1632 egGridCtrl.dragColumn = attrs.column;
1633 egGridCtrl.dragType = attrs.dragType || 'move'; // or resize
1634 egGridCtrl.colResizeDir = 0;
1636 if (egGridCtrl.dragType == 'move') {
1637 // style the column getting moved
1638 angular.element(e.target).addClass(
1639 'eg-grid-column-move-handle-active');
1643 element.bind('dragend', function(e) {
1644 if (egGridCtrl.dragType == 'move') {
1645 angular.element(e.target).removeClass(
1646 'eg-grid-column-move-handle-active');
1653 .directive('egGridColumnDragDest', function() {
1656 require : '^egGrid',
1657 link : function(scope, element, attrs, egGridCtrl) {
1659 element.bind('dragover', function(e) { // required for drop
1660 e.stopPropagation();
1662 e.dataTransfer.dropEffect = 'move';
1664 if (egGridCtrl.colResizeDir == 0) return; // move
1666 var cols = egGridCtrl.columnsProvider;
1667 var srcCol = egGridCtrl.dragColumn;
1668 var srcColIdx = cols.indexOf(srcCol);
1670 if (egGridCtrl.colResizeDir == -1) {
1671 if (cols.indexOf(attrs.column) <= srcColIdx) {
1672 egGridCtrl.modifyColumnFlex(
1673 egGridCtrl.columnsProvider.findColumn(
1674 egGridCtrl.dragColumn), -1);
1675 if (cols.columns[srcColIdx+1]) {
1676 // source column shrinks by one, column to the
1677 // right grows by one.
1678 egGridCtrl.modifyColumnFlex(
1679 cols.columns[srcColIdx+1], 1);
1684 if (cols.indexOf(attrs.column) > srcColIdx) {
1685 egGridCtrl.modifyColumnFlex(
1686 egGridCtrl.columnsProvider.findColumn(
1687 egGridCtrl.dragColumn), 1);
1688 if (cols.columns[srcColIdx+1]) {
1689 // source column grows by one, column to the
1690 // right grows by one.
1691 egGridCtrl.modifyColumnFlex(
1692 cols.columns[srcColIdx+1], -1);
1700 element.bind('dragenter', function(e) {
1701 e.stopPropagation();
1703 if (egGridCtrl.dragType == 'move') {
1704 angular.element(e.target).addClass('eg-grid-col-hover');
1706 // resize grips are on the right side of each column.
1707 // dragenter will either occur on the source column
1708 // (dragging left) or the column to the right.
1709 if (egGridCtrl.colResizeDir == 0) {
1710 if (egGridCtrl.dragColumn == attrs.column) {
1711 egGridCtrl.colResizeDir = -1; // west
1713 egGridCtrl.colResizeDir = 1; // east
1719 element.bind('dragleave', function(e) {
1720 e.stopPropagation();
1722 if (egGridCtrl.dragType == 'move') {
1723 angular.element(e.target).removeClass('eg-grid-col-hover');
1727 element.bind('drop', function(e) {
1728 e.stopPropagation();
1730 egGridCtrl.colResizeDir = 0;
1731 if (egGridCtrl.dragType == 'move') {
1732 angular.element(e.target).removeClass('eg-grid-col-hover');
1733 egGridCtrl.onColumnDrop(attrs.column); // move the column
1740 .directive('egGridMenuItem', function() {
1743 require : '^egGrid',
1749 handler : '=', // onclick handler function
1750 divider : '=', // if true, show a divider only
1751 handlerData : '=', // if set, passed as second argument to handler
1752 disabled : '=', // function
1753 hidden : '=' // function
1755 link : function(scope, element, attrs, egGridCtrl) {
1756 egGridCtrl.addMenuItem({
1757 checkbox : scope.checkbox,
1758 checked : scope.checked ? true : false,
1759 label : scope.label,
1760 standalone : scope.standalone ? true : false,
1761 handler : scope.handler,
1762 divider : scope.divider,
1763 disabled : scope.disabled,
1764 hidden : scope.hidden,
1765 handlerData : scope.handlerData
1775 * Translates bare IDL object values into display values.
1776 * 1. Passes dates through the angular date filter
1777 * 2. Translates bools to Booleans so the browser can display translated
1778 * value. (Though we could manually translate instead..)
1779 * Others likely to follow...
1781 .filter('egGridValueFilter', ['$filter', function($filter) {
1782 return function(value, column) {
1783 switch(column.datatype) {
1786 // Browser will translate true/false for us
1788 case '1' : // legacy
1792 case '0' : // legacy
1795 // value may be null, '', etc.
1796 default : return '';
1799 // canned angular date filter FTW
1800 if (!column.dateformat)
1801 column.dateformat = 'shortDate';
1802 return $filter('date')(value, column.dateformat);
1804 return $filter('currency')(value);