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 // comma-separated list of supported or disabled grid features
33 // supported features:
34 // startSelected : init the grid with all rows selected by default
35 // -menu : don't show any menu buttons (or use space for them)
36 // -picker : don't show the column picker
37 // -pagination : don't show any pagination elements, and set
39 // -actions : don't show the actions dropdown
40 // -index : don't show the row index column (can't use "index"
41 // as the idField in this case)
42 // -display : columns are hidden by default
43 // -sort : columns are unsortable by default
44 // -multisort : sort priorities config disabled by default
45 // -multiselect : only one row at a time can be selected;
46 // choosing this also disables the checkbox
50 // optional primary grid label
53 // if true, use the IDL class label as the mainLabel
56 // optional context menu label
59 // Hash of control functions.
61 // These functions are defined by the calling scope and
62 // invoked as-is by the grid w/ the specified parameters.
64 // itemRetrieved : function(item) {}
65 // allItemsRetrieved : function() {}
68 // If defined, the grid will watch the return value from
69 // the function defined at watchQuery on each digest and
70 // re-draw the grid when query changes occur.
72 // watchQuery : function() { /* return grid query */ }
75 // These functions are defined by the grid and thus
76 // replace any values defined for these attributes from the
79 // activateItem : function(item) {}
80 // allItems : function(allItems) {}
81 // selectedItems : function(selected) {}
82 // selectItems : function(ids) {}
83 // setQuery : function(queryStruct) {} // causes reload
84 // setSort : function(sortSturct) {} // causes reload
88 // TODO: avoid hard-coded url
89 templateUrl : '/eg/staff/share/t_autogrid',
91 link : function(scope, element, attrs) {
92 // link() is called after page compilation, which means our
93 // eg-grid-field's have been parsed and loaded. Now it's
94 // safe to perform our initial page load.
96 // load auto fields after eg-grid-field's so they are not clobbered
97 scope.handleAutoFields();
100 scope.grid_element = element;
102 .find('.eg-grid-content-body')
103 .bind('contextmenu', scope.showActionContextMenu);
107 '$scope','$q','egCore','egGridFlatDataProvider','$location',
108 'egGridColumnsProvider','$filter','$window','$sce','$timeout',
109 function($scope, $q , egCore, egGridFlatDataProvider , $location,
110 egGridColumnsProvider , $filter , $window , $sce , $timeout) {
114 grid.init = function() {
117 $scope.showGridConf = false;
118 grid.totalCount = -1;
119 $scope.selected = {};
120 $scope.actionGroups = [{actions:[]}]; // Grouped actions for selected items
121 $scope.menuItems = []; // global actions
123 $scope.showIndex = ($scope.features.indexOf('-index') == -1);
125 $scope.startSelected = $scope.selectAll = ($scope.features.indexOf('startSelected') > -1);
126 $scope.showActions = ($scope.features.indexOf('-actions') == -1);
127 $scope.showPagination = ($scope.features.indexOf('-pagination') == -1);
128 $scope.showPicker = ($scope.features.indexOf('-picker') == -1);
130 $scope.showMenu = ($scope.features.indexOf('-menu') == -1);
132 // remove some unneeded values from the scope to reduce bloat
134 grid.idlClass = $scope.idlClass;
135 delete $scope.idlClass;
137 grid.persistKey = $scope.persistKey;
138 delete $scope.persistKey;
140 var stored_limit = 0;
141 if ($scope.showPagination) {
142 if (grid.persistKey) {
143 var stored_limit = Number(
144 egCore.hatch.getLocalItem('eg.grid.' + grid.persistKey + '.limit')
148 stored_limit = 10000; // maybe support "Inf"?
151 grid.limit = Number(stored_limit) || Number($scope.pageSize) || 25;
153 grid.indexField = $scope.idField;
154 delete $scope.idField;
156 grid.dataProvider = $scope.itemsProvider;
158 var features = ($scope.features) ?
159 $scope.features.split(',') : [];
160 delete $scope.features;
162 if (!grid.indexField && grid.idlClass)
163 grid.indexField = egCore.idl.classes[grid.idlClass].pkey;
165 grid.columnsProvider = egGridColumnsProvider.instance({
166 idlClass : grid.idlClass,
167 defaultToHidden : (features.indexOf('-display') > -1),
168 defaultToNoSort : (features.indexOf('-sort') > -1),
169 defaultToNoMultiSort : (features.indexOf('-multisort') > -1)
171 $scope.canMultiSelect = (features.indexOf('-multiselect') == -1);
173 $scope.handleAutoFields = function() {
174 if ($scope.autoFields) {
175 if (grid.autoLabel) {
177 egCore.idl.classes[grid.idlClass].label;
179 grid.columnsProvider.compileAutoColumns();
180 delete $scope.autoFields;
184 if (!grid.dataProvider) {
185 // no provider, um, provided.
186 // Use a flat data provider
188 grid.selfManagedData = true;
189 grid.dataProvider = egGridFlatDataProvider.instance({
190 indexField : grid.indexField,
191 idlClass : grid.idlClass,
192 columnsProvider : grid.columnsProvider,
197 $scope.itemFieldValue = grid.dataProvider.itemFieldValue;
198 $scope.indexValue = function(item) {
199 return grid.indexValue(item)
202 grid.applyControlFunctions();
204 grid.loadConfig().then(function() {
205 // link columns to scope after loadConfig(), since it
206 // replaces the columns array.
207 $scope.columns = grid.columnsProvider.columns;
210 // NOTE: grid.collect() is first called from link(), not here.
213 // link our control functions into the gridControls
214 // scope object so the caller can access them.
215 grid.applyControlFunctions = function() {
217 // we use some of these controls internally, so sett
218 // them up even if the caller doesn't request them.
219 var controls = $scope.gridControls || {};
221 controls.columnMap = function() {
223 angular.forEach(grid.columnsProvider.columns, function (c) {
229 controls.columnsProvider = function() {
230 return grid.columnsProvider;
233 // link in the control functions
234 controls.selectedItems = function() {
235 return grid.getSelectedItems()
238 controls.allItems = function() {
242 controls.selectItems = function(ids) {
244 $scope.selected = {};
245 angular.forEach(ids, function(i) {
246 $scope.selected[''+i] = true;
250 // if the caller provided a functional setQuery,
251 // extract the value before replacing it
252 if (controls.setQuery) {
253 grid.dataProvider.query =
257 controls.setQuery = function(query) {
258 grid.dataProvider.query = query;
262 if (controls.watchQuery) {
263 // capture the initial query value
264 grid.dataProvider.query = controls.watchQuery();
267 $scope.gridWatchQuery = controls.watchQuery;
268 $scope.$watch('gridWatchQuery()', function(newv) {
269 controls.setQuery(newv);
273 // if the caller provided a functional setSort
274 // extract the value before replacing it
275 grid.dataProvider.sort =
276 controls.setSort ? controls.setSort() : [];
278 controls.setSort = function(sort) {
282 controls.refresh = function(noReset) {
283 if (!noReset) grid.offset = 0;
287 controls.setLimit = function(limit,forget) {
288 if (!forget && grid.persistKey)
289 egCore.hatch.setLocalItem('eg.grid.' + grid.persistKey + '.limit', limit);
292 controls.getLimit = function() {
295 controls.setOffset = function(offset) {
296 grid.offset = offset;
298 controls.getOffset = function() {
302 controls.saveConfig = function () {
303 return $scope.saveConfig();
306 grid.dataProvider.refresh = controls.refresh;
307 grid.controls = controls;
310 // If a menu item provides its own HTML template, translate it,
311 // using the menu item for the template scope.
312 // note: $sce is required to avoid security restrictions and
313 // is OK here, since the template comes directly from a
314 // local HTML template (not user input).
315 $scope.translateMenuItemTemplate = function(item) {
316 var html = egCore.strings.$replace(item.template, {item : item});
317 return $sce.trustAsHtml(html);
320 // add a new (global) grid menu item
321 grid.addMenuItem = function(item) {
322 $scope.menuItems.push(item);
323 var handler = item.handler;
324 item.handler = function() {
325 $scope.gridMenuIsOpen = false; // close menu
328 item.handlerData, grid.getSelectedItems());
333 // add a selected-items action
334 grid.addAction = function(act) {
336 $scope.actionGroups.forEach(function(g){
337 if (g.label === act.group) {
343 $scope.actionGroups.push({
350 // remove the stored column configuration preferenc, then recover
351 // the column visibility information from the initial page load.
352 $scope.resetColumns = function() {
353 $scope.gridColumnPickerIsOpen = false;
354 egCore.hatch.removeItem('eg.grid.' + grid.persistKey)
356 grid.columnsProvider.reset();
357 if (grid.selfManagedData) grid.collect();
361 $scope.showAllColumns = function() {
362 $scope.gridColumnPickerIsOpen = false;
363 grid.columnsProvider.showAllColumns();
364 if (grid.selfManagedData) grid.collect();
367 $scope.hideAllColumns = function() {
368 $scope.gridColumnPickerIsOpen = false;
369 grid.columnsProvider.hideAllColumns();
370 // note: no need to fetch new data if no columns are visible
373 $scope.toggleColumnVisibility = function(col) {
374 $scope.gridColumnPickerIsOpen = false;
375 col.visible = !col.visible;
377 // egGridFlatDataProvider only retrieves data to be
378 // displayed. When column visibility changes, it's
379 // necessary to fetch the newly visible column data.
380 if (grid.selfManagedData) grid.collect();
383 // save the columns configuration (position, sort, width) to
384 // eg.grid.<persist-key>
385 $scope.saveConfig = function() {
386 $scope.gridColumnPickerIsOpen = false;
388 if (!grid.persistKey) {
390 "Cannot save settings without a grid persist-key");
394 // only store information about visible columns.
395 var conf = grid.columnsProvider.columns.filter(
396 function(col) {return Boolean(col.visible) });
398 // now scrunch the data down to just the needed info
399 conf = conf.map(function(col) {
400 var c = {name : col.name}
401 // Apart from the name, only store non-default values.
402 // No need to store col.visible, since that's implicit
403 if (col.align != 'left') c.align = col.align;
404 if (col.flex != 2) c.flex = col.flex;
405 if (Number(col.sort)) c.sort = Number(c.sort);
409 egCore.hatch.setItem('eg.grid.' + grid.persistKey, conf)
411 // Save operation performed from the grid configuration UI.
412 // Hide the configuration UI and re-draw w/ sort applied
413 if ($scope.showGridConf)
414 $scope.toggleConfDisplay();
419 // load the columns configuration (position, sort, width) from
420 // eg.grid.<persist-key> and apply the loaded settings to the
421 // columns on our columnsProvider
422 grid.loadConfig = function() {
423 if (!grid.persistKey) return $q.when();
425 return egCore.hatch.getItem('eg.grid.' + grid.persistKey)
426 .then(function(conf) {
429 var columns = grid.columnsProvider.columns;
432 angular.forEach(conf, function(col) {
433 var grid_col = columns.filter(
434 function(c) {return c.name == col.name})[0];
437 // saved column does not match a column in the
438 // current grid. skip it.
442 grid_col.align = col.align || 'left';
443 grid_col.flex = col.flex || 2;
444 grid_col.sort = col.sort || 0;
445 // all saved columns are assumed to be true
446 grid_col.visible = true;
447 new_cols.push(grid_col);
450 // columns which are not expressed within the saved
451 // configuration are marked as non-visible and
452 // appended to the end of the new list of columns.
453 angular.forEach(columns, function(col) {
454 var found = conf.filter(
455 function(c) {return (c.name == col.name)})[0];
462 grid.columnsProvider.columns = new_cols;
468 $scope.onContextMenu = function($event) {
469 var col = angular.element($event.target).attr('column');
470 console.log('selected column ' + col);
473 $scope.page = function() {
474 return (grid.offset / grid.limit) + 1;
477 $scope.goToPage = function(page) {
479 if (angular.isNumber(page) && page > 0) {
480 grid.offset = (page - 1) * grid.limit;
485 $scope.offset = function(o) {
486 if (angular.isNumber(o))
491 $scope.limit = function(l) {
492 if (angular.isNumber(l)) {
494 egCore.hatch.setLocalItem('eg.grid.' + grid.persistKey + '.limit', l);
500 $scope.onFirstPage = function() {
501 return grid.offset == 0;
504 $scope.hasNextPage = function() {
505 // we have less data than requested, there must
506 // not be any more pages
507 if (grid.count() < grid.limit) return false;
509 // if the total count is not known, assume that a full
510 // page of data implies more pages are available.
511 if (grid.totalCount == -1) return true;
513 // we have a full page of data, but is there more?
514 return grid.totalCount > (grid.offset + grid.count());
517 $scope.incrementPage = function() {
518 grid.offset += grid.limit;
522 $scope.decrementPage = function() {
523 if (grid.offset < grid.limit) {
526 grid.offset -= grid.limit;
531 // number of items loaded for the current page of results
532 grid.count = function() {
533 return $scope.items.length;
536 // returns the unique identifier value for the provided item
537 // for internal consistency, indexValue is always coerced
539 grid.indexValue = function(item) {
540 if (angular.isObject(item)) {
542 if (angular.isFunction(item[grid.indexField]))
543 return ''+item[grid.indexField]();
544 return ''+item[grid.indexField]; // flat data
547 // passed a non-object; assume it's an index
551 // fires the hide handler function for a context action
552 $scope.actionHide = function(action) {
556 return action.hide(action);
559 // fires the disable handler function for a context action
560 $scope.actionDisable = function(action) {
561 if (!action.disabled) {
564 return action.disabled(action);
567 // fires the action handler function for a context action
568 $scope.actionLauncher = function(action) {
569 if (!action.handler) {
571 'No handler specified for "' + action.label + '"');
575 action.handler(grid.getSelectedItems());
577 console.error('Error executing handler for "'
578 + action.label + '" => ' + E + "\n" + E.stack);
581 if ($scope.action_context_showing) $scope.hideActionContextMenu();
586 $scope.hideActionContextMenu = function () {
587 $($scope.menu_dom).css({
589 width: $scope.action_context_width,
590 top: $scope.action_context_y,
591 left: $scope.action_context_x
593 $($scope.action_context_parent).append($scope.menu_dom);
594 $scope.action_context_oldy = $scope.action_context_oldx = 0;
595 $('body').unbind('click.remove_context_menu_'+$scope.action_context_index);
596 $scope.action_context_showing = false;
599 $scope.action_context_showing = false;
600 $scope.showActionContextMenu = function ($event) {
602 // Have to gather these here, instead of inside link()
603 if (!$scope.menu_dom) $scope.menu_dom = $($scope.grid_element).find('.grid-action-dropdown')[0];
604 if (!$scope.action_context_parent) $scope.action_context_parent = $($scope.menu_dom).parent();
606 if (!grid.getSelectedItems().length) // Nothing selected, fire the click event
607 $event.target.click();
609 if (!$scope.action_context_showing) {
610 $scope.action_context_width = $($scope.menu_dom).css('width');
611 $scope.action_context_y = $($scope.menu_dom).css('top');
612 $scope.action_context_x = $($scope.menu_dom).css('left');
613 $scope.action_context_showing = true;
614 $scope.action_context_index = Math.floor((Math.random() * 1000) + 1);
616 $('body').append($($scope.menu_dom));
617 $('body').bind('click.remove_context_menu_'+$scope.action_context_index, $scope.hideActionContextMenu);
620 $($scope.menu_dom).css({
622 width: $scope.action_context_width,
630 // returns the list of selected item objects
631 grid.getSelectedItems = function() {
632 return $scope.items.filter(
634 return Boolean($scope.selected[grid.indexValue(item)]);
639 grid.getItemByIndex = function(index) {
640 for (var i = 0; i < $scope.items.length; i++) {
641 var item = $scope.items[i];
642 if (grid.indexValue(item) == index)
647 // selects one row after deselecting all of the others
648 grid.selectOneItem = function(index) {
649 $scope.selected = {};
650 $scope.selected[index] = true;
653 // selects or deselects an item, without affecting the others.
654 // returns true if the item is selected; false if de-selected.
655 grid.toggleSelectOneItem = function(index) {
656 if ($scope.selected[index]) {
657 delete $scope.selected[index];
660 return $scope.selected[index] = true;
664 grid.selectAllItems = function() {
665 angular.forEach($scope.items, function(item) {
666 $scope.selected[grid.indexValue(item)] = true
670 $scope.$watch('selectAll', function(newVal) {
672 grid.selectAllItems();
674 $scope.selected = {};
678 // returns true if item1 appears in the list before item2;
679 // false otherwise. this is slightly more efficient that
680 // finding the position of each then comparing them.
681 // item1 / item2 may be an item or an item index
682 grid.itemComesBefore = function(itemOrIndex1, itemOrIndex2) {
683 var idx1 = grid.indexValue(itemOrIndex1);
684 var idx2 = grid.indexValue(itemOrIndex2);
686 // use for() for early exit
687 for (var i = 0; i < $scope.items.length; i++) {
688 var idx = grid.indexValue($scope.items[i]);
689 if (idx == idx1) return true;
690 if (idx == idx2) return false;
695 // 0-based position of item in the current data set
696 grid.indexOf = function(item) {
697 var idx = grid.indexValue(item);
698 for (var i = 0; i < $scope.items.length; i++) {
699 if (grid.indexValue($scope.items[i]) == idx)
705 grid.modifyColumnFlex = function(column, val) {
707 // prevent flex:0; use hiding instead
711 $scope.modifyColumnFlex = function(col, val) {
712 grid.modifyColumnFlex(col, val);
715 // handles click, control-click, and shift-click
716 $scope.handleRowClick = function($event, item) {
717 var index = grid.indexValue(item);
719 var origSelected = Object.keys($scope.selected);
721 if (!$scope.canMultiSelect) {
722 grid.selectOneItem(index);
723 grid.lastSelectedItemIndex = index;
727 if ($event.ctrlKey || $event.metaKey /* mac command */) {
729 if (grid.toggleSelectOneItem(index))
730 grid.lastSelectedItemIndex = index;
732 } else if ($event.shiftKey) {
735 if (!grid.lastSelectedItemIndex ||
736 index == grid.lastSelectedItemIndex) {
737 grid.selectOneItem(index);
738 grid.lastSelectedItemIndex = index;
742 var selecting = false;
743 var ascending = grid.itemComesBefore(
744 grid.lastSelectedItemIndex, item);
746 grid.indexOf(grid.lastSelectedItemIndex);
748 // update to new last-selected
749 grid.lastSelectedItemIndex = index;
751 // select each row between the last selected and
752 // currently selected items
754 startPos += ascending ? 1 : -1;
755 var curItem = $scope.items[startPos];
757 var curIdx = grid.indexValue(curItem);
758 $scope.selected[curIdx] = true;
759 if (curIdx == index) break; // all done
764 grid.selectOneItem(index);
765 grid.lastSelectedItemIndex = index;
769 // Builds a sort expression from column sort priorities.
770 // called on page load and any time the priorities are modified.
771 grid.compileSort = function() {
772 var sortList = grid.columnsProvider.columns.filter(
773 function(col) { return Number(col.sort) != 0 }
776 if (Math.abs(a.sort) < Math.abs(b.sort))
782 if (sortList.length) {
783 grid.dataProvider.sort = sortList.map(function(col) {
785 blob[col.name] = col.sort < 0 ? 'desc' : 'asc';
791 // builds a sort expression using a single column,
792 // toggling between ascending and descending sort.
793 $scope.quickSort = function(col_name) {
794 var sort = grid.dataProvider.sort;
795 if (sort && sort.length &&
796 sort[0] == col_name) {
798 blob[col_name] = 'desc';
799 grid.dataProvider.sort = [blob];
801 grid.dataProvider.sort = [col_name];
808 // show / hide the grid configuration row
809 $scope.toggleConfDisplay = function() {
810 if ($scope.showGridConf) {
811 $scope.showGridConf = false;
812 if (grid.columnsProvider.hasSortableColumn()) {
813 // only refresh the grid if the user has the
814 // ability to modify the sort priorities.
820 $scope.showGridConf = true;
823 $scope.gridColumnPickerIsOpen = false;
826 // called when a dragged column is dropped onto itself
827 // or any other column
828 grid.onColumnDrop = function(target) {
829 if (angular.isUndefined(target)) return;
830 if (target == grid.dragColumn) return;
831 var srcIdx, targetIdx, srcCol;
832 angular.forEach(grid.columnsProvider.columns,
834 if (col.name == grid.dragColumn) {
837 } else if (col.name == target) {
843 if (srcIdx < targetIdx) targetIdx--;
845 // move src column from old location to new location in
846 // the columns array, then force a page refresh
847 grid.columnsProvider.columns.splice(srcIdx, 1);
848 grid.columnsProvider.columns.splice(targetIdx, 0, srcCol);
852 // prepares a string for inclusion within a CSV document
853 // by escaping commas and quotes and removing newlines.
854 grid.csvDatum = function(str) {
857 str = str.replace(/\n/g, '');
858 if (str.match(/\,/) || str.match(/"/)) {
859 str = str.replace(/"/g, '""');
860 str = '"' + str + '"';
865 // sets the download file name and inserts the current CSV
866 // into a Blob URL for browser download.
867 $scope.generateCSVExportURL = function() {
868 $scope.gridColumnPickerIsOpen = false;
870 // let the file name describe the grid
871 $scope.csvExportFileName =
872 ($scope.mainLabel || grid.persistKey || 'eg_grid_data')
873 .replace(/\s+/g, '_') + '_' + $scope.page();
875 // toss the CSV into a Blob and update the export URL
876 var csv = grid.generateCSV();
877 var blob = new Blob([csv], {type : 'text/plain'});
878 $scope.csvExportURL =
879 ($window.URL || $window.webkitURL).createObjectURL(blob);
882 $scope.printCSV = function() {
883 $scope.gridColumnPickerIsOpen = false;
886 content : grid.generateCSV(),
887 content_type : 'text/plain'
891 // generates CSV for the currently visible grid contents
892 grid.generateCSV = function() {
894 var colCount = grid.columnsProvider.columns.length;
897 angular.forEach(grid.columnsProvider.columns,
899 if (!col.visible) return;
900 csvStr += grid.csvDatum(col.label);
905 csvStr = csvStr.replace(/,$/,'\n');
908 angular.forEach($scope.items, function(item) {
909 angular.forEach(grid.columnsProvider.columns,
911 if (!col.visible) return;
913 var val = grid.dataProvider.itemFieldValue(item, col);
914 // filtered value (dates, etc.)
915 val = $filter('egGridValueFilter')(val, col);
916 csvStr += grid.csvDatum(val);
920 csvStr = csvStr.replace(/,$/,'\n');
926 // Interpolate the value for column.linkpath within the context
927 // of the row item to generate the final link URL.
928 $scope.generateLinkPath = function(col, item) {
929 return egCore.strings.$replace(col.linkpath, {item : item});
932 // If a column provides its own HTML template, translate it,
933 // using the current item for the template scope.
934 // note: $sce is required to avoid security restrictions and
935 // is OK here, since the template comes directly from a
936 // local HTML template (not user input).
937 $scope.translateCellTemplate = function(col, item) {
938 var html = egCore.strings.$replace(col.template, {item : item});
939 return $sce.trustAsHtml(html);
942 $scope.collect = function() { grid.collect() }
944 // asks the dataProvider for a page of data
945 grid.collect = function() {
947 // avoid firing the collect if there is nothing to collect.
948 if (grid.selfManagedData && !grid.dataProvider.query) return;
950 if (grid.collecting) return; // avoid parallel collect()
951 grid.collecting = true;
953 console.debug('egGrid.collect() offset='
954 + grid.offset + '; limit=' + grid.limit);
956 // ensure all of our dropdowns are closed
957 // TODO: git rid of these and just use dropdown-toggle,
958 // which is more reliable.
959 $scope.gridColumnPickerIsOpen = false;
960 $scope.gridRowCountIsOpen = false;
961 $scope.gridPageSelectIsOpen = false;
964 $scope.selected = {};
965 grid.dataProvider.get(grid.offset, grid.limit).then(
967 if (grid.controls.allItemsRetrieved)
968 grid.controls.allItemsRetrieved();
973 $scope.items.push(item)
974 if (grid.controls.itemRetrieved)
975 grid.controls.itemRetrieved(item);
976 if ($scope.selectAll)
977 $scope.selected[grid.indexValue(item)] = true
979 }).finally(function() {
980 console.debug('egGrid.collect() complete');
981 grid.collecting = false
991 * eg-grid-field : used for collecting custom field data from the templates.
992 * This directive does not direct display, it just passes data up to the
995 .directive('egGridField', function() {
1000 flesher: '=', // optional; function that can flesh a linked field, given the value
1001 name : '@', // required; unique name
1002 path : '@', // optional; flesh path
1003 ignore: '@', // optional; fields to ignore when path is a wildcard
1004 label : '@', // optional; display label
1005 flex : '@', // optional; default flex width
1006 align : '@', // optional; default alignment, left/center/right
1007 dateformat : '@', // optional: passed down to egGridValueFilter
1009 // if a field is part of an IDL object, but we are unable to
1010 // determine the class, because it's nested within a hash
1011 // (i.e. we can't navigate directly to the object via the IDL),
1012 // idlClass lets us specify the class. This is particularly
1013 // useful for nested wildcard fields.
1014 parentIdlClass : '@',
1016 // optional: for non-IDL columns, specifying a datatype
1017 // lets the caller control which display filter is used.
1018 // datatype should match the standard IDL datatypes.
1021 link : function(scope, element, attrs, egGridCtrl) {
1023 // boolean fields are presented as value-less attributes
1032 'required' // if set, always fetch data for this column
1035 if (angular.isDefined(attrs[field]))
1036 scope[field] = true;
1040 // any HTML content within the field is its custom template
1041 var tmpl = element.html();
1042 if (tmpl && !tmpl.match(/^\s*$/))
1043 scope.template = tmpl
1045 egGridCtrl.columnsProvider.add(scope);
1052 * eg-grid-action : used for specifying actions which may be applied
1053 * to items within the grid.
1055 .directive('egGridAction', function() {
1057 require : '^egGrid',
1061 group : '@', // Action group, ungrouped if not set
1062 label : '@', // Action label
1063 handler : '=', // Action function handler
1065 disabled : '=', // function
1068 link : function(scope, element, attrs, egGridCtrl) {
1069 egGridCtrl.addAction({
1071 group : scope.group,
1072 label : scope.label,
1073 divider : scope.divider,
1074 handler : scope.handler,
1075 disabled : scope.disabled,
1082 .factory('egGridColumnsProvider', ['egCore', function(egCore) {
1084 function ColumnsProvider(args) {
1087 cols.stockVisible = [];
1088 cols.idlClass = args.idlClass;
1089 cols.defaultToHidden = args.defaultToHidden;
1090 cols.defaultToNoSort = args.defaultToNoSort;
1091 cols.defaultToNoMultiSort = args.defaultToNoMultiSort;
1093 // resets column width, visibility, and sort behavior
1094 // Visibility resets to the visibility settings defined in the
1095 // template (i.e. the original egGridField values).
1096 cols.reset = function() {
1097 angular.forEach(cols.columns, function(col) {
1101 if (cols.stockVisible.indexOf(col.name) > -1) {
1104 col.visible = false;
1109 // returns true if any columns are sortable
1110 cols.hasSortableColumn = function() {
1111 return cols.columns.filter(
1113 return col.sortable || col.multisortable;
1118 cols.showAllColumns = function() {
1119 angular.forEach(cols.columns, function(column) {
1120 column.visible = true;
1124 cols.hideAllColumns = function() {
1125 angular.forEach(cols.columns, function(col) {
1130 cols.indexOf = function(name) {
1131 for (var i = 0; i < cols.columns.length; i++) {
1132 if (cols.columns[i].name == name)
1138 cols.findColumn = function(name) {
1139 return cols.columns[cols.indexOf(name)];
1142 cols.compileAutoColumns = function() {
1143 var idl_class = egCore.idl.classes[cols.idlClass];
1146 idl_class.fields.sort(
1147 function(a, b) { return a.name < b.name ? -1 : 1 }),
1149 if (field.virtual) return;
1150 if (field.datatype == 'link' || field.datatype == 'org_unit') {
1151 // if the field is a link and the linked class has a
1152 // "selector" field specified, use the selector field
1153 // as the display field for the columns.
1154 // flattener will take care of the fleshing.
1155 if (field['class']) {
1156 var selector_field = egCore.idl.classes[field['class']].fields
1157 .filter(function(f) { return Boolean(f.selector) })[0];
1158 if (selector_field) {
1159 field.path = field.name + '.' + selector_field.selector;
1163 cols.add(field, true);
1168 // if a column definition has a path with a wildcard, create
1169 // columns for all non-virtual fields at the specified
1170 // position in the path.
1171 cols.expandPath = function(colSpec) {
1173 var ignoreList = [];
1175 ignoreList = colSpec.ignore.split(' ');
1177 var dotpath = colSpec.path.replace(/\.?\*$/,'');
1181 if (colSpec.parentIdlClass) {
1182 class_obj = egCore.idl.classes[colSpec.parentIdlClass];
1184 class_obj = egCore.idl.classes[cols.idlClass];
1187 if (!class_obj) return;
1189 console.debug('egGrid: auto dotpath is: ' + dotpath);
1190 var path_parts = dotpath.split(/\./);
1192 // find the IDL class definition for the last element in the
1193 // path before the .*
1194 // an empty path_parts means expand the root class
1196 for (var path_idx in path_parts) {
1197 var part = path_parts[path_idx];
1198 idl_field = class_obj.field_map[part];
1200 // unless we're at the end of the list, this field should
1201 // link to another class.
1202 if (idl_field && idl_field['class'] && (
1203 idl_field.datatype == 'link' ||
1204 idl_field.datatype == 'org_unit')) {
1205 class_obj = egCore.idl.classes[idl_field['class']];
1207 if (path_idx < (path_parts.length - 1)) {
1208 // we ran out of classes to hop through before
1209 // we ran out of path components
1210 console.error("egGrid: invalid IDL path: " + dotpath);
1217 angular.forEach(class_obj.fields, function(field) {
1219 // Only show wildcard fields where we have data to show
1220 // Virtual and un-fleshed links will not have any data.
1221 if (field.virtual ||
1222 (field.datatype == 'link' || field.datatype == 'org_unit') ||
1223 ignoreList.indexOf(field.name) > -1
1227 var col = cols.cloneFromScope(colSpec);
1228 col.path = (dotpath ? dotpath + '.' + field.name : field.name);
1229 console.debug('egGrid: field: ' +field.name + '; parent field: ' + js2JSON(idl_field));
1230 cols.add(col, false, true,
1231 {idl_parent : idl_field, idl_field : field, idl_class : class_obj});
1234 cols.columns = cols.columns.sort(
1236 if (a.explicit) return -1;
1237 if (b.explicit) return 1;
1238 if (a.idlclass && b.idlclass) {
1239 return a.idlclass < b.idlclass ? -1 : 1;
1240 return a.idlclass > b.idlclass ? 1 : -1;
1242 if (a.path && b.path) {
1243 return a.path < b.path ? -1 : 1;
1244 return a.path > b.path ? 1 : -1;
1247 return a.label < b.label ? -1 : 1;
1254 "egGrid: wildcard path does not resolve to an object: "
1259 // angular.clone(scopeObject) is not permittable. Manually copy
1260 // the fields over that we need (so the scope object can go away).
1261 cols.cloneFromScope = function(colSpec) {
1263 flesher : colSpec.flesher,
1264 name : colSpec.name,
1265 label : colSpec.label,
1266 path : colSpec.path,
1267 align : colSpec.align || 'left',
1268 flex : Number(colSpec.flex) || 2,
1269 sort : Number(colSpec.sort) || 0,
1270 required : colSpec.required,
1271 linkpath : colSpec.linkpath,
1272 template : colSpec.template,
1273 visible : colSpec.visible,
1274 hidden : colSpec.hidden,
1275 datatype : colSpec.datatype,
1276 sortable : colSpec.sortable,
1277 nonsortable : colSpec.nonsortable,
1278 multisortable : colSpec.multisortable,
1279 nonmultisortable : colSpec.nonmultisortable,
1280 dateformat : colSpec.dateformat,
1281 parentIdlClass : colSpec.parentIdlClass
1286 // Add a column to the columns collection.
1287 // Columns may come from a slim eg-columns-field or
1288 // directly from the IDL.
1289 cols.add = function(colSpec, fromIDL, fromExpand, idl_info) {
1291 // First added column with the specified path takes precedence.
1292 // This allows for specific definitions followed by wildcard
1293 // definitions. If a match is found, back out.
1294 if (cols.columns.filter(function(c) {
1295 return (c.path == colSpec.path) })[0]) {
1296 console.debug('skipping pre-existing column ' + colSpec.path);
1300 var column = fromExpand ? colSpec : cols.cloneFromScope(colSpec);
1302 if (column.path && column.path.match(/\*$/))
1303 return cols.expandPath(colSpec);
1305 if (!fromExpand) column.explicit = true;
1307 if (!column.name) column.name = column.path;
1308 if (!column.path) column.path = column.name;
1310 if (column.visible || (!cols.defaultToHidden && !column.hidden))
1311 column.visible = true;
1313 if (column.sortable || (!cols.defaultToNoSort && !column.nonsortable))
1314 column.sortable = true;
1316 if (column.multisortable ||
1317 (!cols.defaultToNoMultiSort && !column.nonmultisortable))
1318 column.multisortable = true;
1320 cols.columns.push(column);
1322 // Track which columns are visible by default in case we
1323 // need to reset column visibility
1325 cols.stockVisible.push(column.name);
1327 if (fromIDL) return; // directly from egIDL. nothing left to do.
1329 // lookup the matching IDL field
1330 if (!idl_info && cols.idlClass)
1331 idl_info = cols.idlFieldFromPath(column.path);
1334 // column is not represented within the IDL
1335 column.adhoc = true;
1339 column.datatype = idl_info.idl_field.datatype;
1341 if (!column.label) {
1342 column.label = idl_info.idl_field.label || column.name;
1345 if (fromExpand && idl_info.idl_class) {
1346 column.idlclass = '';
1347 if (idl_info.idl_parent) {
1348 column.idlclass = idl_info.idl_parent.label || idl_info.idl_parent.name;
1350 column.idlclass += idl_info.idl_class.label || idl_info.idl_class.name;
1355 // finds the IDL field from the dotpath, using the columns
1356 // idlClass as the base.
1357 cols.idlFieldFromPath = function(dotpath) {
1358 var class_obj = egCore.idl.classes[cols.idlClass];
1359 var path_parts = dotpath.split(/\./);
1363 for (var path_idx in path_parts) {
1364 var part = path_parts[path_idx];
1365 idl_parent = idl_field;
1366 idl_field = class_obj.field_map[part];
1368 if (idl_field && idl_field['class'] && (
1369 idl_field.datatype == 'link' ||
1370 idl_field.datatype == 'org_unit')) {
1371 class_obj = egCore.idl.classes[idl_field['class']];
1373 // else, path is not in the IDL, which is fine
1376 if (!idl_field) return null;
1379 idl_parent: idl_parent,
1380 idl_field : idl_field,
1381 idl_class : class_obj
1387 instance : function(args) { return new ColumnsProvider(args) }
1393 * Generic data provider template class. This is basically an abstract
1394 * class factory service whose instances can be locally modified to
1395 * meet the needs of each individual grid.
1397 .factory('egGridDataProvider',
1398 ['$q','$timeout','$filter','egCore',
1399 function($q , $timeout , $filter , egCore) {
1401 function GridDataProvider(args) {
1402 var gridData = this;
1403 if (!args) args = {};
1406 gridData.get = args.get;
1407 gridData.query = args.query;
1408 gridData.idlClass = args.idlClass;
1409 gridData.columnsProvider = args.columnsProvider;
1411 // Delivers a stream of array data via promise.notify()
1412 // Useful for passing an array of data to egGrid.get()
1413 // If a count is provided, the array will be trimmed to
1414 // the range defined by count and offset
1415 gridData.arrayNotifier = function(arr, offset, count) {
1416 if (!arr || arr.length == 0) return $q.when();
1417 if (count) arr = arr.slice(offset, offset + count);
1418 var def = $q.defer();
1419 // promise notifications are only witnessed when delivered
1420 // after the caller has his hands on the promise object
1421 $timeout(function() {
1422 angular.forEach(arr, def.notify);
1428 // Calls the grid refresh function. Once instantiated, the
1429 // grid will replace this function with it's own refresh()
1430 gridData.refresh = function(noReset) { }
1432 if (!gridData.get) {
1433 // returns a promise whose notify() delivers items
1434 gridData.get = function(index, count) {
1435 console.error("egGridDataProvider.get() not implemented");
1439 // attempts a flat field lookup first. If the column is not
1440 // found on the top-level object, attempts a nested lookup
1441 // TODO: consider a caching layer to speed up template
1442 // rendering, particularly for nested objects?
1443 gridData.itemFieldValue = function(item, column) {
1445 if (column.name in item) {
1446 if (typeof item[column.name] == 'function') {
1447 val = item[column.name]();
1449 val = item[column.name];
1452 val = gridData.nestedItemFieldValue(item, column);
1458 // TODO: deprecate me
1459 gridData.flatItemFieldValue = function(item, column) {
1460 console.warn('gridData.flatItemFieldValue deprecated; '
1461 + 'leave provider.itemFieldValue unset');
1462 return item[column.name];
1465 // given an object and a dot-separated path to a field,
1466 // extract the value of the field. The path can refer
1467 // to function names or object attributes. If the final
1468 // value is an IDL field, run the value through its
1469 // corresponding output filter.
1470 gridData.nestedItemFieldValue = function(obj, column) {
1471 item = obj; // keep a copy around
1473 if (obj === null || obj === undefined || obj === '') return '';
1474 if (!column.path) return obj;
1477 var parts = column.path.split('.');
1479 angular.forEach(parts, function(step, idx) {
1480 // object is not fleshed to the expected extent
1481 if (typeof obj != 'object') {
1482 if (typeof obj != 'undefined' && column.flesher) {
1483 obj = column.flesher(obj, column, item);
1490 var cls = obj.classname;
1491 if (cls && (class_obj = egCore.idl.classes[cls])) {
1492 idl_field = class_obj.field_map[step];
1493 obj = obj[step] ? obj[step]() : '';
1495 if (angular.isFunction(obj[step])) {
1503 // We found a nested IDL object which may or may not have
1504 // been configured as a top-level column. Grab the datatype.
1505 if (idl_field && !column.datatype)
1506 column.datatype = idl_field.datatype;
1508 if (obj === null || obj === undefined || obj === '') return '';
1514 instance : function(args) {
1515 return new GridDataProvider(args);
1522 // Factory service for egGridDataManager instances, which are
1523 // responsible for collecting flattened grid data.
1524 .factory('egGridFlatDataProvider',
1525 ['$q','egCore','egGridDataProvider',
1526 function($q , egCore , egGridDataProvider) {
1529 instance : function(args) {
1530 var provider = egGridDataProvider.instance(args);
1532 provider.get = function(offset, count) {
1534 // no query means no call
1535 if (!provider.query ||
1536 angular.equals(provider.query, {}))
1539 // find all of the currently visible columns
1540 var queryFields = {}
1541 angular.forEach(provider.columnsProvider.columns,
1543 // only query IDL-tracked columns
1544 if (!col.adhoc && (col.required || col.visible))
1545 queryFields[col.name] = col.path;
1549 return egCore.net.request(
1551 'open-ils.fielder.flattened_search',
1552 egCore.auth.token(), provider.idlClass,
1553 queryFields, provider.query,
1554 { sort : provider.sort,
1560 //provider.itemFieldValue = provider.flatItemFieldValue;
1567 .directive('egGridColumnDragSource', function() {
1570 require : '^egGrid',
1571 link : function(scope, element, attrs, egGridCtrl) {
1572 angular.element(element).attr('draggable', 'true');
1574 element.bind('dragstart', function(e) {
1575 egGridCtrl.dragColumn = attrs.column;
1576 egGridCtrl.dragType = attrs.dragType || 'move'; // or resize
1577 egGridCtrl.colResizeDir = 0;
1579 if (egGridCtrl.dragType == 'move') {
1580 // style the column getting moved
1581 angular.element(e.target).addClass(
1582 'eg-grid-column-move-handle-active');
1586 element.bind('dragend', function(e) {
1587 if (egGridCtrl.dragType == 'move') {
1588 angular.element(e.target).removeClass(
1589 'eg-grid-column-move-handle-active');
1596 .directive('egGridColumnDragDest', function() {
1599 require : '^egGrid',
1600 link : function(scope, element, attrs, egGridCtrl) {
1602 element.bind('dragover', function(e) { // required for drop
1603 e.stopPropagation();
1605 e.dataTransfer.dropEffect = 'move';
1607 if (egGridCtrl.colResizeDir == 0) return; // move
1609 var cols = egGridCtrl.columnsProvider;
1610 var srcCol = egGridCtrl.dragColumn;
1611 var srcColIdx = cols.indexOf(srcCol);
1613 if (egGridCtrl.colResizeDir == -1) {
1614 if (cols.indexOf(attrs.column) <= srcColIdx) {
1615 egGridCtrl.modifyColumnFlex(
1616 egGridCtrl.columnsProvider.findColumn(
1617 egGridCtrl.dragColumn), -1);
1618 if (cols.columns[srcColIdx+1]) {
1619 // source column shrinks by one, column to the
1620 // right grows by one.
1621 egGridCtrl.modifyColumnFlex(
1622 cols.columns[srcColIdx+1], 1);
1627 if (cols.indexOf(attrs.column) > srcColIdx) {
1628 egGridCtrl.modifyColumnFlex(
1629 egGridCtrl.columnsProvider.findColumn(
1630 egGridCtrl.dragColumn), 1);
1631 if (cols.columns[srcColIdx+1]) {
1632 // source column grows by one, column to the
1633 // right grows by one.
1634 egGridCtrl.modifyColumnFlex(
1635 cols.columns[srcColIdx+1], -1);
1643 element.bind('dragenter', function(e) {
1644 e.stopPropagation();
1646 if (egGridCtrl.dragType == 'move') {
1647 angular.element(e.target).addClass('eg-grid-col-hover');
1649 // resize grips are on the right side of each column.
1650 // dragenter will either occur on the source column
1651 // (dragging left) or the column to the right.
1652 if (egGridCtrl.colResizeDir == 0) {
1653 if (egGridCtrl.dragColumn == attrs.column) {
1654 egGridCtrl.colResizeDir = -1; // west
1656 egGridCtrl.colResizeDir = 1; // east
1662 element.bind('dragleave', function(e) {
1663 e.stopPropagation();
1665 if (egGridCtrl.dragType == 'move') {
1666 angular.element(e.target).removeClass('eg-grid-col-hover');
1670 element.bind('drop', function(e) {
1671 e.stopPropagation();
1673 egGridCtrl.colResizeDir = 0;
1674 if (egGridCtrl.dragType == 'move') {
1675 angular.element(e.target).removeClass('eg-grid-col-hover');
1676 egGridCtrl.onColumnDrop(attrs.column); // move the column
1683 .directive('egGridMenuItem', function() {
1686 require : '^egGrid',
1692 handler : '=', // onclick handler function
1693 divider : '=', // if true, show a divider only
1694 handlerData : '=', // if set, passed as second argument to handler
1695 disabled : '=', // function
1696 hidden : '=' // function
1698 link : function(scope, element, attrs, egGridCtrl) {
1699 egGridCtrl.addMenuItem({
1700 checkbox : scope.checkbox,
1701 checked : scope.checked ? true : false,
1702 label : scope.label,
1703 standalone : scope.standalone ? true : false,
1704 handler : scope.handler,
1705 divider : scope.divider,
1706 disabled : scope.disabled,
1707 hidden : scope.hidden,
1708 handlerData : scope.handlerData
1718 * Translates bare IDL object values into display values.
1719 * 1. Passes dates through the angular date filter
1720 * 2. Translates bools to Booleans so the browser can display translated
1721 * value. (Though we could manually translate instead..)
1722 * Others likely to follow...
1724 .filter('egGridValueFilter', ['$filter', function($filter) {
1725 return function(value, column) {
1726 switch(column.datatype) {
1729 // Browser will translate true/false for us
1731 case '1' : // legacy
1735 case '0' : // legacy
1738 // value may be null, '', etc.
1739 default : return '';
1742 // canned angular date filter FTW
1743 if (!column.dateformat)
1744 column.dateformat = 'shortDate';
1745 return $filter('date')(value, column.dateformat);
1747 return $filter('currency')(value);