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 var features = ($scope.features) ?
131 $scope.features.split(',') : [];
132 delete $scope.features;
134 $scope.showIndex = (features.indexOf('-index') == -1);
136 $scope.allowAll = (features.indexOf('allowAll') > -1);
137 $scope.startSelected = $scope.selectAll = (features.indexOf('startSelected') > -1);
138 $scope.showActions = (features.indexOf('-actions') == -1);
139 $scope.showPagination = (features.indexOf('-pagination') == -1);
140 $scope.showPicker = (features.indexOf('-picker') == -1);
142 $scope.showMenu = (features.indexOf('-menu') == -1);
144 // remove some unneeded values from the scope to reduce bloat
146 grid.idlClass = $scope.idlClass;
147 delete $scope.idlClass;
149 grid.persistKey = $scope.persistKey;
150 delete $scope.persistKey;
152 var stored_limit = 0;
153 if ($scope.showPagination) {
154 if (grid.persistKey) {
155 var stored_limit = Number(
156 egCore.hatch.getLocalItem('eg.grid.' + grid.persistKey + '.limit')
160 stored_limit = 10000; // maybe support "Inf"?
163 grid.limit = Number(stored_limit) || Number($scope.pageSize) || 25;
165 grid.indexField = $scope.idField;
166 delete $scope.idField;
168 grid.dataProvider = $scope.itemsProvider;
170 if (!grid.indexField && grid.idlClass)
171 grid.indexField = egCore.idl.classes[grid.idlClass].pkey;
173 grid.columnsProvider = egGridColumnsProvider.instance({
174 idlClass : grid.idlClass,
175 defaultToHidden : (features.indexOf('-display') > -1),
176 defaultToNoSort : (features.indexOf('-sort') > -1),
177 defaultToNoMultiSort : (features.indexOf('-multisort') > -1)
179 $scope.canMultiSelect = (features.indexOf('-multiselect') == -1);
181 $scope.handleAutoFields = function() {
182 if ($scope.autoFields) {
183 if (grid.autoLabel) {
185 egCore.idl.classes[grid.idlClass].label;
187 grid.columnsProvider.compileAutoColumns();
188 delete $scope.autoFields;
192 if (!grid.dataProvider) {
193 // no provider, um, provided.
194 // Use a flat data provider
196 grid.selfManagedData = true;
197 grid.dataProvider = egGridFlatDataProvider.instance({
198 indexField : grid.indexField,
199 idlClass : grid.idlClass,
200 columnsProvider : grid.columnsProvider,
205 $scope.itemFieldValue = grid.dataProvider.itemFieldValue;
206 $scope.indexValue = function(item) {
207 return grid.indexValue(item)
210 grid.applyControlFunctions();
212 grid.loadConfig().then(function() {
213 // link columns to scope after loadConfig(), since it
214 // replaces the columns array.
215 $scope.columns = grid.columnsProvider.columns;
218 // NOTE: grid.collect() is first called from link(), not here.
221 // link our control functions into the gridControls
222 // scope object so the caller can access them.
223 grid.applyControlFunctions = function() {
225 // we use some of these controls internally, so sett
226 // them up even if the caller doesn't request them.
227 var controls = $scope.gridControls || {};
229 controls.columnMap = function() {
231 angular.forEach(grid.columnsProvider.columns, function (c) {
237 controls.columnsProvider = function() {
238 return grid.columnsProvider;
241 // link in the control functions
242 controls.selectedItems = function() {
243 return grid.getSelectedItems()
246 controls.allItems = function() {
250 controls.selectItems = function(ids) {
252 $scope.selected = {};
253 angular.forEach(ids, function(i) {
254 $scope.selected[''+i] = true;
258 // if the caller provided a functional setQuery,
259 // extract the value before replacing it
260 if (controls.setQuery) {
261 grid.dataProvider.query =
265 controls.setQuery = function(query) {
266 grid.dataProvider.query = query;
270 if (controls.watchQuery) {
271 // capture the initial query value
272 grid.dataProvider.query = controls.watchQuery();
275 $scope.gridWatchQuery = controls.watchQuery;
276 $scope.$watch('gridWatchQuery()', function(newv) {
277 controls.setQuery(newv);
281 // if the caller provided a functional setSort
282 // extract the value before replacing it
283 grid.dataProvider.sort =
284 controls.setSort ? controls.setSort() : [];
286 controls.setSort = function(sort) {
290 controls.refresh = function(noReset) {
291 if (!noReset) grid.offset = 0;
295 controls.setLimit = function(limit,forget) {
296 if (!forget && grid.persistKey)
297 egCore.hatch.setLocalItem('eg.grid.' + grid.persistKey + '.limit', limit);
300 controls.getLimit = function() {
303 controls.setOffset = function(offset) {
304 grid.offset = offset;
306 controls.getOffset = function() {
310 controls.saveConfig = function () {
311 return $scope.saveConfig();
314 grid.dataProvider.refresh = controls.refresh;
315 grid.controls = controls;
318 // If a menu item provides its own HTML template, translate it,
319 // using the menu item for the template scope.
320 // note: $sce is required to avoid security restrictions and
321 // is OK here, since the template comes directly from a
322 // local HTML template (not user input).
323 $scope.translateMenuItemTemplate = function(item) {
324 var html = egCore.strings.$replace(item.template, {item : item});
325 return $sce.trustAsHtml(html);
328 // add a new (global) grid menu item
329 grid.addMenuItem = function(item) {
330 $scope.menuItems.push(item);
331 var handler = item.handler;
332 item.handler = function() {
333 $scope.gridMenuIsOpen = false; // close menu
336 item.handlerData, grid.getSelectedItems());
341 // add a selected-items action
342 grid.addAction = function(act) {
344 $scope.actionGroups.forEach(function(g){
345 if (g.label === act.group) {
351 $scope.actionGroups.push({
358 // remove the stored column configuration preferenc, then recover
359 // the column visibility information from the initial page load.
360 $scope.resetColumns = function() {
361 $scope.gridColumnPickerIsOpen = false;
362 egCore.hatch.removeItem('eg.grid.' + grid.persistKey)
364 grid.columnsProvider.reset();
365 if (grid.selfManagedData) grid.collect();
369 $scope.showAllColumns = function() {
370 $scope.gridColumnPickerIsOpen = false;
371 grid.columnsProvider.showAllColumns();
372 if (grid.selfManagedData) grid.collect();
375 $scope.hideAllColumns = function() {
376 $scope.gridColumnPickerIsOpen = false;
377 grid.columnsProvider.hideAllColumns();
378 // note: no need to fetch new data if no columns are visible
381 $scope.toggleColumnVisibility = function(col) {
382 $scope.gridColumnPickerIsOpen = false;
383 col.visible = !col.visible;
385 // egGridFlatDataProvider only retrieves data to be
386 // displayed. When column visibility changes, it's
387 // necessary to fetch the newly visible column data.
388 if (grid.selfManagedData) grid.collect();
391 // save the columns configuration (position, sort, width) to
392 // eg.grid.<persist-key>
393 $scope.saveConfig = function() {
394 $scope.gridColumnPickerIsOpen = false;
396 if (!grid.persistKey) {
398 "Cannot save settings without a grid persist-key");
402 // only store information about visible columns.
403 var conf = grid.columnsProvider.columns.filter(
404 function(col) {return Boolean(col.visible) });
406 // now scrunch the data down to just the needed info
407 conf = conf.map(function(col) {
408 var c = {name : col.name}
409 // Apart from the name, only store non-default values.
410 // No need to store col.visible, since that's implicit
411 if (col.align != 'left') c.align = col.align;
412 if (col.flex != 2) c.flex = col.flex;
413 if (Number(col.sort)) c.sort = Number(c.sort);
417 egCore.hatch.setItem('eg.grid.' + grid.persistKey, conf)
419 // Save operation performed from the grid configuration UI.
420 // Hide the configuration UI and re-draw w/ sort applied
421 if ($scope.showGridConf)
422 $scope.toggleConfDisplay();
427 // load the columns configuration (position, sort, width) from
428 // eg.grid.<persist-key> and apply the loaded settings to the
429 // columns on our columnsProvider
430 grid.loadConfig = function() {
431 if (!grid.persistKey) return $q.when();
433 return egCore.hatch.getItem('eg.grid.' + grid.persistKey)
434 .then(function(conf) {
437 var columns = grid.columnsProvider.columns;
440 angular.forEach(conf, function(col) {
441 var grid_col = columns.filter(
442 function(c) {return c.name == col.name})[0];
445 // saved column does not match a column in the
446 // current grid. skip it.
450 grid_col.align = col.align || 'left';
451 grid_col.flex = col.flex || 2;
452 grid_col.sort = col.sort || 0;
453 // all saved columns are assumed to be true
454 grid_col.visible = true;
456 .filter(function (c) {
457 return c.name == grid_col.name;
460 new_cols.push(grid_col);
463 // columns which are not expressed within the saved
464 // configuration are marked as non-visible and
465 // appended to the end of the new list of columns.
466 angular.forEach(columns, function(col) {
467 var found = conf.filter(
468 function(c) {return (c.name == col.name)})[0];
475 grid.columnsProvider.columns = new_cols;
481 $scope.onContextMenu = function($event) {
482 var col = angular.element($event.target).attr('column');
483 console.log('selected column ' + col);
486 $scope.page = function() {
487 return (grid.offset / grid.limit) + 1;
490 $scope.goToPage = function(page) {
492 if (angular.isNumber(page) && page > 0) {
493 grid.offset = (page - 1) * grid.limit;
498 $scope.offset = function(o) {
499 if (angular.isNumber(o))
504 $scope.limit = function(l) {
505 if (angular.isNumber(l)) {
507 egCore.hatch.setLocalItem('eg.grid.' + grid.persistKey + '.limit', l);
513 $scope.onFirstPage = function() {
514 return grid.offset == 0;
517 $scope.hasNextPage = function() {
518 // we have less data than requested, there must
519 // not be any more pages
520 if (grid.count() < grid.limit) return false;
522 // if the total count is not known, assume that a full
523 // page of data implies more pages are available.
524 if (grid.totalCount == -1) return true;
526 // we have a full page of data, but is there more?
527 return grid.totalCount > (grid.offset + grid.count());
530 $scope.incrementPage = function() {
531 grid.offset += grid.limit;
535 $scope.decrementPage = function() {
536 if (grid.offset < grid.limit) {
539 grid.offset -= grid.limit;
544 // number of items loaded for the current page of results
545 grid.count = function() {
546 return $scope.items.length;
549 // returns the unique identifier value for the provided item
550 // for internal consistency, indexValue is always coerced
552 grid.indexValue = function(item) {
553 if (angular.isObject(item)) {
555 if (angular.isFunction(item[grid.indexField]))
556 return ''+item[grid.indexField]();
557 return ''+item[grid.indexField]; // flat data
560 // passed a non-object; assume it's an index
564 // fires the hide handler function for a context action
565 $scope.actionHide = function(action) {
566 if (typeof action.hide == 'undefined') {
569 if (angular.isFunction(action.hide))
570 return action.hide(action);
574 // fires the disable handler function for a context action
575 $scope.actionDisable = function(action) {
576 if (typeof action.disabled == 'undefined') {
579 if (angular.isFunction(action.disabled))
580 return action.disabled(action);
581 return action.disabled;
584 // fires the action handler function for a context action
585 $scope.actionLauncher = function(action) {
586 if (!action.handler) {
588 'No handler specified for "' + action.label + '"');
592 action.handler(grid.getSelectedItems());
594 console.error('Error executing handler for "'
595 + action.label + '" => ' + E + "\n" + E.stack);
598 if ($scope.action_context_showing) $scope.hideActionContextMenu();
603 $scope.hideActionContextMenu = function () {
604 $($scope.menu_dom).css({
606 width: $scope.action_context_width,
607 top: $scope.action_context_y,
608 left: $scope.action_context_x
610 $($scope.action_context_parent).append($scope.menu_dom);
611 $scope.action_context_oldy = $scope.action_context_oldx = 0;
612 $('body').unbind('click.remove_context_menu_'+$scope.action_context_index);
613 $scope.action_context_showing = false;
616 $scope.action_context_showing = false;
617 $scope.showActionContextMenu = function ($event) {
619 // Have to gather these here, instead of inside link()
620 if (!$scope.menu_dom) $scope.menu_dom = $($scope.grid_element).find('.grid-action-dropdown')[0];
621 if (!$scope.action_context_parent) $scope.action_context_parent = $($scope.menu_dom).parent();
623 if (!grid.getSelectedItems().length) // Nothing selected, fire the click event
624 $event.target.click();
626 if (!$scope.action_context_showing) {
627 $scope.action_context_width = $($scope.menu_dom).css('width');
628 $scope.action_context_y = $($scope.menu_dom).css('top');
629 $scope.action_context_x = $($scope.menu_dom).css('left');
630 $scope.action_context_showing = true;
631 $scope.action_context_index = Math.floor((Math.random() * 1000) + 1);
633 $('body').append($($scope.menu_dom));
634 $('body').bind('click.remove_context_menu_'+$scope.action_context_index, $scope.hideActionContextMenu);
637 $($scope.menu_dom).css({
639 width: $scope.action_context_width,
647 // returns the list of selected item objects
648 grid.getSelectedItems = function() {
649 return $scope.items.filter(
651 return Boolean($scope.selected[grid.indexValue(item)]);
656 grid.getItemByIndex = function(index) {
657 for (var i = 0; i < $scope.items.length; i++) {
658 var item = $scope.items[i];
659 if (grid.indexValue(item) == index)
664 // selects one row after deselecting all of the others
665 grid.selectOneItem = function(index) {
666 $scope.selected = {};
667 $scope.selected[index] = true;
670 // selects or deselects an item, without affecting the others.
671 // returns true if the item is selected; false if de-selected.
672 // we overwrite the object so that we can watch $scope.selected
673 grid.toggleSelectOneItem = function(index) {
674 if ($scope.selected[index]) {
675 delete $scope.selected[index];
676 $scope.selected = angular.copy($scope.selected);
679 $scope.selected[index] = true;
680 $scope.selected = angular.copy($scope.selected);
685 $scope.updateSelected = function () {
686 return $scope.selected = angular.copy($scope.selected);
689 grid.selectAllItems = function() {
690 angular.forEach($scope.items, function(item) {
691 $scope.selected[grid.indexValue(item)] = true
693 $scope.selected = angular.copy($scope.selected);
696 $scope.$watch('selectAll', function(newVal) {
698 grid.selectAllItems();
700 $scope.selected = {};
704 if ($scope.onSelect) {
705 $scope.$watch('selected', function(newVal) {
706 $scope.onSelect(grid.getSelectedItems());
707 if ($scope.afterSelect) $scope.afterSelect();
711 // returns true if item1 appears in the list before item2;
712 // false otherwise. this is slightly more efficient that
713 // finding the position of each then comparing them.
714 // item1 / item2 may be an item or an item index
715 grid.itemComesBefore = function(itemOrIndex1, itemOrIndex2) {
716 var idx1 = grid.indexValue(itemOrIndex1);
717 var idx2 = grid.indexValue(itemOrIndex2);
719 // use for() for early exit
720 for (var i = 0; i < $scope.items.length; i++) {
721 var idx = grid.indexValue($scope.items[i]);
722 if (idx == idx1) return true;
723 if (idx == idx2) return false;
728 // 0-based position of item in the current data set
729 grid.indexOf = function(item) {
730 var idx = grid.indexValue(item);
731 for (var i = 0; i < $scope.items.length; i++) {
732 if (grid.indexValue($scope.items[i]) == idx)
738 grid.modifyColumnFlex = function(column, val) {
740 // prevent flex:0; use hiding instead
744 $scope.modifyColumnFlex = function(col, val) {
745 grid.modifyColumnFlex(col, val);
748 // handles click, control-click, and shift-click
749 $scope.handleRowClick = function($event, item) {
750 var index = grid.indexValue(item);
752 var origSelected = Object.keys($scope.selected);
754 if (!$scope.canMultiSelect) {
755 grid.selectOneItem(index);
756 grid.lastSelectedItemIndex = index;
760 if ($event.ctrlKey || $event.metaKey /* mac command */) {
762 if (grid.toggleSelectOneItem(index))
763 grid.lastSelectedItemIndex = index;
765 } else if ($event.shiftKey) {
768 if (!grid.lastSelectedItemIndex ||
769 index == grid.lastSelectedItemIndex) {
770 grid.selectOneItem(index);
771 grid.lastSelectedItemIndex = index;
775 var selecting = false;
776 var ascending = grid.itemComesBefore(
777 grid.lastSelectedItemIndex, item);
779 grid.indexOf(grid.lastSelectedItemIndex);
781 // update to new last-selected
782 grid.lastSelectedItemIndex = index;
784 // select each row between the last selected and
785 // currently selected items
787 startPos += ascending ? 1 : -1;
788 var curItem = $scope.items[startPos];
790 var curIdx = grid.indexValue(curItem);
791 $scope.selected[curIdx] = true;
792 if (curIdx == index) break; // all done
794 $scope.selected = angular.copy($scope.selected);
798 grid.selectOneItem(index);
799 grid.lastSelectedItemIndex = index;
803 // Builds a sort expression from column sort priorities.
804 // called on page load and any time the priorities are modified.
805 grid.compileSort = function() {
806 var sortList = grid.columnsProvider.columns.filter(
807 function(col) { return Number(col.sort) != 0 }
810 if (Math.abs(a.sort) < Math.abs(b.sort))
816 if (sortList.length) {
817 grid.dataProvider.sort = sortList.map(function(col) {
819 blob[col.name] = col.sort < 0 ? 'desc' : 'asc';
825 // builds a sort expression using a single column,
826 // toggling between ascending and descending sort.
827 $scope.quickSort = function(col_name) {
828 var sort = grid.dataProvider.sort;
829 if (sort && sort.length &&
830 sort[0] == col_name) {
832 blob[col_name] = 'desc';
833 grid.dataProvider.sort = [blob];
835 grid.dataProvider.sort = [col_name];
842 // show / hide the grid configuration row
843 $scope.toggleConfDisplay = function() {
844 if ($scope.showGridConf) {
845 $scope.showGridConf = false;
846 if (grid.columnsProvider.hasSortableColumn()) {
847 // only refresh the grid if the user has the
848 // ability to modify the sort priorities.
854 $scope.showGridConf = true;
857 $scope.gridColumnPickerIsOpen = false;
860 // called when a dragged column is dropped onto itself
861 // or any other column
862 grid.onColumnDrop = function(target) {
863 if (angular.isUndefined(target)) return;
864 if (target == grid.dragColumn) return;
865 var srcIdx, targetIdx, srcCol;
866 angular.forEach(grid.columnsProvider.columns,
868 if (col.name == grid.dragColumn) {
871 } else if (col.name == target) {
877 if (srcIdx < targetIdx) targetIdx--;
879 // move src column from old location to new location in
880 // the columns array, then force a page refresh
881 grid.columnsProvider.columns.splice(srcIdx, 1);
882 grid.columnsProvider.columns.splice(targetIdx, 0, srcCol);
886 // prepares a string for inclusion within a CSV document
887 // by escaping commas and quotes and removing newlines.
888 grid.csvDatum = function(str) {
891 str = str.replace(/\n/g, '');
892 if (str.match(/\,/) || str.match(/"/)) {
893 str = str.replace(/"/g, '""');
894 str = '"' + str + '"';
899 // sets the download file name and inserts the current CSV
900 // into a Blob URL for browser download.
901 $scope.generateCSVExportURL = function() {
902 $scope.gridColumnPickerIsOpen = false;
904 // let the file name describe the grid
905 $scope.csvExportFileName =
906 ($scope.mainLabel || grid.persistKey || 'eg_grid_data')
907 .replace(/\s+/g, '_') + '_' + $scope.page();
909 // toss the CSV into a Blob and update the export URL
910 var csv = grid.generateCSV();
911 var blob = new Blob([csv], {type : 'text/plain'});
912 $scope.csvExportURL =
913 ($window.URL || $window.webkitURL).createObjectURL(blob);
916 $scope.printCSV = function() {
917 $scope.gridColumnPickerIsOpen = false;
920 content : grid.generateCSV(),
921 content_type : 'text/plain'
925 // generates CSV for the currently visible grid contents
926 grid.generateCSV = function() {
928 var colCount = grid.columnsProvider.columns.length;
931 angular.forEach(grid.columnsProvider.columns,
933 if (!col.visible) return;
934 csvStr += grid.csvDatum(col.label);
939 csvStr = csvStr.replace(/,$/,'\n');
942 angular.forEach($scope.items, function(item) {
943 angular.forEach(grid.columnsProvider.columns,
945 if (!col.visible) return;
947 var val = grid.dataProvider.itemFieldValue(item, col);
948 // filtered value (dates, etc.)
949 val = $filter('egGridValueFilter')(val, col);
950 csvStr += grid.csvDatum(val);
954 csvStr = csvStr.replace(/,$/,'\n');
960 // Interpolate the value for column.linkpath within the context
961 // of the row item to generate the final link URL.
962 $scope.generateLinkPath = function(col, item) {
963 return egCore.strings.$replace(col.linkpath, {item : item});
966 // If a column provides its own HTML template, translate it,
967 // using the current item for the template scope.
968 // note: $sce is required to avoid security restrictions and
969 // is OK here, since the template comes directly from a
970 // local HTML template (not user input).
971 $scope.translateCellTemplate = function(col, item) {
972 var html = egCore.strings.$replace(col.template, {item : item});
973 return $sce.trustAsHtml(html);
976 $scope.collect = function() { grid.collect() }
978 // asks the dataProvider for a page of data
979 grid.collect = function() {
981 // avoid firing the collect if there is nothing to collect.
982 if (grid.selfManagedData && !grid.dataProvider.query) return;
984 if (grid.collecting) return; // avoid parallel collect()
985 grid.collecting = true;
987 console.debug('egGrid.collect() offset='
988 + grid.offset + '; limit=' + grid.limit);
990 // ensure all of our dropdowns are closed
991 // TODO: git rid of these and just use dropdown-toggle,
992 // which is more reliable.
993 $scope.gridColumnPickerIsOpen = false;
994 $scope.gridRowCountIsOpen = false;
995 $scope.gridPageSelectIsOpen = false;
998 $scope.selected = {};
999 grid.dataProvider.get(grid.offset, grid.limit).then(
1001 if (grid.controls.allItemsRetrieved)
1002 grid.controls.allItemsRetrieved();
1007 $scope.items.push(item)
1008 if (grid.controls.itemRetrieved)
1009 grid.controls.itemRetrieved(item);
1010 if ($scope.selectAll)
1011 $scope.selected[grid.indexValue(item)] = true
1013 }).finally(function() {
1014 console.debug('egGrid.collect() complete');
1015 grid.collecting = false
1016 $scope.selected = angular.copy($scope.selected);
1026 * eg-grid-field : used for collecting custom field data from the templates.
1027 * This directive does not direct display, it just passes data up to the
1030 .directive('egGridField', function() {
1032 require : '^egGrid',
1035 flesher: '=', // optional; function that can flesh a linked field, given the value
1036 name : '@', // required; unique name
1037 path : '@', // optional; flesh path
1038 ignore: '@', // optional; fields to ignore when path is a wildcard
1039 label : '@', // optional; display label
1040 flex : '@', // optional; default flex width
1041 align : '@', // optional; default alignment, left/center/right
1042 dateformat : '@', // optional: passed down to egGridValueFilter
1044 // if a field is part of an IDL object, but we are unable to
1045 // determine the class, because it's nested within a hash
1046 // (i.e. we can't navigate directly to the object via the IDL),
1047 // idlClass lets us specify the class. This is particularly
1048 // useful for nested wildcard fields.
1049 parentIdlClass : '@',
1051 // optional: for non-IDL columns, specifying a datatype
1052 // lets the caller control which display filter is used.
1053 // datatype should match the standard IDL datatypes.
1056 link : function(scope, element, attrs, egGridCtrl) {
1058 // boolean fields are presented as value-less attributes
1067 'required' // if set, always fetch data for this column
1070 if (angular.isDefined(attrs[field]))
1071 scope[field] = true;
1075 // any HTML content within the field is its custom template
1076 var tmpl = element.html();
1077 if (tmpl && !tmpl.match(/^\s*$/))
1078 scope.template = tmpl
1080 egGridCtrl.columnsProvider.add(scope);
1087 * eg-grid-action : used for specifying actions which may be applied
1088 * to items within the grid.
1090 .directive('egGridAction', function() {
1092 require : '^egGrid',
1096 group : '@', // Action group, ungrouped if not set
1097 label : '@', // Action label
1098 handler : '=', // Action function handler
1100 disabled : '=', // function
1103 link : function(scope, element, attrs, egGridCtrl) {
1104 egGridCtrl.addAction({
1106 group : scope.group,
1107 label : scope.label,
1108 divider : scope.divider,
1109 handler : scope.handler,
1110 disabled : scope.disabled,
1117 .factory('egGridColumnsProvider', ['egCore', function(egCore) {
1119 function ColumnsProvider(args) {
1122 cols.stockVisible = [];
1123 cols.idlClass = args.idlClass;
1124 cols.defaultToHidden = args.defaultToHidden;
1125 cols.defaultToNoSort = args.defaultToNoSort;
1126 cols.defaultToNoMultiSort = args.defaultToNoMultiSort;
1128 // resets column width, visibility, and sort behavior
1129 // Visibility resets to the visibility settings defined in the
1130 // template (i.e. the original egGridField values).
1131 cols.reset = function() {
1132 angular.forEach(cols.columns, function(col) {
1136 if (cols.stockVisible.indexOf(col.name) > -1) {
1139 col.visible = false;
1144 // returns true if any columns are sortable
1145 cols.hasSortableColumn = function() {
1146 return cols.columns.filter(
1148 return col.sortable || col.multisortable;
1153 cols.showAllColumns = function() {
1154 angular.forEach(cols.columns, function(column) {
1155 column.visible = true;
1159 cols.hideAllColumns = function() {
1160 angular.forEach(cols.columns, function(col) {
1165 cols.indexOf = function(name) {
1166 for (var i = 0; i < cols.columns.length; i++) {
1167 if (cols.columns[i].name == name)
1173 cols.findColumn = function(name) {
1174 return cols.columns[cols.indexOf(name)];
1177 cols.compileAutoColumns = function() {
1178 var idl_class = egCore.idl.classes[cols.idlClass];
1183 if (field.virtual) return;
1184 if (field.datatype == 'link' || field.datatype == 'org_unit') {
1185 // if the field is a link and the linked class has a
1186 // "selector" field specified, use the selector field
1187 // as the display field for the columns.
1188 // flattener will take care of the fleshing.
1189 if (field['class']) {
1190 var selector_field = egCore.idl.classes[field['class']].fields
1191 .filter(function(f) { return Boolean(f.selector) })[0];
1192 if (selector_field) {
1193 field.path = field.name + '.' + selector_field.selector;
1197 cols.add(field, true);
1202 // if a column definition has a path with a wildcard, create
1203 // columns for all non-virtual fields at the specified
1204 // position in the path.
1205 cols.expandPath = function(colSpec) {
1207 var ignoreList = [];
1209 ignoreList = colSpec.ignore.split(' ');
1211 var dotpath = colSpec.path.replace(/\.?\*$/,'');
1215 if (colSpec.parentIdlClass) {
1216 class_obj = egCore.idl.classes[colSpec.parentIdlClass];
1218 class_obj = egCore.idl.classes[cols.idlClass];
1220 var idl_parent = class_obj;
1221 var old_field_label = '';
1223 if (!class_obj) return;
1225 console.debug('egGrid: auto dotpath is: ' + dotpath);
1226 var path_parts = dotpath.split(/\./);
1228 // find the IDL class definition for the last element in the
1229 // path before the .*
1230 // an empty path_parts means expand the root class
1233 for (var path_idx in path_parts) {
1234 old_field = idl_field;
1236 var part = path_parts[path_idx];
1237 idl_field = class_obj.field_map[part];
1239 // unless we're at the end of the list, this field should
1240 // link to another class.
1241 if (idl_field && idl_field['class'] && (
1242 idl_field.datatype == 'link' ||
1243 idl_field.datatype == 'org_unit')) {
1244 if (old_field_label) old_field_label += ' : ';
1245 old_field_label += idl_field.label;
1246 class_obj = egCore.idl.classes[idl_field['class']];
1247 if (old_field) idl_parent = old_field;
1249 if (path_idx < (path_parts.length - 1)) {
1250 // we ran out of classes to hop through before
1251 // we ran out of path components
1252 console.error("egGrid: invalid IDL path: " + dotpath);
1259 angular.forEach(class_obj.fields, function(field) {
1261 // Only show wildcard fields where we have data to show
1262 // Virtual and un-fleshed links will not have any data.
1263 if (field.virtual ||
1264 (field.datatype == 'link' || field.datatype == 'org_unit') ||
1265 ignoreList.indexOf(field.name) > -1
1269 var col = cols.cloneFromScope(colSpec);
1270 col.path = (dotpath ? dotpath + '.' + field.name : field.name);
1272 // log line below is very chatty. disable until needed.
1273 // console.debug('egGrid: field: ' +field.name + '; parent field: ' + js2JSON(idl_parent));
1274 cols.add(col, false, true,
1275 {idl_parent : idl_parent, idl_field : field, idl_class : class_obj, field_parent_label : old_field_label });
1278 cols.columns = cols.columns.sort(
1280 if (a.explicit) return -1;
1281 if (b.explicit) return 1;
1283 if (a.idlclass && b.idlclass) {
1284 if (a.idlclass < b.idlclass) return -1;
1285 if (b.idlclass < a.idlclass) return 1;
1288 if (a.path && b.path && a.path.lastIndexOf('.') && b.path.lastIndexOf('.')) {
1289 if (a.path.substring(0, a.path.lastIndexOf('.')) < b.path.substring(0, b.path.lastIndexOf('.'))) return -1;
1290 if (b.path.substring(0, b.path.lastIndexOf('.')) < a.path.substring(0, a.path.lastIndexOf('.'))) return 1;
1293 if (a.label && b.label) {
1294 if (a.label < b.label) return -1;
1295 if (b.label < a.label) return 1;
1298 return a.name < b.name ? -1 : 1;
1305 "egGrid: wildcard path does not resolve to an object: "
1310 // angular.clone(scopeObject) is not permittable. Manually copy
1311 // the fields over that we need (so the scope object can go away).
1312 cols.cloneFromScope = function(colSpec) {
1314 flesher : colSpec.flesher,
1315 name : colSpec.name,
1316 label : colSpec.label,
1317 path : colSpec.path,
1318 align : colSpec.align || 'left',
1319 flex : Number(colSpec.flex) || 2,
1320 sort : Number(colSpec.sort) || 0,
1321 required : colSpec.required,
1322 linkpath : colSpec.linkpath,
1323 template : colSpec.template,
1324 visible : colSpec.visible,
1325 hidden : colSpec.hidden,
1326 datatype : colSpec.datatype,
1327 sortable : colSpec.sortable,
1328 nonsortable : colSpec.nonsortable,
1329 multisortable : colSpec.multisortable,
1330 nonmultisortable : colSpec.nonmultisortable,
1331 dateformat : colSpec.dateformat,
1332 parentIdlClass : colSpec.parentIdlClass
1337 // Add a column to the columns collection.
1338 // Columns may come from a slim eg-columns-field or
1339 // directly from the IDL.
1340 cols.add = function(colSpec, fromIDL, fromExpand, idl_info) {
1342 // First added column with the specified path takes precedence.
1343 // This allows for specific definitions followed by wildcard
1344 // definitions. If a match is found, back out.
1345 if (cols.columns.filter(function(c) {
1346 return (c.path == colSpec.path) })[0]) {
1347 console.debug('skipping pre-existing column ' + colSpec.path);
1351 var column = fromExpand ? colSpec : cols.cloneFromScope(colSpec);
1353 if (column.path && column.path.match(/\*$/))
1354 return cols.expandPath(colSpec);
1356 if (!fromExpand) column.explicit = true;
1358 if (!column.name) column.name = column.path;
1359 if (!column.path) column.path = column.name;
1361 if (column.visible || (!cols.defaultToHidden && !column.hidden))
1362 column.visible = true;
1364 if (column.sortable || (!cols.defaultToNoSort && !column.nonsortable))
1365 column.sortable = true;
1367 if (column.multisortable ||
1368 (!cols.defaultToNoMultiSort && !column.nonmultisortable))
1369 column.multisortable = true;
1371 cols.columns.push(column);
1373 // Track which columns are visible by default in case we
1374 // need to reset column visibility
1376 cols.stockVisible.push(column.name);
1378 if (fromIDL) return; // directly from egIDL. nothing left to do.
1380 // lookup the matching IDL field
1381 if (!idl_info && cols.idlClass)
1382 idl_info = cols.idlFieldFromPath(column.path);
1385 // column is not represented within the IDL
1386 column.adhoc = true;
1390 column.datatype = idl_info.idl_field.datatype;
1392 if (!column.label) {
1393 column.label = idl_info.idl_field.label || column.name;
1396 if (fromExpand && idl_info.idl_class) {
1397 column.idlclass = '';
1398 if (idl_info.field_parent_label && idl_info.idl_parent.label != idl_info.idl_class.label) {
1399 column.idlclass = (idl_info.field_parent_label || idl_info.idl_parent.label || idl_info.idl_parent.name);
1401 column.idlclass += idl_info.idl_class.label || idl_info.idl_class.name;
1406 // finds the IDL field from the dotpath, using the columns
1407 // idlClass as the base.
1408 cols.idlFieldFromPath = function(dotpath) {
1409 var class_obj = egCore.idl.classes[cols.idlClass];
1410 var path_parts = dotpath.split(/\./);
1414 for (var path_idx in path_parts) {
1415 var part = path_parts[path_idx];
1416 idl_parent = idl_field;
1417 idl_field = class_obj.field_map[part];
1419 if (idl_field && idl_field['class'] && (
1420 idl_field.datatype == 'link' ||
1421 idl_field.datatype == 'org_unit')) {
1422 class_obj = egCore.idl.classes[idl_field['class']];
1424 // else, path is not in the IDL, which is fine
1427 if (!idl_field) return null;
1430 idl_parent: idl_parent,
1431 idl_field : idl_field,
1432 idl_class : class_obj
1438 instance : function(args) { return new ColumnsProvider(args) }
1444 * Generic data provider template class. This is basically an abstract
1445 * class factory service whose instances can be locally modified to
1446 * meet the needs of each individual grid.
1448 .factory('egGridDataProvider',
1449 ['$q','$timeout','$filter','egCore',
1450 function($q , $timeout , $filter , egCore) {
1452 function GridDataProvider(args) {
1453 var gridData = this;
1454 if (!args) args = {};
1457 gridData.get = args.get;
1458 gridData.query = args.query;
1459 gridData.idlClass = args.idlClass;
1460 gridData.columnsProvider = args.columnsProvider;
1462 // Delivers a stream of array data via promise.notify()
1463 // Useful for passing an array of data to egGrid.get()
1464 // If a count is provided, the array will be trimmed to
1465 // the range defined by count and offset
1466 gridData.arrayNotifier = function(arr, offset, count) {
1467 if (!arr || arr.length == 0) return $q.when();
1468 if (count) arr = arr.slice(offset, offset + count);
1469 var def = $q.defer();
1470 // promise notifications are only witnessed when delivered
1471 // after the caller has his hands on the promise object
1472 $timeout(function() {
1473 angular.forEach(arr, def.notify);
1479 // Calls the grid refresh function. Once instantiated, the
1480 // grid will replace this function with it's own refresh()
1481 gridData.refresh = function(noReset) { }
1483 if (!gridData.get) {
1484 // returns a promise whose notify() delivers items
1485 gridData.get = function(index, count) {
1486 console.error("egGridDataProvider.get() not implemented");
1490 // attempts a flat field lookup first. If the column is not
1491 // found on the top-level object, attempts a nested lookup
1492 // TODO: consider a caching layer to speed up template
1493 // rendering, particularly for nested objects?
1494 gridData.itemFieldValue = function(item, column) {
1496 if (column.name in item) {
1497 if (typeof item[column.name] == 'function') {
1498 val = item[column.name]();
1500 val = item[column.name];
1503 val = gridData.nestedItemFieldValue(item, column);
1509 // TODO: deprecate me
1510 gridData.flatItemFieldValue = function(item, column) {
1511 console.warn('gridData.flatItemFieldValue deprecated; '
1512 + 'leave provider.itemFieldValue unset');
1513 return item[column.name];
1516 // given an object and a dot-separated path to a field,
1517 // extract the value of the field. The path can refer
1518 // to function names or object attributes. If the final
1519 // value is an IDL field, run the value through its
1520 // corresponding output filter.
1521 gridData.nestedItemFieldValue = function(obj, column) {
1522 item = obj; // keep a copy around
1524 if (obj === null || obj === undefined || obj === '') return '';
1525 if (!column.path) return obj;
1528 var parts = column.path.split('.');
1530 angular.forEach(parts, function(step, idx) {
1531 // object is not fleshed to the expected extent
1532 if (typeof obj != 'object') {
1533 if (typeof obj != 'undefined' && column.flesher) {
1534 obj = column.flesher(obj, column, item);
1541 var cls = obj.classname;
1542 if (cls && (class_obj = egCore.idl.classes[cls])) {
1543 idl_field = class_obj.field_map[step];
1544 obj = obj[step] ? obj[step]() : '';
1546 if (angular.isFunction(obj[step])) {
1554 // We found a nested IDL object which may or may not have
1555 // been configured as a top-level column. Grab the datatype.
1556 if (idl_field && !column.datatype)
1557 column.datatype = idl_field.datatype;
1559 if (obj === null || obj === undefined || obj === '') return '';
1565 instance : function(args) {
1566 return new GridDataProvider(args);
1573 // Factory service for egGridDataManager instances, which are
1574 // responsible for collecting flattened grid data.
1575 .factory('egGridFlatDataProvider',
1576 ['$q','egCore','egGridDataProvider',
1577 function($q , egCore , egGridDataProvider) {
1580 instance : function(args) {
1581 var provider = egGridDataProvider.instance(args);
1583 provider.get = function(offset, count) {
1585 // no query means no call
1586 if (!provider.query ||
1587 angular.equals(provider.query, {}))
1590 // find all of the currently visible columns
1591 var queryFields = {}
1592 angular.forEach(provider.columnsProvider.columns,
1594 // only query IDL-tracked columns
1595 if (!col.adhoc && (col.required || col.visible))
1596 queryFields[col.name] = col.path;
1600 return egCore.net.request(
1602 'open-ils.fielder.flattened_search',
1603 egCore.auth.token(), provider.idlClass,
1604 queryFields, provider.query,
1605 { sort : provider.sort,
1611 //provider.itemFieldValue = provider.flatItemFieldValue;
1618 .directive('egGridColumnDragSource', function() {
1621 require : '^egGrid',
1622 link : function(scope, element, attrs, egGridCtrl) {
1623 angular.element(element).attr('draggable', 'true');
1625 element.bind('dragstart', function(e) {
1626 egGridCtrl.dragColumn = attrs.column;
1627 egGridCtrl.dragType = attrs.dragType || 'move'; // or resize
1628 egGridCtrl.colResizeDir = 0;
1630 if (egGridCtrl.dragType == 'move') {
1631 // style the column getting moved
1632 angular.element(e.target).addClass(
1633 'eg-grid-column-move-handle-active');
1637 element.bind('dragend', function(e) {
1638 if (egGridCtrl.dragType == 'move') {
1639 angular.element(e.target).removeClass(
1640 'eg-grid-column-move-handle-active');
1647 .directive('egGridColumnDragDest', function() {
1650 require : '^egGrid',
1651 link : function(scope, element, attrs, egGridCtrl) {
1653 element.bind('dragover', function(e) { // required for drop
1654 e.stopPropagation();
1656 e.dataTransfer.dropEffect = 'move';
1658 if (egGridCtrl.colResizeDir == 0) return; // move
1660 var cols = egGridCtrl.columnsProvider;
1661 var srcCol = egGridCtrl.dragColumn;
1662 var srcColIdx = cols.indexOf(srcCol);
1664 if (egGridCtrl.colResizeDir == -1) {
1665 if (cols.indexOf(attrs.column) <= srcColIdx) {
1666 egGridCtrl.modifyColumnFlex(
1667 egGridCtrl.columnsProvider.findColumn(
1668 egGridCtrl.dragColumn), -1);
1669 if (cols.columns[srcColIdx+1]) {
1670 // source column shrinks by one, column to the
1671 // right grows by one.
1672 egGridCtrl.modifyColumnFlex(
1673 cols.columns[srcColIdx+1], 1);
1678 if (cols.indexOf(attrs.column) > srcColIdx) {
1679 egGridCtrl.modifyColumnFlex(
1680 egGridCtrl.columnsProvider.findColumn(
1681 egGridCtrl.dragColumn), 1);
1682 if (cols.columns[srcColIdx+1]) {
1683 // source column grows by one, column to the
1684 // right grows by one.
1685 egGridCtrl.modifyColumnFlex(
1686 cols.columns[srcColIdx+1], -1);
1694 element.bind('dragenter', function(e) {
1695 e.stopPropagation();
1697 if (egGridCtrl.dragType == 'move') {
1698 angular.element(e.target).addClass('eg-grid-col-hover');
1700 // resize grips are on the right side of each column.
1701 // dragenter will either occur on the source column
1702 // (dragging left) or the column to the right.
1703 if (egGridCtrl.colResizeDir == 0) {
1704 if (egGridCtrl.dragColumn == attrs.column) {
1705 egGridCtrl.colResizeDir = -1; // west
1707 egGridCtrl.colResizeDir = 1; // east
1713 element.bind('dragleave', function(e) {
1714 e.stopPropagation();
1716 if (egGridCtrl.dragType == 'move') {
1717 angular.element(e.target).removeClass('eg-grid-col-hover');
1721 element.bind('drop', function(e) {
1722 e.stopPropagation();
1724 egGridCtrl.colResizeDir = 0;
1725 if (egGridCtrl.dragType == 'move') {
1726 angular.element(e.target).removeClass('eg-grid-col-hover');
1727 egGridCtrl.onColumnDrop(attrs.column); // move the column
1734 .directive('egGridMenuItem', function() {
1737 require : '^egGrid',
1743 handler : '=', // onclick handler function
1744 divider : '=', // if true, show a divider only
1745 handlerData : '=', // if set, passed as second argument to handler
1746 disabled : '=', // function
1747 hidden : '=' // function
1749 link : function(scope, element, attrs, egGridCtrl) {
1750 egGridCtrl.addMenuItem({
1751 checkbox : scope.checkbox,
1752 checked : scope.checked ? true : false,
1753 label : scope.label,
1754 standalone : scope.standalone ? true : false,
1755 handler : scope.handler,
1756 divider : scope.divider,
1757 disabled : scope.disabled,
1758 hidden : scope.hidden,
1759 handlerData : scope.handlerData
1769 * Translates bare IDL object values into display values.
1770 * 1. Passes dates through the angular date filter
1771 * 2. Translates bools to Booleans so the browser can display translated
1772 * value. (Though we could manually translate instead..)
1773 * Others likely to follow...
1775 .filter('egGridValueFilter', ['$filter', function($filter) {
1776 return function(value, column) {
1777 switch(column.datatype) {
1780 // Browser will translate true/false for us
1782 case '1' : // legacy
1786 case '0' : // legacy
1789 // value may be null, '', etc.
1790 default : return '';
1793 // canned angular date filter FTW
1794 if (!column.dateformat)
1795 column.dateformat = 'shortDate';
1796 return $filter('date')(value, column.dateformat);
1798 return $filter('currency')(value);