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 // These functions are defined by the grid and thus
58 // replace any values defined for these attributes from the
61 // activateItem : function(item) {}
62 // allItems : function(allItems) {}
63 // selectedItems : function(selected) {}
64 // selectItems : function(ids) {}
65 // setQuery : function(queryStruct) {} // causes reload
66 // setSort : function(sortSturct) {} // causes reload
70 // TODO: avoid hard-coded url
71 templateUrl : '/eg/staff/share/t_autogrid',
73 link : function(scope, element, attrs) {
74 // link() is called after page compilation, which means our
75 // eg-grid-field's have been parsed and loaded. Now it's
76 // safe to perform our initial page load.
78 // load auto fields after eg-grid-field's so they are not clobbered
79 scope.handleAutoFields();
84 '$scope','$q','egCore','egGridFlatDataProvider','$location',
85 'egGridColumnsProvider','$filter','$window','$sce','$timeout',
86 function($scope, $q , egCore, egGridFlatDataProvider , $location,
87 egGridColumnsProvider , $filter , $window , $sce , $timeout) {
91 grid.init = function() {
93 grid.limit = Number($scope.pageSize) || 25;
95 $scope.showGridConf = false;
98 $scope.actions = []; // actions for selected items
99 $scope.menuItems = []; // global actions
101 // remove some unneeded values from the scope to reduce bloat
103 grid.idlClass = $scope.idlClass;
104 delete $scope.idlClass;
106 grid.persistKey = $scope.persistKey;
107 delete $scope.persistKey;
109 grid.indexField = $scope.idField;
110 delete $scope.idField;
112 grid.dataProvider = $scope.itemsProvider;
114 var features = ($scope.features) ?
115 $scope.features.split(',') : [];
116 delete $scope.features;
118 if (!grid.indexField && grid.idlClass)
119 grid.indexField = egCore.idl.classes[grid.idlClass].pkey;
121 grid.columnsProvider = egGridColumnsProvider.instance({
122 idlClass : grid.idlClass,
123 defaultToHidden : (features.indexOf('-display') > -1),
124 defaultToNoSort : (features.indexOf('-sort') > -1),
125 defaultToNoMultiSort : (features.indexOf('-multisort') > -1)
128 $scope.handleAutoFields = function() {
129 if ($scope.autoFields) {
130 if (grid.autoLabel) {
132 egCore.idl.classes[grid.idlClass].label;
134 grid.columnsProvider.compileAutoColumns();
135 delete $scope.autoFields;
139 if (!grid.dataProvider) {
140 // no provider, um, provided.
141 // Use a flat data provider
143 grid.selfManagedData = true;
144 grid.dataProvider = egGridFlatDataProvider.instance({
145 indexField : grid.indexField,
146 idlClass : grid.idlClass,
147 columnsProvider : grid.columnsProvider,
152 $scope.itemFieldValue = grid.dataProvider.itemFieldValue;
153 $scope.indexValue = function(item) {
154 return grid.indexValue(item)
157 grid.applyControlFunctions();
159 grid.loadConfig().then(function() {
160 // link columns to scope after loadConfig(), since it
161 // replaces the columns array.
162 $scope.columns = grid.columnsProvider.columns;
165 // NOTE: grid.collect() is first called from link(), not here.
168 // link our control functions into the gridControls
169 // scope object so the caller can access them.
170 grid.applyControlFunctions = function() {
172 // we use some of these controls internally, so sett
173 // them up even if the caller doesn't request them.
174 var controls = $scope.gridControls || {};
176 // link in the control functions
177 controls.selectedItems = function() {
178 return grid.getSelectedItems()
181 controls.allItems = function() {
185 controls.selectItems = function(ids) {
187 $scope.selected = {};
188 angular.forEach(ids, function(i) {
189 $scope.selected[''+i] = true;
193 // if the caller provided a functional setQuery,
194 // extract the value before replacing it
195 if (controls.setQuery) {
196 grid.dataProvider.query =
200 controls.setQuery = function(query) {
201 grid.dataProvider.query = query;
205 // if the caller provided a functional setSort
206 // extract the value before replacing it
207 grid.dataProvider.sort =
208 controls.setSort ? controls.setSort() : [];
210 controls.setSort = function(sort) {
214 controls.refresh = function(noReset) {
215 if (!noReset) grid.offset = 0;
219 controls.setLimit = function(limit) {
222 controls.getLimit = function() {
225 controls.setOffset = function(offset) {
226 grid.offset = offset;
228 controls.getOffset = function() {
232 grid.dataProvider.refresh = controls.refresh;
233 grid.controls = controls;
236 // add a new (global) grid menu item
237 grid.addMenuItem = function(item) {
238 $scope.menuItems.push(item);
239 var handler = item.handler;
240 item.handler = function() {
241 $scope.gridMenuIsOpen = false; // close menu
244 item.handlerData, grid.getSelectedItems());
249 // add a selected-items action
250 grid.addAction = function(act) {
251 $scope.actions.push(act);
254 // remove the stored column configuration preferenc, then recover
255 // the column visibility information from the initial page load.
256 $scope.resetColumns = function() {
257 $scope.gridColumnPickerIsOpen = false;
258 egCore.hatch.removeItem('eg.grid.' + grid.persistKey)
260 grid.columnsProvider.reset();
261 if (grid.selfManagedData) grid.collect();
265 $scope.showAllColumns = function() {
266 $scope.gridColumnPickerIsOpen = false;
267 grid.columnsProvider.showAllColumns();
268 if (grid.selfManagedData) grid.collect();
271 $scope.hideAllColumns = function() {
272 $scope.gridColumnPickerIsOpen = false;
273 grid.columnsProvider.hideAllColumns();
274 // note: no need to fetch new data if no columns are visible
277 $scope.toggleColumnVisibility = function(col) {
278 $scope.gridColumnPickerIsOpen = false;
279 col.visible = !col.visible;
281 // egGridFlatDataProvider only retrieves data to be
282 // displayed. When column visibility changes, it's
283 // necessary to fetch the newly visible column data.
284 if (grid.selfManagedData) grid.collect();
287 // save the columns configuration (position, sort, width) to
288 // eg.grid.<persist-key>
289 $scope.saveConfig = function() {
290 $scope.gridColumnPickerIsOpen = false;
292 if (!grid.persistKey) {
294 "Cannot save settings without a grid persist-key");
298 // only store information about visible columns.
299 var conf = grid.columnsProvider.columns.filter(
300 function(col) {return Boolean(col.visible) });
302 // now scrunch the data down to just the needed info
303 conf = conf.map(function(col) {
304 var c = {name : col.name}
305 // Apart from the name, only store non-default values.
306 // No need to store col.visible, since that's implicit
307 if (col.flex != 2) c.flex = col.flex;
308 if (Number(col.sort)) c.sort = Number(c.sort);
312 egCore.hatch.setItem('eg.grid.' + grid.persistKey, conf)
314 // Save operation performed from the grid configuration UI.
315 // Hide the configuration UI and re-draw w/ sort applied
316 if ($scope.showGridConf)
317 $scope.toggleConfDisplay();
321 // load the columns configuration (position, sort, width) from
322 // eg.grid.<persist-key> and apply the loaded settings to the
323 // columns on our columnsProvider
324 grid.loadConfig = function() {
325 if (!grid.persistKey) return $q.when();
327 return egCore.hatch.getItem('eg.grid.' + grid.persistKey)
328 .then(function(conf) {
331 var columns = grid.columnsProvider.columns;
334 angular.forEach(conf, function(col) {
335 var grid_col = columns.filter(
336 function(c) {return c.name == col.name})[0];
339 // saved column does not match a column in the
340 // current grid. skip it.
344 grid_col.flex = col.flex || 2;
345 grid_col.sort = col.sort || 0;
346 // all saved columns are assumed to be true
347 grid_col.visible = true;
348 new_cols.push(grid_col);
351 // columns which are not expressed within the saved
352 // configuration are marked as non-visible and
353 // appended to the end of the new list of columns.
354 angular.forEach(columns, function(col) {
355 var found = conf.filter(
356 function(c) {return (c.name == col.name)})[0];
363 grid.columnsProvider.columns = new_cols;
368 $scope.onContextMenu = function($event) {
369 var col = angular.element($event.target).attr('column');
370 console.log('selected column ' + col);
373 $scope.page = function() {
374 return (grid.offset / grid.limit) + 1;
377 $scope.goToPage = function(page) {
379 if (angular.isNumber(page) && page > 0) {
380 grid.offset = (page - 1) * grid.limit;
385 $scope.offset = function(o) {
386 if (angular.isNumber(o))
391 $scope.limit = function(l) {
392 if (angular.isNumber(l))
397 $scope.onFirstPage = function() {
398 return grid.offset == 0;
401 $scope.hasNextPage = function() {
402 // we have less data than requested, there must
403 // not be any more pages
404 if (grid.count() < grid.limit) return false;
406 // if the total count is not known, assume that a full
407 // page of data implies more pages are available.
408 if (grid.totalCount == -1) return true;
410 // we have a full page of data, but is there more?
411 return grid.totalCount > (grid.offset + grid.count());
414 $scope.incrementPage = function() {
415 grid.offset += grid.limit;
419 $scope.decrementPage = function() {
420 if (grid.offset < grid.limit) {
423 grid.offset -= grid.limit;
428 // number of items loaded for the current page of results
429 grid.count = function() {
430 return $scope.items.length;
433 // returns the unique identifier value for the provided item
434 // for internal consistency, indexValue is always coerced
436 grid.indexValue = function(item) {
437 if (angular.isObject(item)) {
439 if (angular.isFunction(item[grid.indexField]))
440 return ''+item[grid.indexField]();
441 return ''+item[grid.indexField]; // flat data
444 // passed a non-object; assume it's an index
448 // fires the action handler function for a context action
449 $scope.actionLauncher = function(action) {
450 if (!action.handler) {
452 'No handler specified for "' + action.label + '"');
457 action.handler(grid.getSelectedItems());
459 console.error('Error executing handler for "'
460 + action.label + '" => ' + E + "\n" + E.stack);
464 // returns the list of selected item objects
465 grid.getSelectedItems = function() {
466 return $scope.items.filter(
468 return Boolean($scope.selected[grid.indexValue(item)]);
473 grid.getItemByIndex = function(index) {
474 for (var i = 0; i < $scope.items.length; i++) {
475 var item = $scope.items[i];
476 if (grid.indexValue(item) == index)
481 // selects one row after deselecting all of the others
482 grid.selectOneItem = function(index) {
483 $scope.selected = {};
484 $scope.selected[index] = true;
487 // selects or deselects an item, without affecting the others.
488 // returns true if the item is selected; false if de-selected.
489 grid.toggleSelectOneItem = function(index) {
490 if ($scope.selected[index]) {
491 delete $scope.selected[index];
494 return $scope.selected[index] = true;
498 grid.selectAllItems = function() {
499 angular.forEach($scope.items, function(item) {
500 $scope.selected[grid.indexValue(item)] = true
504 $scope.$watch('selectAll', function(newVal) {
506 grid.selectAllItems();
508 $scope.selected = {};
512 // returns true if item1 appears in the list before item2;
513 // false otherwise. this is slightly more efficient that
514 // finding the position of each then comparing them.
515 // item1 / item2 may be an item or an item index
516 grid.itemComesBefore = function(itemOrIndex1, itemOrIndex2) {
517 var idx1 = grid.indexValue(itemOrIndex1);
518 var idx2 = grid.indexValue(itemOrIndex2);
520 // use for() for early exit
521 for (var i = 0; i < $scope.items.length; i++) {
522 var idx = grid.indexValue($scope.items[i]);
523 if (idx == idx1) return true;
524 if (idx == idx2) return false;
529 // 0-based position of item in the current data set
530 grid.indexOf = function(item) {
531 var idx = grid.indexValue(item);
532 for (var i = 0; i < $scope.items.length; i++) {
533 if (grid.indexValue($scope.items[i]) == idx)
539 grid.modifyColumnFlex = function(column, val) {
541 // prevent flex:0; use hiding instead
545 $scope.modifyColumnFlex = function(col, val) {
546 grid.modifyColumnFlex(col, val);
549 // handles click, control-click, and shift-click
550 $scope.handleRowClick = function($event, item) {
551 var index = grid.indexValue(item);
553 var origSelected = Object.keys($scope.selected);
555 if ($event.ctrlKey || $event.metaKey /* mac command */) {
557 if (grid.toggleSelectOneItem(index))
558 grid.lastSelectedItemIndex = index;
560 } else if ($event.shiftKey) {
563 if (!grid.lastSelectedItemIndex ||
564 index == grid.lastSelectedItemIndex) {
565 grid.selectOneItem(index);
566 grid.lastSelectedItemIndex = index;
570 var selecting = false;
571 var ascending = grid.itemComesBefore(
572 grid.lastSelectedItemIndex, item);
574 grid.indexOf(grid.lastSelectedItemIndex);
576 // update to new last-selected
577 grid.lastSelectedItemIndex = index;
579 // select each row between the last selected and
580 // currently selected items
582 startPos += ascending ? 1 : -1;
583 var curItem = $scope.items[startPos];
585 var curIdx = grid.indexValue(curItem);
586 $scope.selected[curIdx] = true;
587 if (curIdx == index) break; // all done
592 grid.selectOneItem(index);
593 grid.lastSelectedItemIndex = index;
597 // Builds a sort expression from column sort priorities.
598 // called on page load and any time the priorities are modified.
599 grid.compileSort = function() {
600 var sortList = grid.columnsProvider.columns.filter(
601 function(col) { return Number(col.sort) != 0 }
604 if (Math.abs(a.sort) < Math.abs(b.sort))
610 if (sortList.length) {
611 grid.dataProvider.sort = sortList.map(function(col) {
613 blob[col.name] = col.sort < 0 ? 'desc' : 'asc';
619 // builds a sort expression using a single column,
620 // toggling between ascending and descending sort.
621 $scope.quickSort = function(col_name) {
622 var sort = grid.dataProvider.sort;
623 if (sort && sort.length &&
624 sort[0] == col_name) {
626 blob[col_name] = 'desc';
627 grid.dataProvider.sort = [blob];
629 grid.dataProvider.sort = [col_name];
636 // show / hide the grid configuration row
637 $scope.toggleConfDisplay = function() {
638 if ($scope.showGridConf) {
639 $scope.showGridConf = false;
640 if (grid.columnsProvider.hasSortableColumn()) {
641 // only refresh the grid if the user has the
642 // ability to modify the sort priorities.
648 $scope.showGridConf = true;
651 $scope.gridColumnPickerIsOpen = false;
654 // called when a dragged column is dropped onto itself
655 // or any other column
656 grid.onColumnDrop = function(target) {
657 if (angular.isUndefined(target)) return;
658 if (target == grid.dragColumn) return;
659 var srcIdx, targetIdx, srcCol;
660 angular.forEach(grid.columnsProvider.columns,
662 if (col.name == grid.dragColumn) {
665 } else if (col.name == target) {
671 if (srcIdx < targetIdx) targetIdx--;
673 // move src column from old location to new location in
674 // the columns array, then force a page refresh
675 grid.columnsProvider.columns.splice(srcIdx, 1);
676 grid.columnsProvider.columns.splice(targetIdx, 0, srcCol);
680 // prepares a string for inclusion within a CSV document
681 // by escaping commas and quotes and removing newlines.
682 grid.csvDatum = function(str) {
685 str = str.replace(/\n/g, '');
686 if (str.match(/\,/) || str.match(/"/)) {
687 str = str.replace(/"/g, '""');
688 str = '"' + str + '"';
693 // sets the download file name and inserts the current CSV
694 // into a Blob URL for browser download.
695 $scope.generateCSVExportURL = function() {
696 $scope.gridColumnPickerIsOpen = false;
698 // let the file name describe the grid
699 $scope.csvExportFileName =
700 ($scope.mainLabel || grid.persistKey || 'eg_grid_data')
701 .replace(/\s+/g, '_') + '_' + $scope.page();
703 // toss the CSV into a Blob and update the export URL
704 var csv = grid.generateCSV();
705 var blob = new Blob([csv], {type : 'text/plain'});
706 $scope.csvExportURL =
707 ($window.URL || $window.webkitURL).createObjectURL(blob);
710 $scope.printCSV = function() {
711 $scope.gridColumnPickerIsOpen = false;
714 content : grid.generateCSV(),
715 content_type : 'text/plain'
719 // generates CSV for the currently visible grid contents
720 grid.generateCSV = function() {
722 var colCount = grid.columnsProvider.columns.length;
725 angular.forEach(grid.columnsProvider.columns,
727 if (!col.visible) return;
728 csvStr += grid.csvDatum(col.label);
733 csvStr = csvStr.replace(/,$/,'\n');
736 angular.forEach($scope.items, function(item) {
737 angular.forEach(grid.columnsProvider.columns,
739 if (!col.visible) return;
741 var val = grid.dataProvider.itemFieldValue(item, col);
742 // filtered value (dates, etc.)
743 val = $filter('egGridValueFilter')(val, col);
744 csvStr += grid.csvDatum(val);
748 csvStr = csvStr.replace(/,$/,'\n');
754 // Interpolate the value for column.linkpath within the context
755 // of the row item to generate the final link URL.
756 $scope.generateLinkPath = function(col, item) {
757 return egCore.strings.$replace(col.linkpath, {item : item});
760 // If a column provides its own HTML template, translate it,
761 // using the current item for the template scope.
762 // note: $sce is required to avoid security restrictions and
763 // is OK here, since the template comes directly from a
764 // local HTML template (not user input).
765 $scope.translateCellTemplate = function(col, item) {
766 var html = egCore.strings.$replace(col.template, {item : item});
767 return $sce.trustAsHtml(html);
770 $scope.collect = function() { grid.collect() }
772 // asks the dataProvider for a page of data
773 grid.collect = function() {
775 // avoid firing the collect if there is nothing to collect.
776 if (grid.selfManagedData && !grid.dataProvider.query) return;
778 if (grid.collecting) return; // avoid parallel collect()
779 grid.collecting = true;
781 console.debug('egGrid.collect() offset='
782 + grid.offset + '; limit=' + grid.limit);
784 // ensure all of our dropdowns are closed
785 // TODO: git rid of these and just use dropdown-toggle,
786 // which is more reliable.
787 $scope.gridColumnPickerIsOpen = false;
788 $scope.gridRowCountIsOpen = false;
789 $scope.gridPageSelectIsOpen = false;
792 $scope.selected = {};
793 grid.dataProvider.get(grid.offset, grid.limit).then(
795 if (grid.controls.allItemsRetrieved)
796 grid.controls.allItemsRetrieved();
801 $scope.items.push(item)
802 if (grid.controls.itemRetrieved)
803 grid.controls.itemRetrieved(item);
805 }).finally(function() {
806 console.debug('egGrid.collect() complete');
807 grid.collecting = false
817 * eg-grid-field : used for collecting custom field data from the templates.
818 * This directive does not direct display, it just passes data up to the
821 .directive('egGridField', function() {
826 name : '@', // required; unique name
827 path : '@', // optional; flesh path
828 ignore: '@', // optional; fields to ignore when path is a wildcard
829 label : '@', // optional; display label
830 flex : '@', // optional; default flex width
831 dateformat : '@', // optional: passed down to egGridValueFilter
833 // if a field is part of an IDL object, but we are unable to
834 // determine the class, because it's nested within a hash
835 // (i.e. we can't navigate directly to the object via the IDL),
836 // idlClass lets us specify the class. This is particularly
837 // useful for nested wildcard fields.
838 parentIdlClass : '@',
840 // optional: for non-IDL columns, specifying a datatype
841 // lets the caller control which display filter is used.
842 // datatype should match the standard IDL datatypes.
845 link : function(scope, element, attrs, egGridCtrl) {
847 // boolean fields are presented as value-less attributes
856 'required' // if set, always fetch data for this column
859 if (angular.isDefined(attrs[field]))
864 // any HTML content within the field is its custom template
865 var tmpl = element.html();
866 if (tmpl && !tmpl.match(/^\s*$/))
867 scope.template = tmpl
869 egGridCtrl.columnsProvider.add(scope);
876 * eg-grid-action : used for specifying actions which may be applied
877 * to items within the grid.
879 .directive('egGridAction', function() {
885 label : '@', // Action label
886 handler : '=', // Action function handler
889 link : function(scope, element, attrs, egGridCtrl) {
890 egGridCtrl.addAction({
892 divider : scope.divider,
893 handler : scope.handler
900 .factory('egGridColumnsProvider', ['egCore', function(egCore) {
902 function ColumnsProvider(args) {
905 cols.stockVisible = [];
906 cols.idlClass = args.idlClass;
907 cols.defaultToHidden = args.defaultToHidden;
908 cols.defaultToNoSort = args.defaultToNoSort;
909 cols.defaultToNoMultiSort = args.defaultToNoMultiSort;
911 // resets column width, visibility, and sort behavior
912 // Visibility resets to the visibility settings defined in the
913 // template (i.e. the original egGridField values).
914 cols.reset = function() {
915 angular.forEach(cols.columns, function(col) {
918 if (cols.stockVisible.indexOf(col.name) > -1) {
926 // returns true if any columns are sortable
927 cols.hasSortableColumn = function() {
928 return cols.columns.filter(
930 return col.sortable || col.multisortable;
935 cols.showAllColumns = function() {
936 angular.forEach(cols.columns, function(column) {
937 column.visible = true;
941 cols.hideAllColumns = function() {
942 angular.forEach(cols.columns, function(col) {
947 cols.indexOf = function(name) {
948 for (var i = 0; i < cols.columns.length; i++) {
949 if (cols.columns[i].name == name)
955 cols.findColumn = function(name) {
956 return cols.columns[cols.indexOf(name)];
959 cols.compileAutoColumns = function() {
960 var idl_class = egCore.idl.classes[cols.idlClass];
963 idl_class.fields.sort(
964 function(a, b) { return a.name < b.name ? -1 : 1 }),
966 if (field.virtual) return;
967 if (field.datatype == 'link' || field.datatype == 'org_unit') {
968 // if the field is a link and the linked class has a
969 // "selector" field specified, use the selector field
970 // as the display field for the columns.
971 // flattener will take care of the fleshing.
972 if (field['class']) {
973 var selector_field = egCore.idl.classes[field['class']].fields
974 .filter(function(f) { return Boolean(f.selector) })[0];
975 if (selector_field) {
976 field.path = field.name + '.' + selector_field.selector;
980 cols.add(field, true);
985 // if a column definition has a path with a wildcard, create
986 // columns for all non-virtual fields at the specified
987 // position in the path.
988 cols.expandPath = function(colSpec) {
992 ignoreList = colSpec.ignore.split(' ');
994 var dotpath = colSpec.path.replace(/\.?\*$/,'');
998 if (colSpec.parentIdlClass) {
999 class_obj = egCore.idl.classes[colSpec.parentIdlClass];
1001 class_obj = egCore.idl.classes[cols.idlClass];
1004 if (!class_obj) return;
1006 console.debug('egGrid: auto dotpath is: ' + dotpath);
1007 var path_parts = dotpath.split(/\./);
1009 // find the IDL class definition for the last element in the
1010 // path before the .*
1011 // an empty path_parts means expand the root class
1013 for (var path_idx in path_parts) {
1014 var part = path_parts[path_idx];
1015 idl_field = class_obj.field_map[part];
1017 // unless we're at the end of the list, this field should
1018 // link to another class.
1019 if (idl_field && idl_field['class'] && (
1020 idl_field.datatype == 'link' ||
1021 idl_field.datatype == 'org_unit')) {
1022 class_obj = egCore.idl.classes[idl_field['class']];
1024 if (path_idx < (path_parts.length - 1)) {
1025 // we ran out of classes to hop through before
1026 // we ran out of path components
1027 console.error("egGrid: invalid IDL path: " + dotpath);
1034 angular.forEach(class_obj.fields, function(field) {
1036 // Only show wildcard fields where we have data to show
1037 // Virtual and un-fleshed links will not have any data.
1038 if (field.virtual ||
1039 (field.datatype == 'link' || field.datatype == 'org_unit') ||
1040 ignoreList.indexOf(field.name) > -1
1044 var col = cols.cloneFromScope(colSpec);
1045 col.path = dotpath + '.' + field.name;
1046 console.debug('egGrid: field: ' +field.name + '; parent field: ' + js2JSON(idl_field));
1047 cols.add(col, false, true,
1048 {idl_parent : idl_field, idl_field : field, idl_class : class_obj});
1051 cols.columns = cols.columns.sort(
1053 if (a.explicit) return -1;
1054 if (b.explicit) return 1;
1055 if (a.idlclass && b.idlclass) {
1056 return a.idlclass < b.idlclass ? -1 : 1;
1057 return a.idlclass > b.idlclass ? 1 : -1;
1059 if (a.path && b.path) {
1060 return a.path < b.path ? -1 : 1;
1061 return a.path > b.path ? 1 : -1;
1064 return a.label < b.label ? -1 : 1;
1071 "egGrid: wildcard path does not resolve to an object: "
1076 // angular.clone(scopeObject) is not permittable. Manually copy
1077 // the fields over that we need (so the scope object can go away).
1078 cols.cloneFromScope = function(colSpec) {
1080 name : colSpec.name,
1081 label : colSpec.label,
1082 path : colSpec.path,
1083 flex : Number(colSpec.flex) || 2,
1084 sort : Number(colSpec.sort) || 0,
1085 required : colSpec.required,
1086 linkpath : colSpec.linkpath,
1087 template : colSpec.template,
1088 visible : colSpec.visible,
1089 hidden : colSpec.hidden,
1090 datatype : colSpec.datatype,
1091 sortable : colSpec.sortable,
1092 nonsortable : colSpec.nonsortable,
1093 multisortable : colSpec.multisortable,
1094 nonmultisortable : colSpec.nonmultisortable,
1095 dateformat : colSpec.dateformat,
1096 parentIdlClass : colSpec.parentIdlClass
1101 // Add a column to the columns collection.
1102 // Columns may come from a slim eg-columns-field or
1103 // directly from the IDL.
1104 cols.add = function(colSpec, fromIDL, fromExpand, idl_info) {
1106 // First added column with the specified path takes precedence.
1107 // This allows for specific definitions followed by wildcard
1108 // definitions. If a match is found, back out.
1109 if (cols.columns.filter(function(c) {
1110 return (c.path == colSpec.path) })[0]) {
1111 console.debug('skipping pre-existing column ' + colSpec.path);
1115 var column = fromExpand ? colSpec : cols.cloneFromScope(colSpec);
1117 if (column.path && column.path.match(/\*$/))
1118 return cols.expandPath(colSpec);
1120 if (!fromExpand) column.explicit = true;
1122 if (!column.name) column.name = column.path;
1123 if (!column.path) column.path = column.name;
1125 if (column.visible || (!cols.defaultToHidden && !column.hidden))
1126 column.visible = true;
1128 if (column.sortable || (!cols.defaultToNoSort && !column.nonsortable))
1129 column.sortable = true;
1131 if (column.multisortable ||
1132 (!cols.defaultToNoMultiSort && !column.nonmultisortable))
1133 column.multisortable = true;
1135 cols.columns.push(column);
1137 // Track which columns are visible by default in case we
1138 // need to reset column visibility
1140 cols.stockVisible.push(column.name);
1142 if (fromIDL) return; // directly from egIDL. nothing left to do.
1144 // lookup the matching IDL field
1145 if (!idl_info && cols.idlClass)
1146 idl_info = cols.idlFieldFromPath(column.path);
1149 // column is not represented within the IDL
1150 column.adhoc = true;
1154 column.datatype = idl_info.idl_field.datatype;
1156 if (!column.label) {
1157 column.label = idl_info.idl_field.label || column.name;
1160 if (fromExpand && idl_info.idl_class) {
1161 column.idlclass = '';
1162 if (idl_info.idl_parent) {
1163 column.idlclass = idl_info.idl_parent.label || idl_info.idl_parent.name;
1165 column.idlclass += idl_info.idl_class.label || idl_info.idl_class.name;
1170 // finds the IDL field from the dotpath, using the columns
1171 // idlClass as the base.
1172 cols.idlFieldFromPath = function(dotpath) {
1173 var class_obj = egCore.idl.classes[cols.idlClass];
1174 var path_parts = dotpath.split(/\./);
1178 for (var path_idx in path_parts) {
1179 var part = path_parts[path_idx];
1180 idl_parent = idl_field;
1181 idl_field = class_obj.field_map[part];
1183 if (idl_field && idl_field['class'] && (
1184 idl_field.datatype == 'link' ||
1185 idl_field.datatype == 'org_unit')) {
1186 class_obj = egCore.idl.classes[idl_field['class']];
1188 // else, path is not in the IDL, which is fine
1191 if (!idl_field) return null;
1194 idl_parent: idl_parent,
1195 idl_field : idl_field,
1196 idl_class : class_obj
1202 instance : function(args) { return new ColumnsProvider(args) }
1208 * Generic data provider template class. This is basically an abstract
1209 * class factory service whose instances can be locally modified to
1210 * meet the needs of each individual grid.
1212 .factory('egGridDataProvider',
1213 ['$q','$timeout','$filter','egCore',
1214 function($q , $timeout , $filter , egCore) {
1216 function GridDataProvider(args) {
1217 var gridData = this;
1218 if (!args) args = {};
1221 gridData.get = args.get;
1222 gridData.query = args.query;
1223 gridData.idlClass = args.idlClass;
1224 gridData.columnsProvider = args.columnsProvider;
1226 // Delivers a stream of array data via promise.notify()
1227 // Useful for passing an array of data to egGrid.get()
1228 // If a count is provided, the array will be trimmed to
1229 // the range defined by count and offset
1230 gridData.arrayNotifier = function(arr, offset, count) {
1231 if (!arr || arr.length == 0) return $q.when();
1232 if (count) arr = arr.slice(offset, offset + count);
1233 var def = $q.defer();
1234 // promise notifications are only witnessed when delivered
1235 // after the caller has his hands on the promise object
1236 $timeout(function() {
1237 angular.forEach(arr, def.notify);
1243 // Calls the grid refresh function. Once instantiated, the
1244 // grid will replace this function with it's own refresh()
1245 gridData.refresh = function(noReset) { }
1247 if (!gridData.get) {
1248 // returns a promise whose notify() delivers items
1249 gridData.get = function(index, count) {
1250 console.error("egGridDataProvider.get() not implemented");
1254 // attempts a flat field lookup first. If the column is not
1255 // found on the top-level object, attempts a nested lookup
1256 // TODO: consider a caching layer to speed up template
1257 // rendering, particularly for nested objects?
1258 gridData.itemFieldValue = function(item, column) {
1259 if (column.name in item) {
1260 if (typeof item[column.name] == 'function') {
1261 return item[column.name]();
1263 return item[column.name];
1266 return gridData.nestedItemFieldValue(item, column);
1270 // TODO: deprecate me
1271 gridData.flatItemFieldValue = function(item, column) {
1272 console.warn('gridData.flatItemFieldValue deprecated; '
1273 + 'leave provider.itemFieldValue unset');
1274 return item[column.name];
1277 // given an object and a dot-separated path to a field,
1278 // extract the value of the field. The path can refer
1279 // to function names or object attributes. If the final
1280 // value is an IDL field, run the value through its
1281 // corresponding output filter.
1282 gridData.nestedItemFieldValue = function(obj, column) {
1283 if (obj === null || obj === undefined || obj === '') return '';
1284 if (!column.path) return obj;
1287 var parts = column.path.split('.');
1289 angular.forEach(parts, function(step, idx) {
1290 // object is not fleshed to the expected extent
1291 if (!obj || typeof obj != 'object') {
1296 var cls = obj.classname;
1297 if (cls && (class_obj = egCore.idl.classes[cls])) {
1298 idl_field = class_obj.field_map[step];
1299 obj = obj[step] ? obj[step]() : '';
1301 if (angular.isFunction(obj[step])) {
1309 // We found a nested IDL object which may or may not have
1310 // been configured as a top-level column. Grab the datatype.
1311 if (idl_field && !column.datatype)
1312 column.datatype = idl_field.datatype;
1314 if (obj === null || obj === undefined || obj === '') return '';
1320 instance : function(args) {
1321 return new GridDataProvider(args);
1328 // Factory service for egGridDataManager instances, which are
1329 // responsible for collecting flattened grid data.
1330 .factory('egGridFlatDataProvider',
1331 ['$q','egCore','egGridDataProvider',
1332 function($q , egCore , egGridDataProvider) {
1335 instance : function(args) {
1336 var provider = egGridDataProvider.instance(args);
1338 provider.get = function(offset, count) {
1340 // no query means no call
1341 if (!provider.query ||
1342 angular.equals(provider.query, {}))
1345 // find all of the currently visible columns
1346 var queryFields = {}
1347 angular.forEach(provider.columnsProvider.columns,
1349 // only query IDL-tracked columns
1350 if (!col.adhoc && (col.required || col.visible))
1351 queryFields[col.name] = col.path;
1355 return egCore.net.request(
1357 'open-ils.fielder.flattened_search',
1358 egCore.auth.token(), provider.idlClass,
1359 queryFields, provider.query,
1360 { sort : provider.sort,
1366 //provider.itemFieldValue = provider.flatItemFieldValue;
1373 .directive('egGridColumnDragSource', function() {
1376 require : '^egGrid',
1377 link : function(scope, element, attrs, egGridCtrl) {
1378 angular.element(element).attr('draggable', 'true');
1380 element.bind('dragstart', function(e) {
1381 egGridCtrl.dragColumn = attrs.column;
1382 egGridCtrl.dragType = attrs.dragType || 'move'; // or resize
1383 egGridCtrl.colResizeDir = 0;
1385 if (egGridCtrl.dragType == 'move') {
1386 // style the column getting moved
1387 angular.element(e.target).addClass(
1388 'eg-grid-column-move-handle-active');
1392 element.bind('dragend', function(e) {
1393 if (egGridCtrl.dragType == 'move') {
1394 angular.element(e.target).removeClass(
1395 'eg-grid-column-move-handle-active');
1402 .directive('egGridColumnDragDest', function() {
1405 require : '^egGrid',
1406 link : function(scope, element, attrs, egGridCtrl) {
1408 element.bind('dragover', function(e) { // required for drop
1409 e.stopPropagation();
1411 e.dataTransfer.dropEffect = 'move';
1413 if (egGridCtrl.colResizeDir == 0) return; // move
1415 var cols = egGridCtrl.columnsProvider;
1416 var srcCol = egGridCtrl.dragColumn;
1417 var srcColIdx = cols.indexOf(srcCol);
1419 if (egGridCtrl.colResizeDir == -1) {
1420 if (cols.indexOf(attrs.column) <= srcColIdx) {
1421 egGridCtrl.modifyColumnFlex(
1422 egGridCtrl.columnsProvider.findColumn(
1423 egGridCtrl.dragColumn), -1);
1424 if (cols.columns[srcColIdx+1]) {
1425 // source column shrinks by one, column to the
1426 // right grows by one.
1427 egGridCtrl.modifyColumnFlex(
1428 cols.columns[srcColIdx+1], 1);
1433 if (cols.indexOf(attrs.column) > srcColIdx) {
1434 egGridCtrl.modifyColumnFlex(
1435 egGridCtrl.columnsProvider.findColumn(
1436 egGridCtrl.dragColumn), 1);
1437 if (cols.columns[srcColIdx+1]) {
1438 // source column grows by one, column to the
1439 // right grows by one.
1440 egGridCtrl.modifyColumnFlex(
1441 cols.columns[srcColIdx+1], -1);
1449 element.bind('dragenter', function(e) {
1450 e.stopPropagation();
1452 if (egGridCtrl.dragType == 'move') {
1453 angular.element(e.target).addClass('eg-grid-col-hover');
1455 // resize grips are on the right side of each column.
1456 // dragenter will either occur on the source column
1457 // (dragging left) or the column to the right.
1458 if (egGridCtrl.colResizeDir == 0) {
1459 if (egGridCtrl.dragColumn == attrs.column) {
1460 egGridCtrl.colResizeDir = -1; // west
1462 egGridCtrl.colResizeDir = 1; // east
1468 element.bind('dragleave', function(e) {
1469 e.stopPropagation();
1471 if (egGridCtrl.dragType == 'move') {
1472 angular.element(e.target).removeClass('eg-grid-col-hover');
1476 element.bind('drop', function(e) {
1477 e.stopPropagation();
1479 egGridCtrl.colResizeDir = 0;
1480 if (egGridCtrl.dragType == 'move') {
1481 angular.element(e.target).removeClass('eg-grid-col-hover');
1482 egGridCtrl.onColumnDrop(attrs.column); // move the column
1489 .directive('egGridMenuItem', function() {
1492 require : '^egGrid',
1495 handler : '=', // onclick handler function
1496 divider : '=', // if true, show a divider only
1497 handlerData : '=', // if set, passed as second argument to handler
1498 disabled : '=', // function
1499 hidden : '=' // function
1501 link : function(scope, element, attrs, egGridCtrl) {
1502 egGridCtrl.addMenuItem({
1503 label : scope.label,
1504 handler : scope.handler,
1505 divider : scope.divider,
1506 disabled : scope.disabled,
1507 hidden : scope.hidden,
1508 handlerData : scope.handlerData
1518 * Translates bare IDL object values into display values.
1519 * 1. Passes dates through the angular date filter
1520 * 2. Translates bools to Booleans so the browser can display translated
1521 * value. (Though we could manually translate instead..)
1522 * Others likely to follow...
1524 .filter('egGridValueFilter', ['$filter', function($filter) {
1525 return function(value, column) {
1526 switch(column.datatype) {
1529 // Browser will translate true/false for us
1531 case '1' : // legacy
1535 case '0' : // legacy
1538 // value may be null, '', etc.
1539 default : return '';
1542 // canned angular date filter FTW
1543 if (!column.dateformat)
1544 column.dateformat = 'shortDate';
1545 return $filter('date')(value, column.dateformat);
1547 return $filter('currency')(value);