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 grid.columnsProvider.showAllColumns();
269 $scope.hideAllColumns = function() {
270 grid.columnsProvider.hideAllColumns();
273 $scope.toggleColumnVisibility = function(col) {
274 $scope.gridColumnPickerIsOpen = false;
275 col.visible = !col.visible;
277 // egGridFlatDataProvider only retrieves data to be
278 // displayed. When column visibility changes, it's
279 // necessary to fetch the newly visible column data.
280 if (grid.selfManagedData) grid.collect();
283 // save the columns configuration (position, sort, width) to
284 // eg.grid.<persist-key>
285 $scope.saveConfig = function() {
286 $scope.gridColumnPickerIsOpen = false;
288 if (!grid.persistKey) {
290 "Cannot save settings without a grid persist-key");
294 // only store information about visible columns.
295 var conf = grid.columnsProvider.columns.filter(
296 function(col) {return Boolean(col.visible) });
298 // now scrunch the data down to just the needed info
299 conf = conf.map(function(col) {
300 var c = {name : col.name}
301 // Apart from the name, only store non-default values.
302 // No need to store col.visible, since that's implicit
303 if (col.flex != 2) c.flex = col.flex;
304 if (Number(col.sort)) c.sort = Number(c.sort);
308 egCore.hatch.setItem('eg.grid.' + grid.persistKey, conf)
310 // Save operation performed from the grid configuration UI.
311 // Hide the configuration UI and re-draw w/ sort applied
312 if ($scope.showGridConf)
313 $scope.toggleConfDisplay();
317 // load the columns configuration (position, sort, width) from
318 // eg.grid.<persist-key> and apply the loaded settings to the
319 // columns on our columnsProvider
320 grid.loadConfig = function() {
321 if (!grid.persistKey) return $q.when();
323 return egCore.hatch.getItem('eg.grid.' + grid.persistKey)
324 .then(function(conf) {
327 var columns = grid.columnsProvider.columns;
330 angular.forEach(conf, function(col) {
331 var grid_col = columns.filter(
332 function(c) {return c.name == col.name})[0];
335 // saved column does not match a column in the
336 // current grid. skip it.
340 grid_col.flex = col.flex || 2;
341 grid_col.sort = col.sort || 0;
342 // all saved columns are assumed to be true
343 grid_col.visible = true;
344 new_cols.push(grid_col);
347 // columns which are not expressed within the saved
348 // configuration are marked as non-visible and
349 // appended to the end of the new list of columns.
350 angular.forEach(columns, function(col) {
351 var found = conf.filter(
352 function(c) {return (c.name == col.name)})[0];
359 grid.columnsProvider.columns = new_cols;
364 $scope.onContextMenu = function($event) {
365 var col = angular.element($event.target).attr('column');
366 console.log('selected column ' + col);
369 $scope.page = function() {
370 return (grid.offset / grid.limit) + 1;
373 $scope.goToPage = function(page) {
375 if (angular.isNumber(page) && page > 0) {
376 grid.offset = (page - 1) * grid.limit;
381 $scope.offset = function(o) {
382 if (angular.isNumber(o))
387 $scope.limit = function(l) {
388 if (angular.isNumber(l))
393 $scope.onFirstPage = function() {
394 return grid.offset == 0;
397 $scope.hasNextPage = function() {
398 // we have less data than requested, there must
399 // not be any more pages
400 if (grid.count() < grid.limit) return false;
402 // if the total count is not known, assume that a full
403 // page of data implies more pages are available.
404 if (grid.totalCount == -1) return true;
406 // we have a full page of data, but is there more?
407 return grid.totalCount > (grid.offset + grid.count());
410 $scope.incrementPage = function() {
411 grid.offset += grid.limit;
415 $scope.decrementPage = function() {
416 if (grid.offset < grid.limit) {
419 grid.offset -= grid.limit;
424 // number of items loaded for the current page of results
425 grid.count = function() {
426 return $scope.items.length;
429 // returns the unique identifier value for the provided item
430 // for internal consistency, indexValue is always coerced
432 grid.indexValue = function(item) {
433 if (angular.isObject(item)) {
435 if (angular.isFunction(item[grid.indexField]))
436 return ''+item[grid.indexField]();
437 return ''+item[grid.indexField]; // flat data
440 // passed a non-object; assume it's an index
444 // fires the action handler function for a context action
445 $scope.actionLauncher = function(action) {
446 if (!action.handler) {
448 'No handler specified for "' + action.label + '"');
453 action.handler(grid.getSelectedItems());
455 console.error('Error executing handler for "'
456 + action.label + '" => ' + E + "\n" + E.stack);
460 // returns the list of selected item objects
461 grid.getSelectedItems = function() {
462 return $scope.items.filter(
464 return Boolean($scope.selected[grid.indexValue(item)]);
469 grid.getItemByIndex = function(index) {
470 for (var i = 0; i < $scope.items.length; i++) {
471 var item = $scope.items[i];
472 if (grid.indexValue(item) == index)
477 // selects one row after deselecting all of the others
478 grid.selectOneItem = function(index) {
479 $scope.selected = {};
480 $scope.selected[index] = true;
483 // selects or deselects an item, without affecting the others.
484 // returns true if the item is selected; false if de-selected.
485 grid.toggleSelectOneItem = function(index) {
486 if ($scope.selected[index]) {
487 delete $scope.selected[index];
490 return $scope.selected[index] = true;
494 grid.selectAllItems = function() {
495 angular.forEach($scope.items, function(item) {
496 $scope.selected[grid.indexValue(item)] = true
500 $scope.$watch('selectAll', function(newVal) {
502 grid.selectAllItems();
504 $scope.selected = {};
508 // returns true if item1 appears in the list before item2;
509 // false otherwise. this is slightly more efficient that
510 // finding the position of each then comparing them.
511 // item1 / item2 may be an item or an item index
512 grid.itemComesBefore = function(itemOrIndex1, itemOrIndex2) {
513 var idx1 = grid.indexValue(itemOrIndex1);
514 var idx2 = grid.indexValue(itemOrIndex2);
516 // use for() for early exit
517 for (var i = 0; i < $scope.items.length; i++) {
518 var idx = grid.indexValue($scope.items[i]);
519 if (idx == idx1) return true;
520 if (idx == idx2) return false;
525 // 0-based position of item in the current data set
526 grid.indexOf = function(item) {
527 var idx = grid.indexValue(item);
528 for (var i = 0; i < $scope.items.length; i++) {
529 if (grid.indexValue($scope.items[i]) == idx)
535 grid.modifyColumnFlex = function(column, val) {
537 // prevent flex:0; use hiding instead
541 $scope.modifyColumnFlex = function(col, val) {
542 grid.modifyColumnFlex(col, val);
545 // handles click, control-click, and shift-click
546 $scope.handleRowClick = function($event, item) {
547 var index = grid.indexValue(item);
549 var origSelected = Object.keys($scope.selected);
551 if ($event.ctrlKey || $event.metaKey /* mac command */) {
553 if (grid.toggleSelectOneItem(index))
554 grid.lastSelectedItemIndex = index;
556 } else if ($event.shiftKey) {
559 if (!grid.lastSelectedItemIndex ||
560 index == grid.lastSelectedItemIndex) {
561 grid.selectOneItem(index);
562 grid.lastSelectedItemIndex = index;
566 var selecting = false;
567 var ascending = grid.itemComesBefore(
568 grid.lastSelectedItemIndex, item);
570 grid.indexOf(grid.lastSelectedItemIndex);
572 // update to new last-selected
573 grid.lastSelectedItemIndex = index;
575 // select each row between the last selected and
576 // currently selected items
578 startPos += ascending ? 1 : -1;
579 var curItem = $scope.items[startPos];
581 var curIdx = grid.indexValue(curItem);
582 $scope.selected[curIdx] = true;
583 if (curIdx == index) break; // all done
588 grid.selectOneItem(index);
589 grid.lastSelectedItemIndex = index;
593 // Builds a sort expression from column sort priorities.
594 // called on page load and any time the priorities are modified.
595 grid.compileSort = function() {
596 var sortList = grid.columnsProvider.columns.filter(
597 function(col) { return Number(col.sort) != 0 }
600 if (Math.abs(a.sort) < Math.abs(b.sort))
606 if (sortList.length) {
607 grid.dataProvider.sort = sortList.map(function(col) {
609 blob[col.name] = col.sort < 0 ? 'desc' : 'asc';
615 // builds a sort expression using a single column,
616 // toggling between ascending and descending sort.
617 $scope.quickSort = function(col_name) {
618 var sort = grid.dataProvider.sort;
619 if (sort && sort.length &&
620 sort[0] == col_name) {
622 blob[col_name] = 'desc';
623 grid.dataProvider.sort = [blob];
625 grid.dataProvider.sort = [col_name];
632 // show / hide the grid configuration row
633 $scope.toggleConfDisplay = function() {
634 if ($scope.showGridConf) {
635 $scope.showGridConf = false;
636 if (grid.columnsProvider.hasSortableColumn()) {
637 // only refresh the grid if the user has the
638 // ability to modify the sort priorities.
644 $scope.showGridConf = true;
647 $scope.gridColumnPickerIsOpen = false;
650 // called when a dragged column is dropped onto itself
651 // or any other column
652 grid.onColumnDrop = function(target) {
653 if (angular.isUndefined(target)) return;
654 if (target == grid.dragColumn) return;
655 var srcIdx, targetIdx, srcCol;
656 angular.forEach(grid.columnsProvider.columns,
658 if (col.name == grid.dragColumn) {
661 } else if (col.name == target) {
667 if (srcIdx < targetIdx) targetIdx--;
669 // move src column from old location to new location in
670 // the columns array, then force a page refresh
671 grid.columnsProvider.columns.splice(srcIdx, 1);
672 grid.columnsProvider.columns.splice(targetIdx, 0, srcCol);
676 // prepares a string for inclusion within a CSV document
677 // by escaping commas and quotes and removing newlines.
678 grid.csvDatum = function(str) {
681 str = str.replace(/\n/g, '');
682 if (str.match(/\,/) || str.match(/"/)) {
683 str = str.replace(/"/g, '""');
684 str = '"' + str + '"';
689 // sets the download file name and inserts the current CSV
690 // into a Blob URL for browser download.
691 $scope.generateCSVExportURL = function() {
692 $scope.gridColumnPickerIsOpen = false;
694 // let the file name describe the grid
695 $scope.csvExportFileName =
696 ($scope.mainLabel || grid.persistKey || 'eg_grid_data')
697 .replace(/\s+/g, '_') + '_' + $scope.page();
699 // toss the CSV into a Blob and update the export URL
700 var csv = grid.generateCSV();
701 var blob = new Blob([csv], {type : 'text/plain'});
702 $scope.csvExportURL =
703 ($window.URL || $window.webkitURL).createObjectURL(blob);
706 $scope.printCSV = function() {
707 $scope.gridColumnPickerIsOpen = false;
708 egCore.hatch.print('default', 'text/plain', grid.generateCSV())
709 .then(function() { console.debug('print complete') });
712 // generates CSV for the currently visible grid contents
713 grid.generateCSV = function() {
715 var colCount = grid.columnsProvider.columns.length;
718 angular.forEach(grid.columnsProvider.columns,
720 if (!col.visible) return;
721 csvStr += grid.csvDatum(col.label);
726 csvStr = csvStr.replace(/,$/,'\n');
729 angular.forEach($scope.items, function(item) {
730 angular.forEach(grid.columnsProvider.columns,
732 if (!col.visible) return;
734 var val = grid.dataProvider.itemFieldValue(item, col);
735 // filtered value (dates, etc.)
736 val = $filter('egGridValueFilter')(val, col);
737 csvStr += grid.csvDatum(val);
741 csvStr = csvStr.replace(/,$/,'\n');
747 // Interpolate the value for column.linkpath within the context
748 // of the row item to generate the final link URL.
749 $scope.generateLinkPath = function(col, item) {
750 return egCore.strings.$replace(col.linkpath, {item : item});
753 // If a column provides its own HTML template, translate it,
754 // using the current item for the template scope.
755 // note: $sce is required to avoid security restrictions and
756 // is OK here, since the template comes directly from a
757 // local HTML template (not user input).
758 $scope.translateCellTemplate = function(col, item) {
759 var html = egCore.strings.$replace(col.template, {item : item});
760 return $sce.trustAsHtml(html);
763 $scope.collect = function() { grid.collect() }
765 // asks the dataProvider for a page of data
766 grid.collect = function() {
768 // avoid firing the collect if there is nothing to collect.
769 if (grid.selfManagedData && !grid.dataProvider.query) return;
771 if (grid.collecting) return; // avoid parallel collect()
772 grid.collecting = true;
774 console.debug('egGrid.collect() offset='
775 + grid.offset + '; limit=' + grid.limit);
777 // ensure all of our dropdowns are closed
778 // TODO: git rid of these and just use dropdown-toggle,
779 // which is more reliable.
780 $scope.gridColumnPickerIsOpen = false;
781 $scope.gridRowCountIsOpen = false;
782 $scope.gridPageSelectIsOpen = false;
785 $scope.selected = {};
786 grid.dataProvider.get(grid.offset, grid.limit).then(
788 if (grid.controls.allItemsRetrieved)
789 grid.controls.allItemsRetrieved();
794 $scope.items.push(item)
795 if (grid.controls.itemRetrieved)
796 grid.controls.itemRetrieved(item);
798 }).finally(function() {
799 console.debug('egGrid.collect() complete');
800 grid.collecting = false
810 * eg-grid-field : used for collecting custom field data from the templates.
811 * This directive does not direct display, it just passes data up to the
814 .directive('egGridField', function() {
819 name : '@', // required; unique name
820 path : '@', // optional; flesh path
821 label : '@', // optional; display label
822 flex : '@', // optional; default flex width
823 dateformat : '@', // optional: passed down to egGridValueFilter
825 // if a field is part of an IDL object, but we are unable to
826 // determine the class, because it's nested within a hash
827 // (i.e. we can't navigate directly to the object via the IDL),
828 // idlClass lets us specify the class. This is particularly
829 // useful for nested wildcard fields.
830 parentIdlClass : '@',
832 // optional: for non-IDL columns, specifying a datatype
833 // lets the caller control which display filter is used.
834 // datatype should match the standard IDL datatypes.
837 link : function(scope, element, attrs, egGridCtrl) {
839 // boolean fields are presented as value-less attributes
848 'required' // if set, always fetch data for this column
851 if (angular.isDefined(attrs[field]))
856 // any HTML content within the field is its custom template
857 var tmpl = element.html();
858 if (tmpl && !tmpl.match(/^\s*$/))
859 scope.template = tmpl
861 egGridCtrl.columnsProvider.add(scope);
868 * eg-grid-action : used for specifying actions which may be applied
869 * to items within the grid.
871 .directive('egGridAction', function() {
877 label : '@', // Action label
878 handler : '=', // Action function handler
881 link : function(scope, element, attrs, egGridCtrl) {
882 egGridCtrl.addAction({
884 divider : scope.divider,
885 handler : scope.handler
892 .factory('egGridColumnsProvider', ['egCore', function(egCore) {
894 function ColumnsProvider(args) {
897 cols.stockVisible = [];
898 cols.idlClass = args.idlClass;
899 cols.defaultToHidden = args.defaultToHidden;
900 cols.defaultToNoSort = args.defaultToNoSort;
901 cols.defaultToNoMultiSort = args.defaultToNoMultiSort;
903 // resets column width, visibility, and sort behavior
904 // Visibility resets to the visibility settings defined in the
905 // template (i.e. the original egGridField values).
906 cols.reset = function() {
907 angular.forEach(cols.columns, function(col) {
910 if (cols.stockVisible.indexOf(col.name) > -1) {
918 // returns true if any columns are sortable
919 cols.hasSortableColumn = function() {
920 return cols.columns.filter(
922 return col.sortable || col.multisortable;
927 cols.showAllColumns = function() {
928 $scope.gridColumnPickerIsOpen = false;
929 angular.forEach(cols.columns, function(column) {
930 column.visible = true;
932 if (grid.selfManagedData) grid.collect();
935 cols.hideAllColumns = function() {
936 $scope.gridColumnPickerIsOpen = false;
937 angular.forEach(cols.columns, function(col) {
940 // note: no need to fetch new data if no columns are visible
943 cols.indexOf = function(name) {
944 for (var i = 0; i < cols.columns.length; i++) {
945 if (cols.columns[i].name == name)
951 cols.findColumn = function(name) {
952 return cols.columns[cols.indexOf(name)];
955 cols.compileAutoColumns = function() {
956 var idl_class = egCore.idl.classes[cols.idlClass];
959 idl_class.fields.sort(
960 function(a, b) { return a.name < b.name ? -1 : 1 }),
962 if (field.virtual) return;
963 if (field.datatype == 'link' || field.datatype == 'org_unit') {
964 // if the field is a link and the linked class has a
965 // "selector" field specified, use the selector field
966 // as the display field for the columns.
967 // flattener will take care of the fleshing.
968 if (field['class']) {
969 var selector_field = egCore.idl.classes[field['class']].fields
970 .filter(function(f) { return Boolean(f.selector) })[0];
971 if (selector_field) {
972 field.path = field.name + '.' + selector_field.selector;
976 cols.add(field, true);
981 // if a column definition has a path with a wildcard, create
982 // columns for all non-virtual fields at the specified
983 // position in the path.
984 cols.expandPath = function(colSpec) {
986 var dotpath = colSpec.path.replace(/\.?\*$/,'');
989 if (colSpec.parentIdlClass) {
990 class_obj = egCore.idl.classes[colSpec.parentIdlClass];
994 class_obj = egCore.idl.classes[cols.idlClass];
995 if (!class_obj) return;
997 var path_parts = dotpath.split(/\./);
999 // find the IDL class definition for the last element in the
1000 // path before the .*
1001 // an empty path_parts means expand the root class
1003 for (var path_idx in path_parts) {
1004 var part = path_parts[path_idx];
1005 var idl_field = class_obj.field_map[part];
1007 // unless we're at the end of the list, this field should
1008 // link to another class.
1009 if (idl_field && idl_field['class'] && (
1010 idl_field.datatype == 'link' ||
1011 idl_field.datatype == 'org_unit')) {
1012 class_obj = egCore.idl.classes[idl_field['class']];
1014 if (path_idx < (path_parts.length - 1)) {
1015 // we ran out of classes to hop through before
1016 // we ran out of path components
1017 console.error("egGrid: invalid IDL path: " + dotpath);
1025 angular.forEach(class_obj.fields, function(field) {
1027 // Only show wildcard fields where we have data to show
1028 // Virtual and un-fleshed links will not have any data.
1029 if (field.virtual || (
1030 field.datatype == 'link' || field.datatype == 'org_unit'))
1033 var col = cols.cloneFromScope(colSpec);
1034 col.path = dotpath + '.' + field.name;
1035 cols.add(col, false, true,
1036 {idl_field : field, idl_class : class_obj});
1041 "egGrid: wildcard path does not resolve to an object: "
1046 // angular.clone(scopeObject) is not permittable. Manually copy
1047 // the fields over that we need (so the scope object can go away).
1048 cols.cloneFromScope = function(colSpec) {
1050 name : colSpec.name,
1051 label : colSpec.label,
1052 path : colSpec.path,
1053 flex : Number(colSpec.flex) || 2,
1054 sort : Number(colSpec.sort) || 0,
1055 required : colSpec.required,
1056 linkpath : colSpec.linkpath,
1057 template : colSpec.template,
1058 visible : colSpec.visible,
1059 hidden : colSpec.hidden,
1060 datatype : colSpec.datatype,
1061 sortable : colSpec.sortable,
1062 nonsortable : colSpec.nonsortable,
1063 multisortable : colSpec.multisortable,
1064 nonmultisortable : colSpec.nonmultisortable,
1065 dateformat : colSpec.dateformat,
1066 parentIdlClass : colSpec.parentIdlClass
1071 // Add a column to the columns collection.
1072 // Columns may come from a slim eg-columns-field or
1073 // directly from the IDL.
1074 cols.add = function(colSpec, fromIDL, fromExpand, idl_info) {
1076 // First added column with the specified path takes precedence.
1077 // This allows for specific definitions followed by wildcard
1078 // definitions. If a match is found, back out.
1079 if (cols.columns.filter(function(c) {
1080 return (c.path == colSpec.path) })[0]) {
1081 //console.debug('skipping column ' + colSpec.path);
1085 var column = fromExpand ? colSpec : cols.cloneFromScope(colSpec);
1087 if (column.path && column.path.match(/\*$/))
1088 return cols.expandPath(colSpec);
1090 if (!column.name) column.name = column.path;
1091 if (!column.path) column.path = column.name;
1093 if (column.visible || (!cols.defaultToHidden && !column.hidden))
1094 column.visible = true;
1096 if (column.sortable || (!cols.defaultToNoSort && !column.nonsortable))
1097 column.sortable = true;
1099 if (column.multisortable ||
1100 (!cols.defaultToNoMultiSort && !column.nonmultisortable))
1101 column.multisortable = true;
1103 cols.columns.push(column);
1105 // Track which columns are visible by default in case we
1106 // need to reset column visibility
1108 cols.stockVisible.push(column.name);
1110 if (fromIDL) return; // directly from egIDL. nothing left to do.
1112 // lookup the matching IDL field
1113 if (!idl_info && cols.idlClass)
1114 idl_info = cols.idlFieldFromPath(column.path);
1117 // column is not represented within the IDL
1118 column.adhoc = true;
1122 column.datatype = idl_info.idl_field.datatype;
1124 if (!column.label) {
1125 column.label = idl_info.idl_field.label || column.name;
1127 // append class label to column label to better differentiate
1128 // columns in the selector.
1129 // Disabled for now, since it results in columns w/ really
1130 // long names, making the grid unappealing when any of
1131 // these colmns are selected.
1132 // TODO: consider nesting the colum picker by class?
1135 idl_info.idl_class.label || idl_info.idl_class.name;
1136 column.label = label + '::' + column.label;
1142 // finds the IDL field from the dotpath, using the columns
1143 // idlClass as the base.
1144 cols.idlFieldFromPath = function(dotpath) {
1145 var class_obj = egCore.idl.classes[cols.idlClass];
1146 var path_parts = dotpath.split(/\./);
1149 for (var path_idx in path_parts) {
1150 var part = path_parts[path_idx];
1151 idl_field = class_obj.field_map[part];
1153 if (idl_field && idl_field['class'] && (
1154 idl_field.datatype == 'link' ||
1155 idl_field.datatype == 'org_unit')) {
1156 class_obj = egCore.idl.classes[idl_field['class']];
1158 // else, path is not in the IDL, which is fine
1161 if (!idl_field) return null;
1164 idl_field :idl_field,
1165 idl_class : class_obj
1171 instance : function(args) { return new ColumnsProvider(args) }
1177 * Generic data provider template class. This is basically an abstract
1178 * class factory service whose instances can be locally modified to
1179 * meet the needs of each individual grid.
1181 .factory('egGridDataProvider',
1182 ['$q','$timeout','$filter','egCore',
1183 function($q , $timeout , $filter , egCore) {
1185 function GridDataProvider(args) {
1186 var gridData = this;
1187 if (!args) args = {};
1190 gridData.get = args.get;
1191 gridData.query = args.query;
1192 gridData.idlClass = args.idlClass;
1193 gridData.columnsProvider = args.columnsProvider;
1195 // Delivers a stream of array data via promise.notify()
1196 // Useful for passing an array of data to egGrid.get()
1197 // If a count is provided, the array will be trimmed to
1198 // the range defined by count and offset
1199 gridData.arrayNotifier = function(arr, offset, count) {
1200 if (!arr || arr.length == 0) return $q.when();
1201 if (count) arr = arr.slice(offset, offset + count);
1202 var def = $q.defer();
1203 // promise notifications are only witnessed when delivered
1204 // after the caller has his hands on the promise object
1205 $timeout(function() {
1206 angular.forEach(arr, def.notify);
1212 // Calls the grid refresh function. Once instantiated, the
1213 // grid will replace this function with it's own refresh()
1214 gridData.refresh = function(noReset) { }
1216 if (!gridData.get) {
1217 // returns a promise whose notify() delivers items
1218 gridData.get = function(index, count) {
1219 console.error("egGridDataProvider.get() not implemented");
1223 // attempts a flat field lookup first. If the column is not
1224 // found on the top-level object, attempts a nested lookup
1225 // TODO: consider a caching layer to speed up template
1226 // rendering, particularly for nested objects?
1227 gridData.itemFieldValue = function(item, column) {
1228 if (column.name in item) {
1229 if (typeof item[column.name] == 'function') {
1230 return item[column.name]();
1232 return item[column.name];
1235 return gridData.nestedItemFieldValue(item, column);
1239 // TODO: deprecate me
1240 gridData.flatItemFieldValue = function(item, column) {
1241 console.warn('gridData.flatItemFieldValue deprecated; '
1242 + 'leave provider.itemFieldValue unset');
1243 return item[column.name];
1246 // given an object and a dot-separated path to a field,
1247 // extract the value of the field. The path can refer
1248 // to function names or object attributes. If the final
1249 // value is an IDL field, run the value through its
1250 // corresponding output filter.
1251 gridData.nestedItemFieldValue = function(obj, column) {
1252 if (obj === null || obj === undefined || obj === '') return '';
1253 if (!column.path) return obj;
1256 var parts = column.path.split('.');
1258 angular.forEach(parts, function(step, idx) {
1259 // object is not fleshed to the expected extent
1260 if (!obj || typeof obj != 'object') {
1265 var cls = obj.classname;
1266 if (cls && (class_obj = egCore.idl.classes[cls])) {
1267 idl_field = class_obj.field_map[step];
1268 obj = obj[step] ? obj[step]() : '';
1270 if (angular.isFunction(obj[step])) {
1278 // We found a nested IDL object which may or may not have
1279 // been configured as a top-level column. Grab the datatype.
1280 if (idl_field && !column.datatype)
1281 column.datatype = idl_field.datatype;
1283 if (obj === null || obj === undefined || obj === '') return '';
1289 instance : function(args) {
1290 return new GridDataProvider(args);
1297 // Factory service for egGridDataManager instances, which are
1298 // responsible for collecting flattened grid data.
1299 .factory('egGridFlatDataProvider',
1300 ['$q','egCore','egGridDataProvider',
1301 function($q , egCore , egGridDataProvider) {
1304 instance : function(args) {
1305 var provider = egGridDataProvider.instance(args);
1307 provider.get = function(offset, count) {
1309 // no query means no call
1310 if (!provider.query ||
1311 angular.equals(provider.query, {}))
1314 // find all of the currently visible columns
1315 var queryFields = {}
1316 angular.forEach(provider.columnsProvider.columns,
1318 // only query IDL-tracked columns
1319 if (!col.adhoc && (col.required || col.visible))
1320 queryFields[col.name] = col.path;
1324 return egCore.net.request(
1326 'open-ils.fielder.flattened_search',
1327 egCore.auth.token(), provider.idlClass,
1328 queryFields, provider.query,
1329 { sort : provider.sort,
1335 //provider.itemFieldValue = provider.flatItemFieldValue;
1342 .directive('egGridColumnDragSource', function() {
1345 require : '^egGrid',
1346 link : function(scope, element, attrs, egGridCtrl) {
1347 angular.element(element).attr('draggable', 'true');
1349 element.bind('dragstart', function(e) {
1350 egGridCtrl.dragColumn = attrs.column;
1351 egGridCtrl.dragType = attrs.dragType || 'move'; // or resize
1352 egGridCtrl.colResizeDir = 0;
1354 if (egGridCtrl.dragType == 'move') {
1355 // style the column getting moved
1356 angular.element(e.target).addClass(
1357 'eg-grid-column-move-handle-active');
1361 element.bind('dragend', function(e) {
1362 if (egGridCtrl.dragType == 'move') {
1363 angular.element(e.target).removeClass(
1364 'eg-grid-column-move-handle-active');
1371 .directive('egGridColumnDragDest', function() {
1374 require : '^egGrid',
1375 link : function(scope, element, attrs, egGridCtrl) {
1377 element.bind('dragover', function(e) { // required for drop
1378 e.stopPropagation();
1380 e.dataTransfer.dropEffect = 'move';
1382 if (egGridCtrl.colResizeDir == 0) return; // move
1384 var cols = egGridCtrl.columnsProvider;
1385 var srcCol = egGridCtrl.dragColumn;
1386 var srcColIdx = cols.indexOf(srcCol);
1388 if (egGridCtrl.colResizeDir == -1) {
1389 if (cols.indexOf(attrs.column) <= srcColIdx) {
1390 egGridCtrl.modifyColumnFlex(
1391 egGridCtrl.columnsProvider.findColumn(
1392 egGridCtrl.dragColumn), -1);
1393 if (cols.columns[srcColIdx+1]) {
1394 // source column shrinks by one, column to the
1395 // right grows by one.
1396 egGridCtrl.modifyColumnFlex(
1397 cols.columns[srcColIdx+1], 1);
1402 if (cols.indexOf(attrs.column) > srcColIdx) {
1403 egGridCtrl.modifyColumnFlex(
1404 egGridCtrl.columnsProvider.findColumn(
1405 egGridCtrl.dragColumn), 1);
1406 if (cols.columns[srcColIdx+1]) {
1407 // source column grows by one, column to the
1408 // right grows by one.
1409 egGridCtrl.modifyColumnFlex(
1410 cols.columns[srcColIdx+1], -1);
1418 element.bind('dragenter', function(e) {
1419 e.stopPropagation();
1421 if (egGridCtrl.dragType == 'move') {
1422 angular.element(e.target).addClass('eg-grid-col-hover');
1424 // resize grips are on the right side of each column.
1425 // dragenter will either occur on the source column
1426 // (dragging left) or the column to the right.
1427 if (egGridCtrl.colResizeDir == 0) {
1428 if (egGridCtrl.dragColumn == attrs.column) {
1429 egGridCtrl.colResizeDir = -1; // west
1431 egGridCtrl.colResizeDir = 1; // east
1437 element.bind('dragleave', function(e) {
1438 e.stopPropagation();
1440 if (egGridCtrl.dragType == 'move') {
1441 angular.element(e.target).removeClass('eg-grid-col-hover');
1445 element.bind('drop', function(e) {
1446 e.stopPropagation();
1448 egGridCtrl.colResizeDir = 0;
1449 if (egGridCtrl.dragType == 'move') {
1450 angular.element(e.target).removeClass('eg-grid-col-hover');
1451 egGridCtrl.onColumnDrop(attrs.column); // move the column
1458 .directive('egGridMenuItem', function() {
1461 require : '^egGrid',
1464 handler : '=', // onclick handler function
1465 divider : '=', // if true, show a divider only
1466 handlerData : '=', // if set, passed as second argument to handler
1467 disabled : '=', // function
1468 hidden : '=' // function
1470 link : function(scope, element, attrs, egGridCtrl) {
1471 egGridCtrl.addMenuItem({
1472 label : scope.label,
1473 handler : scope.handler,
1474 divider : scope.divider,
1475 disabled : scope.disabled,
1476 hidden : scope.hidden,
1477 handlerData : scope.handlerData
1487 * Translates bare IDL object values into display values.
1488 * 1. Passes dates through the angular date filter
1489 * 2. Translates bools to Booleans so the browser can display translated
1490 * value. (Though we could manually translate instead..)
1491 * Others likely to follow...
1493 .filter('egGridValueFilter', ['$filter', function($filter) {
1494 return function(value, column) {
1495 switch(column.datatype) {
1498 // Browser will translate true/false for us
1500 case '1' : // legacy
1504 case '0' : // legacy
1507 // value may be null, '', etc.
1508 default : return '';
1511 // canned angular date filter FTW
1512 if (!column.dateformat)
1513 column.dateformat = 'shortDate';
1514 return $filter('date')(value, column.dateformat);
1516 return $filter('currency')(value);