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 label : '@', // optional; display label
829 flex : '@', // optional; default flex width
830 dateformat : '@', // optional: passed down to egGridValueFilter
832 // if a field is part of an IDL object, but we are unable to
833 // determine the class, because it's nested within a hash
834 // (i.e. we can't navigate directly to the object via the IDL),
835 // idlClass lets us specify the class. This is particularly
836 // useful for nested wildcard fields.
837 parentIdlClass : '@',
839 // optional: for non-IDL columns, specifying a datatype
840 // lets the caller control which display filter is used.
841 // datatype should match the standard IDL datatypes.
844 link : function(scope, element, attrs, egGridCtrl) {
846 // boolean fields are presented as value-less attributes
855 'required' // if set, always fetch data for this column
858 if (angular.isDefined(attrs[field]))
863 // any HTML content within the field is its custom template
864 var tmpl = element.html();
865 if (tmpl && !tmpl.match(/^\s*$/))
866 scope.template = tmpl
868 egGridCtrl.columnsProvider.add(scope);
875 * eg-grid-action : used for specifying actions which may be applied
876 * to items within the grid.
878 .directive('egGridAction', function() {
884 label : '@', // Action label
885 handler : '=', // Action function handler
888 link : function(scope, element, attrs, egGridCtrl) {
889 egGridCtrl.addAction({
891 divider : scope.divider,
892 handler : scope.handler
899 .factory('egGridColumnsProvider', ['egCore', function(egCore) {
901 function ColumnsProvider(args) {
904 cols.stockVisible = [];
905 cols.idlClass = args.idlClass;
906 cols.defaultToHidden = args.defaultToHidden;
907 cols.defaultToNoSort = args.defaultToNoSort;
908 cols.defaultToNoMultiSort = args.defaultToNoMultiSort;
910 // resets column width, visibility, and sort behavior
911 // Visibility resets to the visibility settings defined in the
912 // template (i.e. the original egGridField values).
913 cols.reset = function() {
914 angular.forEach(cols.columns, function(col) {
917 if (cols.stockVisible.indexOf(col.name) > -1) {
925 // returns true if any columns are sortable
926 cols.hasSortableColumn = function() {
927 return cols.columns.filter(
929 return col.sortable || col.multisortable;
934 cols.showAllColumns = function() {
935 angular.forEach(cols.columns, function(column) {
936 column.visible = true;
940 cols.hideAllColumns = function() {
941 angular.forEach(cols.columns, function(col) {
946 cols.indexOf = function(name) {
947 for (var i = 0; i < cols.columns.length; i++) {
948 if (cols.columns[i].name == name)
954 cols.findColumn = function(name) {
955 return cols.columns[cols.indexOf(name)];
958 cols.compileAutoColumns = function() {
959 var idl_class = egCore.idl.classes[cols.idlClass];
962 idl_class.fields.sort(
963 function(a, b) { return a.name < b.name ? -1 : 1 }),
965 if (field.virtual) return;
966 if (field.datatype == 'link' || field.datatype == 'org_unit') {
967 // if the field is a link and the linked class has a
968 // "selector" field specified, use the selector field
969 // as the display field for the columns.
970 // flattener will take care of the fleshing.
971 if (field['class']) {
972 var selector_field = egCore.idl.classes[field['class']].fields
973 .filter(function(f) { return Boolean(f.selector) })[0];
974 if (selector_field) {
975 field.path = field.name + '.' + selector_field.selector;
979 cols.add(field, true);
984 // if a column definition has a path with a wildcard, create
985 // columns for all non-virtual fields at the specified
986 // position in the path.
987 cols.expandPath = function(colSpec) {
989 var dotpath = colSpec.path.replace(/\.?\*$/,'');
992 if (colSpec.parentIdlClass) {
993 class_obj = egCore.idl.classes[colSpec.parentIdlClass];
997 class_obj = egCore.idl.classes[cols.idlClass];
998 if (!class_obj) return;
1000 var path_parts = dotpath.split(/\./);
1002 // find the IDL class definition for the last element in the
1003 // path before the .*
1004 // an empty path_parts means expand the root class
1006 for (var path_idx in path_parts) {
1007 var part = path_parts[path_idx];
1008 var idl_field = class_obj.field_map[part];
1010 // unless we're at the end of the list, this field should
1011 // link to another class.
1012 if (idl_field && idl_field['class'] && (
1013 idl_field.datatype == 'link' ||
1014 idl_field.datatype == 'org_unit')) {
1015 class_obj = egCore.idl.classes[idl_field['class']];
1017 if (path_idx < (path_parts.length - 1)) {
1018 // we ran out of classes to hop through before
1019 // we ran out of path components
1020 console.error("egGrid: invalid IDL path: " + dotpath);
1028 angular.forEach(class_obj.fields, function(field) {
1030 // Only show wildcard fields where we have data to show
1031 // Virtual and un-fleshed links will not have any data.
1032 if (field.virtual || (
1033 field.datatype == 'link' || field.datatype == 'org_unit'))
1036 var col = cols.cloneFromScope(colSpec);
1037 col.path = dotpath + '.' + field.name;
1038 cols.add(col, false, true,
1039 {idl_field : field, idl_class : class_obj});
1042 cols.columns = cols.columns.sort(
1044 if (a.explicit) return -1;
1045 if (b.explicit) return 1;
1046 return a.label < b.label ? -1 : 1;
1053 "egGrid: wildcard path does not resolve to an object: "
1058 // angular.clone(scopeObject) is not permittable. Manually copy
1059 // the fields over that we need (so the scope object can go away).
1060 cols.cloneFromScope = function(colSpec) {
1062 name : colSpec.name,
1063 label : colSpec.label,
1064 path : colSpec.path,
1065 flex : Number(colSpec.flex) || 2,
1066 sort : Number(colSpec.sort) || 0,
1067 required : colSpec.required,
1068 linkpath : colSpec.linkpath,
1069 template : colSpec.template,
1070 visible : colSpec.visible,
1071 hidden : colSpec.hidden,
1072 datatype : colSpec.datatype,
1073 sortable : colSpec.sortable,
1074 nonsortable : colSpec.nonsortable,
1075 multisortable : colSpec.multisortable,
1076 nonmultisortable : colSpec.nonmultisortable,
1077 dateformat : colSpec.dateformat,
1078 parentIdlClass : colSpec.parentIdlClass
1083 // Add a column to the columns collection.
1084 // Columns may come from a slim eg-columns-field or
1085 // directly from the IDL.
1086 cols.add = function(colSpec, fromIDL, fromExpand, idl_info) {
1088 // First added column with the specified path takes precedence.
1089 // This allows for specific definitions followed by wildcard
1090 // definitions. If a match is found, back out.
1091 if (cols.columns.filter(function(c) {
1092 return (c.path == colSpec.path) })[0]) {
1093 //console.debug('skipping column ' + colSpec.path);
1097 var column = fromExpand ? colSpec : cols.cloneFromScope(colSpec);
1099 if (column.path && column.path.match(/\*$/))
1100 return cols.expandPath(colSpec);
1102 if (!fromExpand) column.explicit = true;
1104 if (!column.name) column.name = column.path;
1105 if (!column.path) column.path = column.name;
1107 if (column.visible || (!cols.defaultToHidden && !column.hidden))
1108 column.visible = true;
1110 if (column.sortable || (!cols.defaultToNoSort && !column.nonsortable))
1111 column.sortable = true;
1113 if (column.multisortable ||
1114 (!cols.defaultToNoMultiSort && !column.nonmultisortable))
1115 column.multisortable = true;
1117 cols.columns.push(column);
1119 // Track which columns are visible by default in case we
1120 // need to reset column visibility
1122 cols.stockVisible.push(column.name);
1124 if (fromIDL) return; // directly from egIDL. nothing left to do.
1126 // lookup the matching IDL field
1127 if (!idl_info && cols.idlClass)
1128 idl_info = cols.idlFieldFromPath(column.path);
1131 // column is not represented within the IDL
1132 column.adhoc = true;
1136 column.datatype = idl_info.idl_field.datatype;
1138 if (!column.label) {
1139 column.label = idl_info.idl_field.label || column.name;
1141 // append class label to column label to better differentiate
1142 // columns in the selector.
1143 // Disabled for now, since it results in columns w/ really
1144 // long names, making the grid unappealing when any of
1145 // these colmns are selected.
1146 // TODO: consider nesting the colum picker by class?
1149 idl_info.idl_class.label || idl_info.idl_class.name;
1150 column.label = label + '::' + column.label;
1156 // finds the IDL field from the dotpath, using the columns
1157 // idlClass as the base.
1158 cols.idlFieldFromPath = function(dotpath) {
1159 var class_obj = egCore.idl.classes[cols.idlClass];
1160 var path_parts = dotpath.split(/\./);
1163 for (var path_idx in path_parts) {
1164 var part = path_parts[path_idx];
1165 idl_field = class_obj.field_map[part];
1167 if (idl_field && idl_field['class'] && (
1168 idl_field.datatype == 'link' ||
1169 idl_field.datatype == 'org_unit')) {
1170 class_obj = egCore.idl.classes[idl_field['class']];
1172 // else, path is not in the IDL, which is fine
1175 if (!idl_field) return null;
1178 idl_field :idl_field,
1179 idl_class : class_obj
1185 instance : function(args) { return new ColumnsProvider(args) }
1191 * Generic data provider template class. This is basically an abstract
1192 * class factory service whose instances can be locally modified to
1193 * meet the needs of each individual grid.
1195 .factory('egGridDataProvider',
1196 ['$q','$timeout','$filter','egCore',
1197 function($q , $timeout , $filter , egCore) {
1199 function GridDataProvider(args) {
1200 var gridData = this;
1201 if (!args) args = {};
1204 gridData.get = args.get;
1205 gridData.query = args.query;
1206 gridData.idlClass = args.idlClass;
1207 gridData.columnsProvider = args.columnsProvider;
1209 // Delivers a stream of array data via promise.notify()
1210 // Useful for passing an array of data to egGrid.get()
1211 // If a count is provided, the array will be trimmed to
1212 // the range defined by count and offset
1213 gridData.arrayNotifier = function(arr, offset, count) {
1214 if (!arr || arr.length == 0) return $q.when();
1215 if (count) arr = arr.slice(offset, offset + count);
1216 var def = $q.defer();
1217 // promise notifications are only witnessed when delivered
1218 // after the caller has his hands on the promise object
1219 $timeout(function() {
1220 angular.forEach(arr, def.notify);
1226 // Calls the grid refresh function. Once instantiated, the
1227 // grid will replace this function with it's own refresh()
1228 gridData.refresh = function(noReset) { }
1230 if (!gridData.get) {
1231 // returns a promise whose notify() delivers items
1232 gridData.get = function(index, count) {
1233 console.error("egGridDataProvider.get() not implemented");
1237 // attempts a flat field lookup first. If the column is not
1238 // found on the top-level object, attempts a nested lookup
1239 // TODO: consider a caching layer to speed up template
1240 // rendering, particularly for nested objects?
1241 gridData.itemFieldValue = function(item, column) {
1242 if (column.name in item) {
1243 if (typeof item[column.name] == 'function') {
1244 return item[column.name]();
1246 return item[column.name];
1249 return gridData.nestedItemFieldValue(item, column);
1253 // TODO: deprecate me
1254 gridData.flatItemFieldValue = function(item, column) {
1255 console.warn('gridData.flatItemFieldValue deprecated; '
1256 + 'leave provider.itemFieldValue unset');
1257 return item[column.name];
1260 // given an object and a dot-separated path to a field,
1261 // extract the value of the field. The path can refer
1262 // to function names or object attributes. If the final
1263 // value is an IDL field, run the value through its
1264 // corresponding output filter.
1265 gridData.nestedItemFieldValue = function(obj, column) {
1266 if (obj === null || obj === undefined || obj === '') return '';
1267 if (!column.path) return obj;
1270 var parts = column.path.split('.');
1272 angular.forEach(parts, function(step, idx) {
1273 // object is not fleshed to the expected extent
1274 if (!obj || typeof obj != 'object') {
1279 var cls = obj.classname;
1280 if (cls && (class_obj = egCore.idl.classes[cls])) {
1281 idl_field = class_obj.field_map[step];
1282 obj = obj[step] ? obj[step]() : '';
1284 if (angular.isFunction(obj[step])) {
1292 // We found a nested IDL object which may or may not have
1293 // been configured as a top-level column. Grab the datatype.
1294 if (idl_field && !column.datatype)
1295 column.datatype = idl_field.datatype;
1297 if (obj === null || obj === undefined || obj === '') return '';
1303 instance : function(args) {
1304 return new GridDataProvider(args);
1311 // Factory service for egGridDataManager instances, which are
1312 // responsible for collecting flattened grid data.
1313 .factory('egGridFlatDataProvider',
1314 ['$q','egCore','egGridDataProvider',
1315 function($q , egCore , egGridDataProvider) {
1318 instance : function(args) {
1319 var provider = egGridDataProvider.instance(args);
1321 provider.get = function(offset, count) {
1323 // no query means no call
1324 if (!provider.query ||
1325 angular.equals(provider.query, {}))
1328 // find all of the currently visible columns
1329 var queryFields = {}
1330 angular.forEach(provider.columnsProvider.columns,
1332 // only query IDL-tracked columns
1333 if (!col.adhoc && (col.required || col.visible))
1334 queryFields[col.name] = col.path;
1338 return egCore.net.request(
1340 'open-ils.fielder.flattened_search',
1341 egCore.auth.token(), provider.idlClass,
1342 queryFields, provider.query,
1343 { sort : provider.sort,
1349 //provider.itemFieldValue = provider.flatItemFieldValue;
1356 .directive('egGridColumnDragSource', function() {
1359 require : '^egGrid',
1360 link : function(scope, element, attrs, egGridCtrl) {
1361 angular.element(element).attr('draggable', 'true');
1363 element.bind('dragstart', function(e) {
1364 egGridCtrl.dragColumn = attrs.column;
1365 egGridCtrl.dragType = attrs.dragType || 'move'; // or resize
1366 egGridCtrl.colResizeDir = 0;
1368 if (egGridCtrl.dragType == 'move') {
1369 // style the column getting moved
1370 angular.element(e.target).addClass(
1371 'eg-grid-column-move-handle-active');
1375 element.bind('dragend', function(e) {
1376 if (egGridCtrl.dragType == 'move') {
1377 angular.element(e.target).removeClass(
1378 'eg-grid-column-move-handle-active');
1385 .directive('egGridColumnDragDest', function() {
1388 require : '^egGrid',
1389 link : function(scope, element, attrs, egGridCtrl) {
1391 element.bind('dragover', function(e) { // required for drop
1392 e.stopPropagation();
1394 e.dataTransfer.dropEffect = 'move';
1396 if (egGridCtrl.colResizeDir == 0) return; // move
1398 var cols = egGridCtrl.columnsProvider;
1399 var srcCol = egGridCtrl.dragColumn;
1400 var srcColIdx = cols.indexOf(srcCol);
1402 if (egGridCtrl.colResizeDir == -1) {
1403 if (cols.indexOf(attrs.column) <= srcColIdx) {
1404 egGridCtrl.modifyColumnFlex(
1405 egGridCtrl.columnsProvider.findColumn(
1406 egGridCtrl.dragColumn), -1);
1407 if (cols.columns[srcColIdx+1]) {
1408 // source column shrinks by one, column to the
1409 // right grows by one.
1410 egGridCtrl.modifyColumnFlex(
1411 cols.columns[srcColIdx+1], 1);
1416 if (cols.indexOf(attrs.column) > srcColIdx) {
1417 egGridCtrl.modifyColumnFlex(
1418 egGridCtrl.columnsProvider.findColumn(
1419 egGridCtrl.dragColumn), 1);
1420 if (cols.columns[srcColIdx+1]) {
1421 // source column grows by one, column to the
1422 // right grows by one.
1423 egGridCtrl.modifyColumnFlex(
1424 cols.columns[srcColIdx+1], -1);
1432 element.bind('dragenter', function(e) {
1433 e.stopPropagation();
1435 if (egGridCtrl.dragType == 'move') {
1436 angular.element(e.target).addClass('eg-grid-col-hover');
1438 // resize grips are on the right side of each column.
1439 // dragenter will either occur on the source column
1440 // (dragging left) or the column to the right.
1441 if (egGridCtrl.colResizeDir == 0) {
1442 if (egGridCtrl.dragColumn == attrs.column) {
1443 egGridCtrl.colResizeDir = -1; // west
1445 egGridCtrl.colResizeDir = 1; // east
1451 element.bind('dragleave', function(e) {
1452 e.stopPropagation();
1454 if (egGridCtrl.dragType == 'move') {
1455 angular.element(e.target).removeClass('eg-grid-col-hover');
1459 element.bind('drop', function(e) {
1460 e.stopPropagation();
1462 egGridCtrl.colResizeDir = 0;
1463 if (egGridCtrl.dragType == 'move') {
1464 angular.element(e.target).removeClass('eg-grid-col-hover');
1465 egGridCtrl.onColumnDrop(attrs.column); // move the column
1472 .directive('egGridMenuItem', function() {
1475 require : '^egGrid',
1478 handler : '=', // onclick handler function
1479 divider : '=', // if true, show a divider only
1480 handlerData : '=', // if set, passed as second argument to handler
1481 disabled : '=', // function
1482 hidden : '=' // function
1484 link : function(scope, element, attrs, egGridCtrl) {
1485 egGridCtrl.addMenuItem({
1486 label : scope.label,
1487 handler : scope.handler,
1488 divider : scope.divider,
1489 disabled : scope.disabled,
1490 hidden : scope.hidden,
1491 handlerData : scope.handlerData
1501 * Translates bare IDL object values into display values.
1502 * 1. Passes dates through the angular date filter
1503 * 2. Translates bools to Booleans so the browser can display translated
1504 * value. (Though we could manually translate instead..)
1505 * Others likely to follow...
1507 .filter('egGridValueFilter', ['$filter', function($filter) {
1508 return function(value, column) {
1509 switch(column.datatype) {
1512 // Browser will translate true/false for us
1514 case '1' : // legacy
1518 case '0' : // legacy
1521 // value may be null, '', etc.
1522 default : return '';
1525 // canned angular date filter FTW
1526 if (!column.dateformat)
1527 column.dateformat = 'shortDate';
1528 return $filter('date')(value, column.dateformat);
1530 return $filter('currency')(value);