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 // -display : columns are hidden by default
35 // -sort : columns are unsortable by default
36 // -multisort : sort priorities config disabled by default
39 // optional primary grid label
42 // if true, use the IDL class label as the mainLabel
45 // optional context menu label
48 // Hash of control functions.
50 // These functions are defined by the calling scope and
51 // invoked as-is by the grid w/ the specified parameters.
53 // itemRetrieved : function(item) {}
54 // allItemsRetrieved : function() {}
57 // If defined, the grid will watch the return value from
58 // the function defined at watchQuery on each digest and
59 // re-draw the grid when query changes occur.
61 // watchQuery : function() { /* return grid query */ }
64 // These functions are defined by the grid and thus
65 // replace any values defined for these attributes from the
68 // activateItem : function(item) {}
69 // allItems : function(allItems) {}
70 // selectedItems : function(selected) {}
71 // selectItems : function(ids) {}
72 // setQuery : function(queryStruct) {} // causes reload
73 // setSort : function(sortSturct) {} // causes reload
77 // TODO: avoid hard-coded url
78 templateUrl : '/eg/staff/share/t_autogrid',
80 link : function(scope, element, attrs) {
81 // link() is called after page compilation, which means our
82 // eg-grid-field's have been parsed and loaded. Now it's
83 // safe to perform our initial page load.
85 // load auto fields after eg-grid-field's so they are not clobbered
86 scope.handleAutoFields();
89 scope.grid_element = element;
91 .find('.eg-grid-content-body')
92 .bind('contextmenu', scope.showActionContextMenu);
96 '$scope','$q','egCore','egGridFlatDataProvider','$location',
97 'egGridColumnsProvider','$filter','$window','$sce','$timeout',
98 function($scope, $q , egCore, egGridFlatDataProvider , $location,
99 egGridColumnsProvider , $filter , $window , $sce , $timeout) {
103 grid.init = function() {
106 $scope.showGridConf = false;
107 grid.totalCount = -1;
108 $scope.selected = {};
109 $scope.actionGroups = [{actions:[]}]; // Grouped actions for selected items
110 $scope.menuItems = []; // global actions
112 // remove some unneeded values from the scope to reduce bloat
114 grid.idlClass = $scope.idlClass;
115 delete $scope.idlClass;
117 grid.persistKey = $scope.persistKey;
118 delete $scope.persistKey;
120 var stored_limit = 0;
121 if (grid.persistKey) {
122 var stored_limit = Number(
123 egCore.hatch.getLocalItem('eg.grid.' + grid.persistKey + '.limit')
126 grid.limit = Number(stored_limit) || Number($scope.pageSize) || 25;
128 grid.indexField = $scope.idField;
129 delete $scope.idField;
131 grid.dataProvider = $scope.itemsProvider;
133 var features = ($scope.features) ?
134 $scope.features.split(',') : [];
135 delete $scope.features;
137 if (!grid.indexField && grid.idlClass)
138 grid.indexField = egCore.idl.classes[grid.idlClass].pkey;
140 grid.columnsProvider = egGridColumnsProvider.instance({
141 idlClass : grid.idlClass,
142 defaultToHidden : (features.indexOf('-display') > -1),
143 defaultToNoSort : (features.indexOf('-sort') > -1),
144 defaultToNoMultiSort : (features.indexOf('-multisort') > -1)
147 $scope.handleAutoFields = function() {
148 if ($scope.autoFields) {
149 if (grid.autoLabel) {
151 egCore.idl.classes[grid.idlClass].label;
153 grid.columnsProvider.compileAutoColumns();
154 delete $scope.autoFields;
158 if (!grid.dataProvider) {
159 // no provider, um, provided.
160 // Use a flat data provider
162 grid.selfManagedData = true;
163 grid.dataProvider = egGridFlatDataProvider.instance({
164 indexField : grid.indexField,
165 idlClass : grid.idlClass,
166 columnsProvider : grid.columnsProvider,
171 $scope.itemFieldValue = grid.dataProvider.itemFieldValue;
172 $scope.indexValue = function(item) {
173 return grid.indexValue(item)
176 grid.applyControlFunctions();
178 grid.loadConfig().then(function() {
179 // link columns to scope after loadConfig(), since it
180 // replaces the columns array.
181 $scope.columns = grid.columnsProvider.columns;
184 // NOTE: grid.collect() is first called from link(), not here.
187 // link our control functions into the gridControls
188 // scope object so the caller can access them.
189 grid.applyControlFunctions = function() {
191 // we use some of these controls internally, so sett
192 // them up even if the caller doesn't request them.
193 var controls = $scope.gridControls || {};
195 // link in the control functions
196 controls.selectedItems = function() {
197 return grid.getSelectedItems()
200 controls.allItems = function() {
204 controls.selectItems = function(ids) {
206 $scope.selected = {};
207 angular.forEach(ids, function(i) {
208 $scope.selected[''+i] = true;
212 // if the caller provided a functional setQuery,
213 // extract the value before replacing it
214 if (controls.setQuery) {
215 grid.dataProvider.query =
219 controls.setQuery = function(query) {
220 grid.dataProvider.query = query;
224 if (controls.watchQuery) {
225 // capture the initial query value
226 grid.dataProvider.query = controls.watchQuery();
229 $scope.gridWatchQuery = controls.watchQuery;
230 $scope.$watch('gridWatchQuery()', function(newv) {
231 controls.setQuery(newv);
235 // if the caller provided a functional setSort
236 // extract the value before replacing it
237 grid.dataProvider.sort =
238 controls.setSort ? controls.setSort() : [];
240 controls.setSort = function(sort) {
244 controls.refresh = function(noReset) {
245 if (!noReset) grid.offset = 0;
249 controls.setLimit = function(limit,forget) {
250 if (!forget && grid.persistKey)
251 egCore.hatch.setLocalItem('eg.grid.' + grid.persistKey + '.limit', limit);
254 controls.getLimit = function() {
257 controls.setOffset = function(offset) {
258 grid.offset = offset;
260 controls.getOffset = function() {
264 grid.dataProvider.refresh = controls.refresh;
265 grid.controls = controls;
268 // add a new (global) grid menu item
269 grid.addMenuItem = function(item) {
270 $scope.menuItems.push(item);
271 var handler = item.handler;
272 item.handler = function() {
273 $scope.gridMenuIsOpen = false; // close menu
276 item.handlerData, grid.getSelectedItems());
281 // add a selected-items action
282 grid.addAction = function(act) {
284 $scope.actionGroups.forEach(function(g){
285 if (g.label === act.group) {
291 $scope.actionGroups.push({
298 // remove the stored column configuration preferenc, then recover
299 // the column visibility information from the initial page load.
300 $scope.resetColumns = function() {
301 $scope.gridColumnPickerIsOpen = false;
302 egCore.hatch.removeItem('eg.grid.' + grid.persistKey)
304 grid.columnsProvider.reset();
305 if (grid.selfManagedData) grid.collect();
309 $scope.showAllColumns = function() {
310 $scope.gridColumnPickerIsOpen = false;
311 grid.columnsProvider.showAllColumns();
312 if (grid.selfManagedData) grid.collect();
315 $scope.hideAllColumns = function() {
316 $scope.gridColumnPickerIsOpen = false;
317 grid.columnsProvider.hideAllColumns();
318 // note: no need to fetch new data if no columns are visible
321 $scope.toggleColumnVisibility = function(col) {
322 $scope.gridColumnPickerIsOpen = false;
323 col.visible = !col.visible;
325 // egGridFlatDataProvider only retrieves data to be
326 // displayed. When column visibility changes, it's
327 // necessary to fetch the newly visible column data.
328 if (grid.selfManagedData) grid.collect();
331 // save the columns configuration (position, sort, width) to
332 // eg.grid.<persist-key>
333 $scope.saveConfig = function() {
334 $scope.gridColumnPickerIsOpen = false;
336 if (!grid.persistKey) {
338 "Cannot save settings without a grid persist-key");
342 // only store information about visible columns.
343 var conf = grid.columnsProvider.columns.filter(
344 function(col) {return Boolean(col.visible) });
346 // now scrunch the data down to just the needed info
347 conf = conf.map(function(col) {
348 var c = {name : col.name}
349 // Apart from the name, only store non-default values.
350 // No need to store col.visible, since that's implicit
351 if (col.flex != 2) c.flex = col.flex;
352 if (Number(col.sort)) c.sort = Number(c.sort);
356 egCore.hatch.setItem('eg.grid.' + grid.persistKey, conf)
358 // Save operation performed from the grid configuration UI.
359 // Hide the configuration UI and re-draw w/ sort applied
360 if ($scope.showGridConf)
361 $scope.toggleConfDisplay();
365 // load the columns configuration (position, sort, width) from
366 // eg.grid.<persist-key> and apply the loaded settings to the
367 // columns on our columnsProvider
368 grid.loadConfig = function() {
369 if (!grid.persistKey) return $q.when();
371 return egCore.hatch.getItem('eg.grid.' + grid.persistKey)
372 .then(function(conf) {
375 var columns = grid.columnsProvider.columns;
378 angular.forEach(conf, function(col) {
379 var grid_col = columns.filter(
380 function(c) {return c.name == col.name})[0];
383 // saved column does not match a column in the
384 // current grid. skip it.
388 grid_col.flex = col.flex || 2;
389 grid_col.sort = col.sort || 0;
390 // all saved columns are assumed to be true
391 grid_col.visible = true;
392 new_cols.push(grid_col);
395 // columns which are not expressed within the saved
396 // configuration are marked as non-visible and
397 // appended to the end of the new list of columns.
398 angular.forEach(columns, function(col) {
399 var found = conf.filter(
400 function(c) {return (c.name == col.name)})[0];
407 grid.columnsProvider.columns = new_cols;
412 $scope.onContextMenu = function($event) {
413 var col = angular.element($event.target).attr('column');
414 console.log('selected column ' + col);
417 $scope.page = function() {
418 return (grid.offset / grid.limit) + 1;
421 $scope.goToPage = function(page) {
423 if (angular.isNumber(page) && page > 0) {
424 grid.offset = (page - 1) * grid.limit;
429 $scope.offset = function(o) {
430 if (angular.isNumber(o))
435 $scope.limit = function(l) {
436 if (angular.isNumber(l)) {
438 egCore.hatch.setLocalItem('eg.grid.' + grid.persistKey + '.limit', l);
444 $scope.onFirstPage = function() {
445 return grid.offset == 0;
448 $scope.hasNextPage = function() {
449 // we have less data than requested, there must
450 // not be any more pages
451 if (grid.count() < grid.limit) return false;
453 // if the total count is not known, assume that a full
454 // page of data implies more pages are available.
455 if (grid.totalCount == -1) return true;
457 // we have a full page of data, but is there more?
458 return grid.totalCount > (grid.offset + grid.count());
461 $scope.incrementPage = function() {
462 grid.offset += grid.limit;
466 $scope.decrementPage = function() {
467 if (grid.offset < grid.limit) {
470 grid.offset -= grid.limit;
475 // number of items loaded for the current page of results
476 grid.count = function() {
477 return $scope.items.length;
480 // returns the unique identifier value for the provided item
481 // for internal consistency, indexValue is always coerced
483 grid.indexValue = function(item) {
484 if (angular.isObject(item)) {
486 if (angular.isFunction(item[grid.indexField]))
487 return ''+item[grid.indexField]();
488 return ''+item[grid.indexField]; // flat data
491 // passed a non-object; assume it's an index
495 // fires the hide handler function for a context action
496 $scope.actionHide = function(action) {
500 return action.hide(action);
503 // fires the action handler function for a context action
504 $scope.actionLauncher = function(action) {
505 if (!action.handler) {
507 'No handler specified for "' + action.label + '"');
511 action.handler(grid.getSelectedItems());
513 console.error('Error executing handler for "'
514 + action.label + '" => ' + E + "\n" + E.stack);
517 if ($scope.action_context_showing) $scope.hideActionContextMenu();
522 $scope.hideActionContextMenu = function () {
523 $($scope.menu_dom).css({
525 width: $scope.action_context_width,
526 top: $scope.action_context_y,
527 left: $scope.action_context_x
529 $($scope.action_context_parent).append($scope.menu_dom);
530 $scope.action_context_oldy = $scope.action_context_oldx = 0;
531 $('body').unbind('click.remove_context_menu_'+$scope.action_context_index);
532 $scope.action_context_showing = false;
535 $scope.action_context_showing = false;
536 $scope.showActionContextMenu = function ($event) {
538 // Have to gather these here, instead of inside link()
539 if (!$scope.menu_dom) $scope.menu_dom = $($scope.grid_element).find('.grid-action-dropdown')[0];
540 if (!$scope.action_context_parent) $scope.action_context_parent = $($scope.menu_dom).parent();
542 if (!grid.getSelectedItems().length) // Nothing selected, fire the click event
543 $event.target.click();
545 if (!$scope.action_context_showing) {
546 $scope.action_context_width = $($scope.menu_dom).css('width');
547 $scope.action_context_y = $($scope.menu_dom).css('top');
548 $scope.action_context_x = $($scope.menu_dom).css('left');
549 $scope.action_context_showing = true;
550 $scope.action_context_index = Math.floor((Math.random() * 1000) + 1);
552 $('body').append($($scope.menu_dom));
553 $('body').bind('click.remove_context_menu_'+$scope.action_context_index, $scope.hideActionContextMenu);
556 $($scope.menu_dom).css({
558 width: $scope.action_context_width,
566 // returns the list of selected item objects
567 grid.getSelectedItems = function() {
568 return $scope.items.filter(
570 return Boolean($scope.selected[grid.indexValue(item)]);
575 grid.getItemByIndex = function(index) {
576 for (var i = 0; i < $scope.items.length; i++) {
577 var item = $scope.items[i];
578 if (grid.indexValue(item) == index)
583 // selects one row after deselecting all of the others
584 grid.selectOneItem = function(index) {
585 $scope.selected = {};
586 $scope.selected[index] = true;
589 // selects or deselects an item, without affecting the others.
590 // returns true if the item is selected; false if de-selected.
591 grid.toggleSelectOneItem = function(index) {
592 if ($scope.selected[index]) {
593 delete $scope.selected[index];
596 return $scope.selected[index] = true;
600 grid.selectAllItems = function() {
601 angular.forEach($scope.items, function(item) {
602 $scope.selected[grid.indexValue(item)] = true
606 $scope.$watch('selectAll', function(newVal) {
608 grid.selectAllItems();
610 $scope.selected = {};
614 // returns true if item1 appears in the list before item2;
615 // false otherwise. this is slightly more efficient that
616 // finding the position of each then comparing them.
617 // item1 / item2 may be an item or an item index
618 grid.itemComesBefore = function(itemOrIndex1, itemOrIndex2) {
619 var idx1 = grid.indexValue(itemOrIndex1);
620 var idx2 = grid.indexValue(itemOrIndex2);
622 // use for() for early exit
623 for (var i = 0; i < $scope.items.length; i++) {
624 var idx = grid.indexValue($scope.items[i]);
625 if (idx == idx1) return true;
626 if (idx == idx2) return false;
631 // 0-based position of item in the current data set
632 grid.indexOf = function(item) {
633 var idx = grid.indexValue(item);
634 for (var i = 0; i < $scope.items.length; i++) {
635 if (grid.indexValue($scope.items[i]) == idx)
641 grid.modifyColumnFlex = function(column, val) {
643 // prevent flex:0; use hiding instead
647 $scope.modifyColumnFlex = function(col, val) {
648 grid.modifyColumnFlex(col, val);
651 // handles click, control-click, and shift-click
652 $scope.handleRowClick = function($event, item) {
653 var index = grid.indexValue(item);
655 var origSelected = Object.keys($scope.selected);
657 if ($event.ctrlKey || $event.metaKey /* mac command */) {
659 if (grid.toggleSelectOneItem(index))
660 grid.lastSelectedItemIndex = index;
662 } else if ($event.shiftKey) {
665 if (!grid.lastSelectedItemIndex ||
666 index == grid.lastSelectedItemIndex) {
667 grid.selectOneItem(index);
668 grid.lastSelectedItemIndex = index;
672 var selecting = false;
673 var ascending = grid.itemComesBefore(
674 grid.lastSelectedItemIndex, item);
676 grid.indexOf(grid.lastSelectedItemIndex);
678 // update to new last-selected
679 grid.lastSelectedItemIndex = index;
681 // select each row between the last selected and
682 // currently selected items
684 startPos += ascending ? 1 : -1;
685 var curItem = $scope.items[startPos];
687 var curIdx = grid.indexValue(curItem);
688 $scope.selected[curIdx] = true;
689 if (curIdx == index) break; // all done
694 grid.selectOneItem(index);
695 grid.lastSelectedItemIndex = index;
699 // Builds a sort expression from column sort priorities.
700 // called on page load and any time the priorities are modified.
701 grid.compileSort = function() {
702 var sortList = grid.columnsProvider.columns.filter(
703 function(col) { return Number(col.sort) != 0 }
706 if (Math.abs(a.sort) < Math.abs(b.sort))
712 if (sortList.length) {
713 grid.dataProvider.sort = sortList.map(function(col) {
715 blob[col.name] = col.sort < 0 ? 'desc' : 'asc';
721 // builds a sort expression using a single column,
722 // toggling between ascending and descending sort.
723 $scope.quickSort = function(col_name) {
724 var sort = grid.dataProvider.sort;
725 if (sort && sort.length &&
726 sort[0] == col_name) {
728 blob[col_name] = 'desc';
729 grid.dataProvider.sort = [blob];
731 grid.dataProvider.sort = [col_name];
738 // show / hide the grid configuration row
739 $scope.toggleConfDisplay = function() {
740 if ($scope.showGridConf) {
741 $scope.showGridConf = false;
742 if (grid.columnsProvider.hasSortableColumn()) {
743 // only refresh the grid if the user has the
744 // ability to modify the sort priorities.
750 $scope.showGridConf = true;
753 $scope.gridColumnPickerIsOpen = false;
756 // called when a dragged column is dropped onto itself
757 // or any other column
758 grid.onColumnDrop = function(target) {
759 if (angular.isUndefined(target)) return;
760 if (target == grid.dragColumn) return;
761 var srcIdx, targetIdx, srcCol;
762 angular.forEach(grid.columnsProvider.columns,
764 if (col.name == grid.dragColumn) {
767 } else if (col.name == target) {
773 if (srcIdx < targetIdx) targetIdx--;
775 // move src column from old location to new location in
776 // the columns array, then force a page refresh
777 grid.columnsProvider.columns.splice(srcIdx, 1);
778 grid.columnsProvider.columns.splice(targetIdx, 0, srcCol);
782 // prepares a string for inclusion within a CSV document
783 // by escaping commas and quotes and removing newlines.
784 grid.csvDatum = function(str) {
787 str = str.replace(/\n/g, '');
788 if (str.match(/\,/) || str.match(/"/)) {
789 str = str.replace(/"/g, '""');
790 str = '"' + str + '"';
795 // sets the download file name and inserts the current CSV
796 // into a Blob URL for browser download.
797 $scope.generateCSVExportURL = function() {
798 $scope.gridColumnPickerIsOpen = false;
800 // let the file name describe the grid
801 $scope.csvExportFileName =
802 ($scope.mainLabel || grid.persistKey || 'eg_grid_data')
803 .replace(/\s+/g, '_') + '_' + $scope.page();
805 // toss the CSV into a Blob and update the export URL
806 var csv = grid.generateCSV();
807 var blob = new Blob([csv], {type : 'text/plain'});
808 $scope.csvExportURL =
809 ($window.URL || $window.webkitURL).createObjectURL(blob);
812 $scope.printCSV = function() {
813 $scope.gridColumnPickerIsOpen = false;
816 content : grid.generateCSV(),
817 content_type : 'text/plain'
821 // generates CSV for the currently visible grid contents
822 grid.generateCSV = function() {
824 var colCount = grid.columnsProvider.columns.length;
827 angular.forEach(grid.columnsProvider.columns,
829 if (!col.visible) return;
830 csvStr += grid.csvDatum(col.label);
835 csvStr = csvStr.replace(/,$/,'\n');
838 angular.forEach($scope.items, function(item) {
839 angular.forEach(grid.columnsProvider.columns,
841 if (!col.visible) return;
843 var val = grid.dataProvider.itemFieldValue(item, col);
844 // filtered value (dates, etc.)
845 val = $filter('egGridValueFilter')(val, col);
846 csvStr += grid.csvDatum(val);
850 csvStr = csvStr.replace(/,$/,'\n');
856 // Interpolate the value for column.linkpath within the context
857 // of the row item to generate the final link URL.
858 $scope.generateLinkPath = function(col, item) {
859 return egCore.strings.$replace(col.linkpath, {item : item});
862 // If a column provides its own HTML template, translate it,
863 // using the current item for the template scope.
864 // note: $sce is required to avoid security restrictions and
865 // is OK here, since the template comes directly from a
866 // local HTML template (not user input).
867 $scope.translateCellTemplate = function(col, item) {
868 var html = egCore.strings.$replace(col.template, {item : item});
869 return $sce.trustAsHtml(html);
872 $scope.collect = function() { grid.collect() }
874 // asks the dataProvider for a page of data
875 grid.collect = function() {
877 // avoid firing the collect if there is nothing to collect.
878 if (grid.selfManagedData && !grid.dataProvider.query) return;
880 if (grid.collecting) return; // avoid parallel collect()
881 grid.collecting = true;
883 console.debug('egGrid.collect() offset='
884 + grid.offset + '; limit=' + grid.limit);
886 // ensure all of our dropdowns are closed
887 // TODO: git rid of these and just use dropdown-toggle,
888 // which is more reliable.
889 $scope.gridColumnPickerIsOpen = false;
890 $scope.gridRowCountIsOpen = false;
891 $scope.gridPageSelectIsOpen = false;
894 $scope.selected = {};
895 grid.dataProvider.get(grid.offset, grid.limit).then(
897 if (grid.controls.allItemsRetrieved)
898 grid.controls.allItemsRetrieved();
903 $scope.items.push(item)
904 if (grid.controls.itemRetrieved)
905 grid.controls.itemRetrieved(item);
907 }).finally(function() {
908 console.debug('egGrid.collect() complete');
909 grid.collecting = false
919 * eg-grid-field : used for collecting custom field data from the templates.
920 * This directive does not direct display, it just passes data up to the
923 .directive('egGridField', function() {
928 name : '@', // required; unique name
929 path : '@', // optional; flesh path
930 ignore: '@', // optional; fields to ignore when path is a wildcard
931 label : '@', // optional; display label
932 flex : '@', // optional; default flex width
933 dateformat : '@', // optional: passed down to egGridValueFilter
935 // if a field is part of an IDL object, but we are unable to
936 // determine the class, because it's nested within a hash
937 // (i.e. we can't navigate directly to the object via the IDL),
938 // idlClass lets us specify the class. This is particularly
939 // useful for nested wildcard fields.
940 parentIdlClass : '@',
942 // optional: for non-IDL columns, specifying a datatype
943 // lets the caller control which display filter is used.
944 // datatype should match the standard IDL datatypes.
947 link : function(scope, element, attrs, egGridCtrl) {
949 // boolean fields are presented as value-less attributes
958 'required' // if set, always fetch data for this column
961 if (angular.isDefined(attrs[field]))
966 // any HTML content within the field is its custom template
967 var tmpl = element.html();
968 if (tmpl && !tmpl.match(/^\s*$/))
969 scope.template = tmpl
971 egGridCtrl.columnsProvider.add(scope);
978 * eg-grid-action : used for specifying actions which may be applied
979 * to items within the grid.
981 .directive('egGridAction', function() {
987 group : '@', // Action group, ungrouped if not set
988 label : '@', // Action label
989 handler : '=', // Action function handler
993 link : function(scope, element, attrs, egGridCtrl) {
994 egGridCtrl.addAction({
998 divider : scope.divider,
999 handler : scope.handler
1006 .factory('egGridColumnsProvider', ['egCore', function(egCore) {
1008 function ColumnsProvider(args) {
1011 cols.stockVisible = [];
1012 cols.idlClass = args.idlClass;
1013 cols.defaultToHidden = args.defaultToHidden;
1014 cols.defaultToNoSort = args.defaultToNoSort;
1015 cols.defaultToNoMultiSort = args.defaultToNoMultiSort;
1017 // resets column width, visibility, and sort behavior
1018 // Visibility resets to the visibility settings defined in the
1019 // template (i.e. the original egGridField values).
1020 cols.reset = function() {
1021 angular.forEach(cols.columns, function(col) {
1024 if (cols.stockVisible.indexOf(col.name) > -1) {
1027 col.visible = false;
1032 // returns true if any columns are sortable
1033 cols.hasSortableColumn = function() {
1034 return cols.columns.filter(
1036 return col.sortable || col.multisortable;
1041 cols.showAllColumns = function() {
1042 angular.forEach(cols.columns, function(column) {
1043 column.visible = true;
1047 cols.hideAllColumns = function() {
1048 angular.forEach(cols.columns, function(col) {
1053 cols.indexOf = function(name) {
1054 for (var i = 0; i < cols.columns.length; i++) {
1055 if (cols.columns[i].name == name)
1061 cols.findColumn = function(name) {
1062 return cols.columns[cols.indexOf(name)];
1065 cols.compileAutoColumns = function() {
1066 var idl_class = egCore.idl.classes[cols.idlClass];
1069 idl_class.fields.sort(
1070 function(a, b) { return a.name < b.name ? -1 : 1 }),
1072 if (field.virtual) return;
1073 if (field.datatype == 'link' || field.datatype == 'org_unit') {
1074 // if the field is a link and the linked class has a
1075 // "selector" field specified, use the selector field
1076 // as the display field for the columns.
1077 // flattener will take care of the fleshing.
1078 if (field['class']) {
1079 var selector_field = egCore.idl.classes[field['class']].fields
1080 .filter(function(f) { return Boolean(f.selector) })[0];
1081 if (selector_field) {
1082 field.path = field.name + '.' + selector_field.selector;
1086 cols.add(field, true);
1091 // if a column definition has a path with a wildcard, create
1092 // columns for all non-virtual fields at the specified
1093 // position in the path.
1094 cols.expandPath = function(colSpec) {
1096 var ignoreList = [];
1098 ignoreList = colSpec.ignore.split(' ');
1100 var dotpath = colSpec.path.replace(/\.?\*$/,'');
1104 if (colSpec.parentIdlClass) {
1105 class_obj = egCore.idl.classes[colSpec.parentIdlClass];
1107 class_obj = egCore.idl.classes[cols.idlClass];
1110 if (!class_obj) return;
1112 console.debug('egGrid: auto dotpath is: ' + dotpath);
1113 var path_parts = dotpath.split(/\./);
1115 // find the IDL class definition for the last element in the
1116 // path before the .*
1117 // an empty path_parts means expand the root class
1119 for (var path_idx in path_parts) {
1120 var part = path_parts[path_idx];
1121 idl_field = class_obj.field_map[part];
1123 // unless we're at the end of the list, this field should
1124 // link to another class.
1125 if (idl_field && idl_field['class'] && (
1126 idl_field.datatype == 'link' ||
1127 idl_field.datatype == 'org_unit')) {
1128 class_obj = egCore.idl.classes[idl_field['class']];
1130 if (path_idx < (path_parts.length - 1)) {
1131 // we ran out of classes to hop through before
1132 // we ran out of path components
1133 console.error("egGrid: invalid IDL path: " + dotpath);
1140 angular.forEach(class_obj.fields, function(field) {
1142 // Only show wildcard fields where we have data to show
1143 // Virtual and un-fleshed links will not have any data.
1144 if (field.virtual ||
1145 (field.datatype == 'link' || field.datatype == 'org_unit') ||
1146 ignoreList.indexOf(field.name) > -1
1150 var col = cols.cloneFromScope(colSpec);
1151 col.path = dotpath + '.' + field.name;
1152 console.debug('egGrid: field: ' +field.name + '; parent field: ' + js2JSON(idl_field));
1153 cols.add(col, false, true,
1154 {idl_parent : idl_field, idl_field : field, idl_class : class_obj});
1157 cols.columns = cols.columns.sort(
1159 if (a.explicit) return -1;
1160 if (b.explicit) return 1;
1161 if (a.idlclass && b.idlclass) {
1162 return a.idlclass < b.idlclass ? -1 : 1;
1163 return a.idlclass > b.idlclass ? 1 : -1;
1165 if (a.path && b.path) {
1166 return a.path < b.path ? -1 : 1;
1167 return a.path > b.path ? 1 : -1;
1170 return a.label < b.label ? -1 : 1;
1177 "egGrid: wildcard path does not resolve to an object: "
1182 // angular.clone(scopeObject) is not permittable. Manually copy
1183 // the fields over that we need (so the scope object can go away).
1184 cols.cloneFromScope = function(colSpec) {
1186 name : colSpec.name,
1187 label : colSpec.label,
1188 path : colSpec.path,
1189 flex : Number(colSpec.flex) || 2,
1190 sort : Number(colSpec.sort) || 0,
1191 required : colSpec.required,
1192 linkpath : colSpec.linkpath,
1193 template : colSpec.template,
1194 visible : colSpec.visible,
1195 hidden : colSpec.hidden,
1196 datatype : colSpec.datatype,
1197 sortable : colSpec.sortable,
1198 nonsortable : colSpec.nonsortable,
1199 multisortable : colSpec.multisortable,
1200 nonmultisortable : colSpec.nonmultisortable,
1201 dateformat : colSpec.dateformat,
1202 parentIdlClass : colSpec.parentIdlClass
1207 // Add a column to the columns collection.
1208 // Columns may come from a slim eg-columns-field or
1209 // directly from the IDL.
1210 cols.add = function(colSpec, fromIDL, fromExpand, idl_info) {
1212 // First added column with the specified path takes precedence.
1213 // This allows for specific definitions followed by wildcard
1214 // definitions. If a match is found, back out.
1215 if (cols.columns.filter(function(c) {
1216 return (c.path == colSpec.path) })[0]) {
1217 console.debug('skipping pre-existing column ' + colSpec.path);
1221 var column = fromExpand ? colSpec : cols.cloneFromScope(colSpec);
1223 if (column.path && column.path.match(/\*$/))
1224 return cols.expandPath(colSpec);
1226 if (!fromExpand) column.explicit = true;
1228 if (!column.name) column.name = column.path;
1229 if (!column.path) column.path = column.name;
1231 if (column.visible || (!cols.defaultToHidden && !column.hidden))
1232 column.visible = true;
1234 if (column.sortable || (!cols.defaultToNoSort && !column.nonsortable))
1235 column.sortable = true;
1237 if (column.multisortable ||
1238 (!cols.defaultToNoMultiSort && !column.nonmultisortable))
1239 column.multisortable = true;
1241 cols.columns.push(column);
1243 // Track which columns are visible by default in case we
1244 // need to reset column visibility
1246 cols.stockVisible.push(column.name);
1248 if (fromIDL) return; // directly from egIDL. nothing left to do.
1250 // lookup the matching IDL field
1251 if (!idl_info && cols.idlClass)
1252 idl_info = cols.idlFieldFromPath(column.path);
1255 // column is not represented within the IDL
1256 column.adhoc = true;
1260 column.datatype = idl_info.idl_field.datatype;
1262 if (!column.label) {
1263 column.label = idl_info.idl_field.label || column.name;
1266 if (fromExpand && idl_info.idl_class) {
1267 column.idlclass = '';
1268 if (idl_info.idl_parent) {
1269 column.idlclass = idl_info.idl_parent.label || idl_info.idl_parent.name;
1271 column.idlclass += idl_info.idl_class.label || idl_info.idl_class.name;
1276 // finds the IDL field from the dotpath, using the columns
1277 // idlClass as the base.
1278 cols.idlFieldFromPath = function(dotpath) {
1279 var class_obj = egCore.idl.classes[cols.idlClass];
1280 var path_parts = dotpath.split(/\./);
1284 for (var path_idx in path_parts) {
1285 var part = path_parts[path_idx];
1286 idl_parent = idl_field;
1287 idl_field = class_obj.field_map[part];
1289 if (idl_field && idl_field['class'] && (
1290 idl_field.datatype == 'link' ||
1291 idl_field.datatype == 'org_unit')) {
1292 class_obj = egCore.idl.classes[idl_field['class']];
1294 // else, path is not in the IDL, which is fine
1297 if (!idl_field) return null;
1300 idl_parent: idl_parent,
1301 idl_field : idl_field,
1302 idl_class : class_obj
1308 instance : function(args) { return new ColumnsProvider(args) }
1314 * Generic data provider template class. This is basically an abstract
1315 * class factory service whose instances can be locally modified to
1316 * meet the needs of each individual grid.
1318 .factory('egGridDataProvider',
1319 ['$q','$timeout','$filter','egCore',
1320 function($q , $timeout , $filter , egCore) {
1322 function GridDataProvider(args) {
1323 var gridData = this;
1324 if (!args) args = {};
1327 gridData.get = args.get;
1328 gridData.query = args.query;
1329 gridData.idlClass = args.idlClass;
1330 gridData.columnsProvider = args.columnsProvider;
1332 // Delivers a stream of array data via promise.notify()
1333 // Useful for passing an array of data to egGrid.get()
1334 // If a count is provided, the array will be trimmed to
1335 // the range defined by count and offset
1336 gridData.arrayNotifier = function(arr, offset, count) {
1337 if (!arr || arr.length == 0) return $q.when();
1338 if (count) arr = arr.slice(offset, offset + count);
1339 var def = $q.defer();
1340 // promise notifications are only witnessed when delivered
1341 // after the caller has his hands on the promise object
1342 $timeout(function() {
1343 angular.forEach(arr, def.notify);
1349 // Calls the grid refresh function. Once instantiated, the
1350 // grid will replace this function with it's own refresh()
1351 gridData.refresh = function(noReset) { }
1353 if (!gridData.get) {
1354 // returns a promise whose notify() delivers items
1355 gridData.get = function(index, count) {
1356 console.error("egGridDataProvider.get() not implemented");
1360 // attempts a flat field lookup first. If the column is not
1361 // found on the top-level object, attempts a nested lookup
1362 // TODO: consider a caching layer to speed up template
1363 // rendering, particularly for nested objects?
1364 gridData.itemFieldValue = function(item, column) {
1365 if (column.name in item) {
1366 if (typeof item[column.name] == 'function') {
1367 return item[column.name]();
1369 return item[column.name];
1372 return gridData.nestedItemFieldValue(item, column);
1376 // TODO: deprecate me
1377 gridData.flatItemFieldValue = function(item, column) {
1378 console.warn('gridData.flatItemFieldValue deprecated; '
1379 + 'leave provider.itemFieldValue unset');
1380 return item[column.name];
1383 // given an object and a dot-separated path to a field,
1384 // extract the value of the field. The path can refer
1385 // to function names or object attributes. If the final
1386 // value is an IDL field, run the value through its
1387 // corresponding output filter.
1388 gridData.nestedItemFieldValue = function(obj, column) {
1389 if (obj === null || obj === undefined || obj === '') return '';
1390 if (!column.path) return obj;
1393 var parts = column.path.split('.');
1395 angular.forEach(parts, function(step, idx) {
1396 // object is not fleshed to the expected extent
1397 if (!obj || typeof obj != 'object') {
1402 var cls = obj.classname;
1403 if (cls && (class_obj = egCore.idl.classes[cls])) {
1404 idl_field = class_obj.field_map[step];
1405 obj = obj[step] ? obj[step]() : '';
1407 if (angular.isFunction(obj[step])) {
1415 // We found a nested IDL object which may or may not have
1416 // been configured as a top-level column. Grab the datatype.
1417 if (idl_field && !column.datatype)
1418 column.datatype = idl_field.datatype;
1420 if (obj === null || obj === undefined || obj === '') return '';
1426 instance : function(args) {
1427 return new GridDataProvider(args);
1434 // Factory service for egGridDataManager instances, which are
1435 // responsible for collecting flattened grid data.
1436 .factory('egGridFlatDataProvider',
1437 ['$q','egCore','egGridDataProvider',
1438 function($q , egCore , egGridDataProvider) {
1441 instance : function(args) {
1442 var provider = egGridDataProvider.instance(args);
1444 provider.get = function(offset, count) {
1446 // no query means no call
1447 if (!provider.query ||
1448 angular.equals(provider.query, {}))
1451 // find all of the currently visible columns
1452 var queryFields = {}
1453 angular.forEach(provider.columnsProvider.columns,
1455 // only query IDL-tracked columns
1456 if (!col.adhoc && (col.required || col.visible))
1457 queryFields[col.name] = col.path;
1461 return egCore.net.request(
1463 'open-ils.fielder.flattened_search',
1464 egCore.auth.token(), provider.idlClass,
1465 queryFields, provider.query,
1466 { sort : provider.sort,
1472 //provider.itemFieldValue = provider.flatItemFieldValue;
1479 .directive('egGridColumnDragSource', function() {
1482 require : '^egGrid',
1483 link : function(scope, element, attrs, egGridCtrl) {
1484 angular.element(element).attr('draggable', 'true');
1486 element.bind('dragstart', function(e) {
1487 egGridCtrl.dragColumn = attrs.column;
1488 egGridCtrl.dragType = attrs.dragType || 'move'; // or resize
1489 egGridCtrl.colResizeDir = 0;
1491 if (egGridCtrl.dragType == 'move') {
1492 // style the column getting moved
1493 angular.element(e.target).addClass(
1494 'eg-grid-column-move-handle-active');
1498 element.bind('dragend', function(e) {
1499 if (egGridCtrl.dragType == 'move') {
1500 angular.element(e.target).removeClass(
1501 'eg-grid-column-move-handle-active');
1508 .directive('egGridColumnDragDest', function() {
1511 require : '^egGrid',
1512 link : function(scope, element, attrs, egGridCtrl) {
1514 element.bind('dragover', function(e) { // required for drop
1515 e.stopPropagation();
1517 e.dataTransfer.dropEffect = 'move';
1519 if (egGridCtrl.colResizeDir == 0) return; // move
1521 var cols = egGridCtrl.columnsProvider;
1522 var srcCol = egGridCtrl.dragColumn;
1523 var srcColIdx = cols.indexOf(srcCol);
1525 if (egGridCtrl.colResizeDir == -1) {
1526 if (cols.indexOf(attrs.column) <= srcColIdx) {
1527 egGridCtrl.modifyColumnFlex(
1528 egGridCtrl.columnsProvider.findColumn(
1529 egGridCtrl.dragColumn), -1);
1530 if (cols.columns[srcColIdx+1]) {
1531 // source column shrinks by one, column to the
1532 // right grows by one.
1533 egGridCtrl.modifyColumnFlex(
1534 cols.columns[srcColIdx+1], 1);
1539 if (cols.indexOf(attrs.column) > srcColIdx) {
1540 egGridCtrl.modifyColumnFlex(
1541 egGridCtrl.columnsProvider.findColumn(
1542 egGridCtrl.dragColumn), 1);
1543 if (cols.columns[srcColIdx+1]) {
1544 // source column grows by one, column to the
1545 // right grows by one.
1546 egGridCtrl.modifyColumnFlex(
1547 cols.columns[srcColIdx+1], -1);
1555 element.bind('dragenter', function(e) {
1556 e.stopPropagation();
1558 if (egGridCtrl.dragType == 'move') {
1559 angular.element(e.target).addClass('eg-grid-col-hover');
1561 // resize grips are on the right side of each column.
1562 // dragenter will either occur on the source column
1563 // (dragging left) or the column to the right.
1564 if (egGridCtrl.colResizeDir == 0) {
1565 if (egGridCtrl.dragColumn == attrs.column) {
1566 egGridCtrl.colResizeDir = -1; // west
1568 egGridCtrl.colResizeDir = 1; // east
1574 element.bind('dragleave', function(e) {
1575 e.stopPropagation();
1577 if (egGridCtrl.dragType == 'move') {
1578 angular.element(e.target).removeClass('eg-grid-col-hover');
1582 element.bind('drop', function(e) {
1583 e.stopPropagation();
1585 egGridCtrl.colResizeDir = 0;
1586 if (egGridCtrl.dragType == 'move') {
1587 angular.element(e.target).removeClass('eg-grid-col-hover');
1588 egGridCtrl.onColumnDrop(attrs.column); // move the column
1595 .directive('egGridMenuItem', function() {
1598 require : '^egGrid',
1602 handler : '=', // onclick handler function
1603 divider : '=', // if true, show a divider only
1604 handlerData : '=', // if set, passed as second argument to handler
1605 disabled : '=', // function
1606 hidden : '=' // function
1608 link : function(scope, element, attrs, egGridCtrl) {
1609 egGridCtrl.addMenuItem({
1610 label : scope.label,
1611 standalone : scope.standalone ? true : false,
1612 handler : scope.handler,
1613 divider : scope.divider,
1614 disabled : scope.disabled,
1615 hidden : scope.hidden,
1616 handlerData : scope.handlerData
1626 * Translates bare IDL object values into display values.
1627 * 1. Passes dates through the angular date filter
1628 * 2. Translates bools to Booleans so the browser can display translated
1629 * value. (Though we could manually translate instead..)
1630 * Others likely to follow...
1632 .filter('egGridValueFilter', ['$filter', function($filter) {
1633 return function(value, column) {
1634 switch(column.datatype) {
1637 // Browser will translate true/false for us
1639 case '1' : // legacy
1643 case '0' : // legacy
1646 // value may be null, '', etc.
1647 default : return '';
1650 // canned angular date filter FTW
1651 if (!column.dateformat)
1652 column.dateformat = 'shortDate';
1653 return $filter('date')(value, column.dateformat);
1655 return $filter('currency')(value);