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() {
94 $scope.showGridConf = false;
97 $scope.actions = []; // actions for selected items
98 $scope.menuItems = []; // global actions
100 // remove some unneeded values from the scope to reduce bloat
102 grid.idlClass = $scope.idlClass;
103 delete $scope.idlClass;
105 grid.persistKey = $scope.persistKey;
106 delete $scope.persistKey;
108 var stored_limit = 0;
109 if (grid.persistKey) {
110 var stored_limit = Number(
111 egCore.hatch.getLocalItem('eg.grid.' + grid.persistKey + '.limit')
114 grid.limit = Number(stored_limit) || Number($scope.pageSize) || 25;
116 grid.indexField = $scope.idField;
117 delete $scope.idField;
119 grid.dataProvider = $scope.itemsProvider;
121 var features = ($scope.features) ?
122 $scope.features.split(',') : [];
123 delete $scope.features;
125 if (!grid.indexField && grid.idlClass)
126 grid.indexField = egCore.idl.classes[grid.idlClass].pkey;
128 grid.columnsProvider = egGridColumnsProvider.instance({
129 idlClass : grid.idlClass,
130 defaultToHidden : (features.indexOf('-display') > -1),
131 defaultToNoSort : (features.indexOf('-sort') > -1),
132 defaultToNoMultiSort : (features.indexOf('-multisort') > -1)
135 $scope.handleAutoFields = function() {
136 if ($scope.autoFields) {
137 if (grid.autoLabel) {
139 egCore.idl.classes[grid.idlClass].label;
141 grid.columnsProvider.compileAutoColumns();
142 delete $scope.autoFields;
146 if (!grid.dataProvider) {
147 // no provider, um, provided.
148 // Use a flat data provider
150 grid.selfManagedData = true;
151 grid.dataProvider = egGridFlatDataProvider.instance({
152 indexField : grid.indexField,
153 idlClass : grid.idlClass,
154 columnsProvider : grid.columnsProvider,
159 $scope.itemFieldValue = grid.dataProvider.itemFieldValue;
160 $scope.indexValue = function(item) {
161 return grid.indexValue(item)
164 grid.applyControlFunctions();
166 grid.loadConfig().then(function() {
167 // link columns to scope after loadConfig(), since it
168 // replaces the columns array.
169 $scope.columns = grid.columnsProvider.columns;
172 // NOTE: grid.collect() is first called from link(), not here.
175 // link our control functions into the gridControls
176 // scope object so the caller can access them.
177 grid.applyControlFunctions = function() {
179 // we use some of these controls internally, so sett
180 // them up even if the caller doesn't request them.
181 var controls = $scope.gridControls || {};
183 // link in the control functions
184 controls.selectedItems = function() {
185 return grid.getSelectedItems()
188 controls.allItems = function() {
192 controls.selectItems = function(ids) {
194 $scope.selected = {};
195 angular.forEach(ids, function(i) {
196 $scope.selected[''+i] = true;
200 // if the caller provided a functional setQuery,
201 // extract the value before replacing it
202 if (controls.setQuery) {
203 grid.dataProvider.query =
207 controls.setQuery = function(query) {
208 grid.dataProvider.query = query;
212 // if the caller provided a functional setSort
213 // extract the value before replacing it
214 grid.dataProvider.sort =
215 controls.setSort ? controls.setSort() : [];
217 controls.setSort = function(sort) {
221 controls.refresh = function(noReset) {
222 if (!noReset) grid.offset = 0;
226 controls.setLimit = function(limit) {
228 egCore.hatch.setLocalItem('eg.grid.' + grid.persistKey + '.limit', limit);
231 controls.getLimit = function() {
234 controls.setOffset = function(offset) {
235 grid.offset = offset;
237 controls.getOffset = function() {
241 grid.dataProvider.refresh = controls.refresh;
242 grid.controls = controls;
245 // add a new (global) grid menu item
246 grid.addMenuItem = function(item) {
247 $scope.menuItems.push(item);
248 var handler = item.handler;
249 item.handler = function() {
250 $scope.gridMenuIsOpen = false; // close menu
253 item.handlerData, grid.getSelectedItems());
258 // add a selected-items action
259 grid.addAction = function(act) {
260 $scope.actions.push(act);
263 // remove the stored column configuration preferenc, then recover
264 // the column visibility information from the initial page load.
265 $scope.resetColumns = function() {
266 $scope.gridColumnPickerIsOpen = false;
267 egCore.hatch.removeItem('eg.grid.' + grid.persistKey)
269 grid.columnsProvider.reset();
270 if (grid.selfManagedData) grid.collect();
274 $scope.showAllColumns = function() {
275 $scope.gridColumnPickerIsOpen = false;
276 grid.columnsProvider.showAllColumns();
277 if (grid.selfManagedData) grid.collect();
280 $scope.hideAllColumns = function() {
281 $scope.gridColumnPickerIsOpen = false;
282 grid.columnsProvider.hideAllColumns();
283 // note: no need to fetch new data if no columns are visible
286 $scope.toggleColumnVisibility = function(col) {
287 $scope.gridColumnPickerIsOpen = false;
288 col.visible = !col.visible;
290 // egGridFlatDataProvider only retrieves data to be
291 // displayed. When column visibility changes, it's
292 // necessary to fetch the newly visible column data.
293 if (grid.selfManagedData) grid.collect();
296 // save the columns configuration (position, sort, width) to
297 // eg.grid.<persist-key>
298 $scope.saveConfig = function() {
299 $scope.gridColumnPickerIsOpen = false;
301 if (!grid.persistKey) {
303 "Cannot save settings without a grid persist-key");
307 // only store information about visible columns.
308 var conf = grid.columnsProvider.columns.filter(
309 function(col) {return Boolean(col.visible) });
311 // now scrunch the data down to just the needed info
312 conf = conf.map(function(col) {
313 var c = {name : col.name}
314 // Apart from the name, only store non-default values.
315 // No need to store col.visible, since that's implicit
316 if (col.flex != 2) c.flex = col.flex;
317 if (Number(col.sort)) c.sort = Number(c.sort);
321 egCore.hatch.setItem('eg.grid.' + grid.persistKey, conf)
323 // Save operation performed from the grid configuration UI.
324 // Hide the configuration UI and re-draw w/ sort applied
325 if ($scope.showGridConf)
326 $scope.toggleConfDisplay();
330 // load the columns configuration (position, sort, width) from
331 // eg.grid.<persist-key> and apply the loaded settings to the
332 // columns on our columnsProvider
333 grid.loadConfig = function() {
334 if (!grid.persistKey) return $q.when();
336 return egCore.hatch.getItem('eg.grid.' + grid.persistKey)
337 .then(function(conf) {
340 var columns = grid.columnsProvider.columns;
343 angular.forEach(conf, function(col) {
344 var grid_col = columns.filter(
345 function(c) {return c.name == col.name})[0];
348 // saved column does not match a column in the
349 // current grid. skip it.
353 grid_col.flex = col.flex || 2;
354 grid_col.sort = col.sort || 0;
355 // all saved columns are assumed to be true
356 grid_col.visible = true;
357 new_cols.push(grid_col);
360 // columns which are not expressed within the saved
361 // configuration are marked as non-visible and
362 // appended to the end of the new list of columns.
363 angular.forEach(columns, function(col) {
364 var found = conf.filter(
365 function(c) {return (c.name == col.name)})[0];
372 grid.columnsProvider.columns = new_cols;
377 $scope.onContextMenu = function($event) {
378 var col = angular.element($event.target).attr('column');
379 console.log('selected column ' + col);
382 $scope.page = function() {
383 return (grid.offset / grid.limit) + 1;
386 $scope.goToPage = function(page) {
388 if (angular.isNumber(page) && page > 0) {
389 grid.offset = (page - 1) * grid.limit;
394 $scope.offset = function(o) {
395 if (angular.isNumber(o))
400 $scope.limit = function(l) {
401 if (angular.isNumber(l)) {
403 egCore.hatch.setLocalItem('eg.grid.' + grid.persistKey + '.limit', l);
409 $scope.onFirstPage = function() {
410 return grid.offset == 0;
413 $scope.hasNextPage = function() {
414 // we have less data than requested, there must
415 // not be any more pages
416 if (grid.count() < grid.limit) return false;
418 // if the total count is not known, assume that a full
419 // page of data implies more pages are available.
420 if (grid.totalCount == -1) return true;
422 // we have a full page of data, but is there more?
423 return grid.totalCount > (grid.offset + grid.count());
426 $scope.incrementPage = function() {
427 grid.offset += grid.limit;
431 $scope.decrementPage = function() {
432 if (grid.offset < grid.limit) {
435 grid.offset -= grid.limit;
440 // number of items loaded for the current page of results
441 grid.count = function() {
442 return $scope.items.length;
445 // returns the unique identifier value for the provided item
446 // for internal consistency, indexValue is always coerced
448 grid.indexValue = function(item) {
449 if (angular.isObject(item)) {
451 if (angular.isFunction(item[grid.indexField]))
452 return ''+item[grid.indexField]();
453 return ''+item[grid.indexField]; // flat data
456 // passed a non-object; assume it's an index
460 // fires the action handler function for a context action
461 $scope.actionLauncher = function(action) {
462 if (!action.handler) {
464 'No handler specified for "' + action.label + '"');
469 action.handler(grid.getSelectedItems());
471 console.error('Error executing handler for "'
472 + action.label + '" => ' + E + "\n" + E.stack);
476 // returns the list of selected item objects
477 grid.getSelectedItems = function() {
478 return $scope.items.filter(
480 return Boolean($scope.selected[grid.indexValue(item)]);
485 grid.getItemByIndex = function(index) {
486 for (var i = 0; i < $scope.items.length; i++) {
487 var item = $scope.items[i];
488 if (grid.indexValue(item) == index)
493 // selects one row after deselecting all of the others
494 grid.selectOneItem = function(index) {
495 $scope.selected = {};
496 $scope.selected[index] = true;
499 // selects or deselects an item, without affecting the others.
500 // returns true if the item is selected; false if de-selected.
501 grid.toggleSelectOneItem = function(index) {
502 if ($scope.selected[index]) {
503 delete $scope.selected[index];
506 return $scope.selected[index] = true;
510 grid.selectAllItems = function() {
511 angular.forEach($scope.items, function(item) {
512 $scope.selected[grid.indexValue(item)] = true
516 $scope.$watch('selectAll', function(newVal) {
518 grid.selectAllItems();
520 $scope.selected = {};
524 // returns true if item1 appears in the list before item2;
525 // false otherwise. this is slightly more efficient that
526 // finding the position of each then comparing them.
527 // item1 / item2 may be an item or an item index
528 grid.itemComesBefore = function(itemOrIndex1, itemOrIndex2) {
529 var idx1 = grid.indexValue(itemOrIndex1);
530 var idx2 = grid.indexValue(itemOrIndex2);
532 // use for() for early exit
533 for (var i = 0; i < $scope.items.length; i++) {
534 var idx = grid.indexValue($scope.items[i]);
535 if (idx == idx1) return true;
536 if (idx == idx2) return false;
541 // 0-based position of item in the current data set
542 grid.indexOf = function(item) {
543 var idx = grid.indexValue(item);
544 for (var i = 0; i < $scope.items.length; i++) {
545 if (grid.indexValue($scope.items[i]) == idx)
551 grid.modifyColumnFlex = function(column, val) {
553 // prevent flex:0; use hiding instead
557 $scope.modifyColumnFlex = function(col, val) {
558 grid.modifyColumnFlex(col, val);
561 // handles click, control-click, and shift-click
562 $scope.handleRowClick = function($event, item) {
563 var index = grid.indexValue(item);
565 var origSelected = Object.keys($scope.selected);
567 if ($event.ctrlKey || $event.metaKey /* mac command */) {
569 if (grid.toggleSelectOneItem(index))
570 grid.lastSelectedItemIndex = index;
572 } else if ($event.shiftKey) {
575 if (!grid.lastSelectedItemIndex ||
576 index == grid.lastSelectedItemIndex) {
577 grid.selectOneItem(index);
578 grid.lastSelectedItemIndex = index;
582 var selecting = false;
583 var ascending = grid.itemComesBefore(
584 grid.lastSelectedItemIndex, item);
586 grid.indexOf(grid.lastSelectedItemIndex);
588 // update to new last-selected
589 grid.lastSelectedItemIndex = index;
591 // select each row between the last selected and
592 // currently selected items
594 startPos += ascending ? 1 : -1;
595 var curItem = $scope.items[startPos];
597 var curIdx = grid.indexValue(curItem);
598 $scope.selected[curIdx] = true;
599 if (curIdx == index) break; // all done
604 grid.selectOneItem(index);
605 grid.lastSelectedItemIndex = index;
609 // Builds a sort expression from column sort priorities.
610 // called on page load and any time the priorities are modified.
611 grid.compileSort = function() {
612 var sortList = grid.columnsProvider.columns.filter(
613 function(col) { return Number(col.sort) != 0 }
616 if (Math.abs(a.sort) < Math.abs(b.sort))
622 if (sortList.length) {
623 grid.dataProvider.sort = sortList.map(function(col) {
625 blob[col.name] = col.sort < 0 ? 'desc' : 'asc';
631 // builds a sort expression using a single column,
632 // toggling between ascending and descending sort.
633 $scope.quickSort = function(col_name) {
634 var sort = grid.dataProvider.sort;
635 if (sort && sort.length &&
636 sort[0] == col_name) {
638 blob[col_name] = 'desc';
639 grid.dataProvider.sort = [blob];
641 grid.dataProvider.sort = [col_name];
648 // show / hide the grid configuration row
649 $scope.toggleConfDisplay = function() {
650 if ($scope.showGridConf) {
651 $scope.showGridConf = false;
652 if (grid.columnsProvider.hasSortableColumn()) {
653 // only refresh the grid if the user has the
654 // ability to modify the sort priorities.
660 $scope.showGridConf = true;
663 $scope.gridColumnPickerIsOpen = false;
666 // called when a dragged column is dropped onto itself
667 // or any other column
668 grid.onColumnDrop = function(target) {
669 if (angular.isUndefined(target)) return;
670 if (target == grid.dragColumn) return;
671 var srcIdx, targetIdx, srcCol;
672 angular.forEach(grid.columnsProvider.columns,
674 if (col.name == grid.dragColumn) {
677 } else if (col.name == target) {
683 if (srcIdx < targetIdx) targetIdx--;
685 // move src column from old location to new location in
686 // the columns array, then force a page refresh
687 grid.columnsProvider.columns.splice(srcIdx, 1);
688 grid.columnsProvider.columns.splice(targetIdx, 0, srcCol);
692 // prepares a string for inclusion within a CSV document
693 // by escaping commas and quotes and removing newlines.
694 grid.csvDatum = function(str) {
697 str = str.replace(/\n/g, '');
698 if (str.match(/\,/) || str.match(/"/)) {
699 str = str.replace(/"/g, '""');
700 str = '"' + str + '"';
705 // sets the download file name and inserts the current CSV
706 // into a Blob URL for browser download.
707 $scope.generateCSVExportURL = function() {
708 $scope.gridColumnPickerIsOpen = false;
710 // let the file name describe the grid
711 $scope.csvExportFileName =
712 ($scope.mainLabel || grid.persistKey || 'eg_grid_data')
713 .replace(/\s+/g, '_') + '_' + $scope.page();
715 // toss the CSV into a Blob and update the export URL
716 var csv = grid.generateCSV();
717 var blob = new Blob([csv], {type : 'text/plain'});
718 $scope.csvExportURL =
719 ($window.URL || $window.webkitURL).createObjectURL(blob);
722 $scope.printCSV = function() {
723 $scope.gridColumnPickerIsOpen = false;
726 content : grid.generateCSV(),
727 content_type : 'text/plain'
731 // generates CSV for the currently visible grid contents
732 grid.generateCSV = function() {
734 var colCount = grid.columnsProvider.columns.length;
737 angular.forEach(grid.columnsProvider.columns,
739 if (!col.visible) return;
740 csvStr += grid.csvDatum(col.label);
745 csvStr = csvStr.replace(/,$/,'\n');
748 angular.forEach($scope.items, function(item) {
749 angular.forEach(grid.columnsProvider.columns,
751 if (!col.visible) return;
753 var val = grid.dataProvider.itemFieldValue(item, col);
754 // filtered value (dates, etc.)
755 val = $filter('egGridValueFilter')(val, col);
756 csvStr += grid.csvDatum(val);
760 csvStr = csvStr.replace(/,$/,'\n');
766 // Interpolate the value for column.linkpath within the context
767 // of the row item to generate the final link URL.
768 $scope.generateLinkPath = function(col, item) {
769 return egCore.strings.$replace(col.linkpath, {item : item});
772 // If a column provides its own HTML template, translate it,
773 // using the current item for the template scope.
774 // note: $sce is required to avoid security restrictions and
775 // is OK here, since the template comes directly from a
776 // local HTML template (not user input).
777 $scope.translateCellTemplate = function(col, item) {
778 var html = egCore.strings.$replace(col.template, {item : item});
779 return $sce.trustAsHtml(html);
782 $scope.collect = function() { grid.collect() }
784 // asks the dataProvider for a page of data
785 grid.collect = function() {
787 // avoid firing the collect if there is nothing to collect.
788 if (grid.selfManagedData && !grid.dataProvider.query) return;
790 if (grid.collecting) return; // avoid parallel collect()
791 grid.collecting = true;
793 console.debug('egGrid.collect() offset='
794 + grid.offset + '; limit=' + grid.limit);
796 // ensure all of our dropdowns are closed
797 // TODO: git rid of these and just use dropdown-toggle,
798 // which is more reliable.
799 $scope.gridColumnPickerIsOpen = false;
800 $scope.gridRowCountIsOpen = false;
801 $scope.gridPageSelectIsOpen = false;
804 $scope.selected = {};
805 grid.dataProvider.get(grid.offset, grid.limit).then(
807 if (grid.controls.allItemsRetrieved)
808 grid.controls.allItemsRetrieved();
813 $scope.items.push(item)
814 if (grid.controls.itemRetrieved)
815 grid.controls.itemRetrieved(item);
817 }).finally(function() {
818 console.debug('egGrid.collect() complete');
819 grid.collecting = false
829 * eg-grid-field : used for collecting custom field data from the templates.
830 * This directive does not direct display, it just passes data up to the
833 .directive('egGridField', function() {
838 name : '@', // required; unique name
839 path : '@', // optional; flesh path
840 ignore: '@', // optional; fields to ignore when path is a wildcard
841 label : '@', // optional; display label
842 flex : '@', // optional; default flex width
843 dateformat : '@', // optional: passed down to egGridValueFilter
845 // if a field is part of an IDL object, but we are unable to
846 // determine the class, because it's nested within a hash
847 // (i.e. we can't navigate directly to the object via the IDL),
848 // idlClass lets us specify the class. This is particularly
849 // useful for nested wildcard fields.
850 parentIdlClass : '@',
852 // optional: for non-IDL columns, specifying a datatype
853 // lets the caller control which display filter is used.
854 // datatype should match the standard IDL datatypes.
857 link : function(scope, element, attrs, egGridCtrl) {
859 // boolean fields are presented as value-less attributes
868 'required' // if set, always fetch data for this column
871 if (angular.isDefined(attrs[field]))
876 // any HTML content within the field is its custom template
877 var tmpl = element.html();
878 if (tmpl && !tmpl.match(/^\s*$/))
879 scope.template = tmpl
881 egGridCtrl.columnsProvider.add(scope);
888 * eg-grid-action : used for specifying actions which may be applied
889 * to items within the grid.
891 .directive('egGridAction', function() {
897 label : '@', // Action label
898 handler : '=', // Action function handler
901 link : function(scope, element, attrs, egGridCtrl) {
902 egGridCtrl.addAction({
904 divider : scope.divider,
905 handler : scope.handler
912 .factory('egGridColumnsProvider', ['egCore', function(egCore) {
914 function ColumnsProvider(args) {
917 cols.stockVisible = [];
918 cols.idlClass = args.idlClass;
919 cols.defaultToHidden = args.defaultToHidden;
920 cols.defaultToNoSort = args.defaultToNoSort;
921 cols.defaultToNoMultiSort = args.defaultToNoMultiSort;
923 // resets column width, visibility, and sort behavior
924 // Visibility resets to the visibility settings defined in the
925 // template (i.e. the original egGridField values).
926 cols.reset = function() {
927 angular.forEach(cols.columns, function(col) {
930 if (cols.stockVisible.indexOf(col.name) > -1) {
938 // returns true if any columns are sortable
939 cols.hasSortableColumn = function() {
940 return cols.columns.filter(
942 return col.sortable || col.multisortable;
947 cols.showAllColumns = function() {
948 angular.forEach(cols.columns, function(column) {
949 column.visible = true;
953 cols.hideAllColumns = function() {
954 angular.forEach(cols.columns, function(col) {
959 cols.indexOf = function(name) {
960 for (var i = 0; i < cols.columns.length; i++) {
961 if (cols.columns[i].name == name)
967 cols.findColumn = function(name) {
968 return cols.columns[cols.indexOf(name)];
971 cols.compileAutoColumns = function() {
972 var idl_class = egCore.idl.classes[cols.idlClass];
975 idl_class.fields.sort(
976 function(a, b) { return a.name < b.name ? -1 : 1 }),
978 if (field.virtual) return;
979 if (field.datatype == 'link' || field.datatype == 'org_unit') {
980 // if the field is a link and the linked class has a
981 // "selector" field specified, use the selector field
982 // as the display field for the columns.
983 // flattener will take care of the fleshing.
984 if (field['class']) {
985 var selector_field = egCore.idl.classes[field['class']].fields
986 .filter(function(f) { return Boolean(f.selector) })[0];
987 if (selector_field) {
988 field.path = field.name + '.' + selector_field.selector;
992 cols.add(field, true);
997 // if a column definition has a path with a wildcard, create
998 // columns for all non-virtual fields at the specified
999 // position in the path.
1000 cols.expandPath = function(colSpec) {
1002 var ignoreList = [];
1004 ignoreList = colSpec.ignore.split(' ');
1006 var dotpath = colSpec.path.replace(/\.?\*$/,'');
1010 if (colSpec.parentIdlClass) {
1011 class_obj = egCore.idl.classes[colSpec.parentIdlClass];
1013 class_obj = egCore.idl.classes[cols.idlClass];
1016 if (!class_obj) return;
1018 console.debug('egGrid: auto dotpath is: ' + dotpath);
1019 var path_parts = dotpath.split(/\./);
1021 // find the IDL class definition for the last element in the
1022 // path before the .*
1023 // an empty path_parts means expand the root class
1025 for (var path_idx in path_parts) {
1026 var part = path_parts[path_idx];
1027 idl_field = class_obj.field_map[part];
1029 // unless we're at the end of the list, this field should
1030 // link to another class.
1031 if (idl_field && idl_field['class'] && (
1032 idl_field.datatype == 'link' ||
1033 idl_field.datatype == 'org_unit')) {
1034 class_obj = egCore.idl.classes[idl_field['class']];
1036 if (path_idx < (path_parts.length - 1)) {
1037 // we ran out of classes to hop through before
1038 // we ran out of path components
1039 console.error("egGrid: invalid IDL path: " + dotpath);
1046 angular.forEach(class_obj.fields, function(field) {
1048 // Only show wildcard fields where we have data to show
1049 // Virtual and un-fleshed links will not have any data.
1050 if (field.virtual ||
1051 (field.datatype == 'link' || field.datatype == 'org_unit') ||
1052 ignoreList.indexOf(field.name) > -1
1056 var col = cols.cloneFromScope(colSpec);
1057 col.path = dotpath + '.' + field.name;
1058 console.debug('egGrid: field: ' +field.name + '; parent field: ' + js2JSON(idl_field));
1059 cols.add(col, false, true,
1060 {idl_parent : idl_field, idl_field : field, idl_class : class_obj});
1063 cols.columns = cols.columns.sort(
1065 if (a.explicit) return -1;
1066 if (b.explicit) return 1;
1067 if (a.idlclass && b.idlclass) {
1068 return a.idlclass < b.idlclass ? -1 : 1;
1069 return a.idlclass > b.idlclass ? 1 : -1;
1071 if (a.path && b.path) {
1072 return a.path < b.path ? -1 : 1;
1073 return a.path > b.path ? 1 : -1;
1076 return a.label < b.label ? -1 : 1;
1083 "egGrid: wildcard path does not resolve to an object: "
1088 // angular.clone(scopeObject) is not permittable. Manually copy
1089 // the fields over that we need (so the scope object can go away).
1090 cols.cloneFromScope = function(colSpec) {
1092 name : colSpec.name,
1093 label : colSpec.label,
1094 path : colSpec.path,
1095 flex : Number(colSpec.flex) || 2,
1096 sort : Number(colSpec.sort) || 0,
1097 required : colSpec.required,
1098 linkpath : colSpec.linkpath,
1099 template : colSpec.template,
1100 visible : colSpec.visible,
1101 hidden : colSpec.hidden,
1102 datatype : colSpec.datatype,
1103 sortable : colSpec.sortable,
1104 nonsortable : colSpec.nonsortable,
1105 multisortable : colSpec.multisortable,
1106 nonmultisortable : colSpec.nonmultisortable,
1107 dateformat : colSpec.dateformat,
1108 parentIdlClass : colSpec.parentIdlClass
1113 // Add a column to the columns collection.
1114 // Columns may come from a slim eg-columns-field or
1115 // directly from the IDL.
1116 cols.add = function(colSpec, fromIDL, fromExpand, idl_info) {
1118 // First added column with the specified path takes precedence.
1119 // This allows for specific definitions followed by wildcard
1120 // definitions. If a match is found, back out.
1121 if (cols.columns.filter(function(c) {
1122 return (c.path == colSpec.path) })[0]) {
1123 console.debug('skipping pre-existing column ' + colSpec.path);
1127 var column = fromExpand ? colSpec : cols.cloneFromScope(colSpec);
1129 if (column.path && column.path.match(/\*$/))
1130 return cols.expandPath(colSpec);
1132 if (!fromExpand) column.explicit = true;
1134 if (!column.name) column.name = column.path;
1135 if (!column.path) column.path = column.name;
1137 if (column.visible || (!cols.defaultToHidden && !column.hidden))
1138 column.visible = true;
1140 if (column.sortable || (!cols.defaultToNoSort && !column.nonsortable))
1141 column.sortable = true;
1143 if (column.multisortable ||
1144 (!cols.defaultToNoMultiSort && !column.nonmultisortable))
1145 column.multisortable = true;
1147 cols.columns.push(column);
1149 // Track which columns are visible by default in case we
1150 // need to reset column visibility
1152 cols.stockVisible.push(column.name);
1154 if (fromIDL) return; // directly from egIDL. nothing left to do.
1156 // lookup the matching IDL field
1157 if (!idl_info && cols.idlClass)
1158 idl_info = cols.idlFieldFromPath(column.path);
1161 // column is not represented within the IDL
1162 column.adhoc = true;
1166 column.datatype = idl_info.idl_field.datatype;
1168 if (!column.label) {
1169 column.label = idl_info.idl_field.label || column.name;
1172 if (fromExpand && idl_info.idl_class) {
1173 column.idlclass = '';
1174 if (idl_info.idl_parent) {
1175 column.idlclass = idl_info.idl_parent.label || idl_info.idl_parent.name;
1177 column.idlclass += idl_info.idl_class.label || idl_info.idl_class.name;
1182 // finds the IDL field from the dotpath, using the columns
1183 // idlClass as the base.
1184 cols.idlFieldFromPath = function(dotpath) {
1185 var class_obj = egCore.idl.classes[cols.idlClass];
1186 var path_parts = dotpath.split(/\./);
1190 for (var path_idx in path_parts) {
1191 var part = path_parts[path_idx];
1192 idl_parent = idl_field;
1193 idl_field = class_obj.field_map[part];
1195 if (idl_field && idl_field['class'] && (
1196 idl_field.datatype == 'link' ||
1197 idl_field.datatype == 'org_unit')) {
1198 class_obj = egCore.idl.classes[idl_field['class']];
1200 // else, path is not in the IDL, which is fine
1203 if (!idl_field) return null;
1206 idl_parent: idl_parent,
1207 idl_field : idl_field,
1208 idl_class : class_obj
1214 instance : function(args) { return new ColumnsProvider(args) }
1220 * Generic data provider template class. This is basically an abstract
1221 * class factory service whose instances can be locally modified to
1222 * meet the needs of each individual grid.
1224 .factory('egGridDataProvider',
1225 ['$q','$timeout','$filter','egCore',
1226 function($q , $timeout , $filter , egCore) {
1228 function GridDataProvider(args) {
1229 var gridData = this;
1230 if (!args) args = {};
1233 gridData.get = args.get;
1234 gridData.query = args.query;
1235 gridData.idlClass = args.idlClass;
1236 gridData.columnsProvider = args.columnsProvider;
1238 // Delivers a stream of array data via promise.notify()
1239 // Useful for passing an array of data to egGrid.get()
1240 // If a count is provided, the array will be trimmed to
1241 // the range defined by count and offset
1242 gridData.arrayNotifier = function(arr, offset, count) {
1243 if (!arr || arr.length == 0) return $q.when();
1244 if (count) arr = arr.slice(offset, offset + count);
1245 var def = $q.defer();
1246 // promise notifications are only witnessed when delivered
1247 // after the caller has his hands on the promise object
1248 $timeout(function() {
1249 angular.forEach(arr, def.notify);
1255 // Calls the grid refresh function. Once instantiated, the
1256 // grid will replace this function with it's own refresh()
1257 gridData.refresh = function(noReset) { }
1259 if (!gridData.get) {
1260 // returns a promise whose notify() delivers items
1261 gridData.get = function(index, count) {
1262 console.error("egGridDataProvider.get() not implemented");
1266 // attempts a flat field lookup first. If the column is not
1267 // found on the top-level object, attempts a nested lookup
1268 // TODO: consider a caching layer to speed up template
1269 // rendering, particularly for nested objects?
1270 gridData.itemFieldValue = function(item, column) {
1271 if (column.name in item) {
1272 if (typeof item[column.name] == 'function') {
1273 return item[column.name]();
1275 return item[column.name];
1278 return gridData.nestedItemFieldValue(item, column);
1282 // TODO: deprecate me
1283 gridData.flatItemFieldValue = function(item, column) {
1284 console.warn('gridData.flatItemFieldValue deprecated; '
1285 + 'leave provider.itemFieldValue unset');
1286 return item[column.name];
1289 // given an object and a dot-separated path to a field,
1290 // extract the value of the field. The path can refer
1291 // to function names or object attributes. If the final
1292 // value is an IDL field, run the value through its
1293 // corresponding output filter.
1294 gridData.nestedItemFieldValue = function(obj, column) {
1295 if (obj === null || obj === undefined || obj === '') return '';
1296 if (!column.path) return obj;
1299 var parts = column.path.split('.');
1301 angular.forEach(parts, function(step, idx) {
1302 // object is not fleshed to the expected extent
1303 if (!obj || typeof obj != 'object') {
1308 var cls = obj.classname;
1309 if (cls && (class_obj = egCore.idl.classes[cls])) {
1310 idl_field = class_obj.field_map[step];
1311 obj = obj[step] ? obj[step]() : '';
1313 if (angular.isFunction(obj[step])) {
1321 // We found a nested IDL object which may or may not have
1322 // been configured as a top-level column. Grab the datatype.
1323 if (idl_field && !column.datatype)
1324 column.datatype = idl_field.datatype;
1326 if (obj === null || obj === undefined || obj === '') return '';
1332 instance : function(args) {
1333 return new GridDataProvider(args);
1340 // Factory service for egGridDataManager instances, which are
1341 // responsible for collecting flattened grid data.
1342 .factory('egGridFlatDataProvider',
1343 ['$q','egCore','egGridDataProvider',
1344 function($q , egCore , egGridDataProvider) {
1347 instance : function(args) {
1348 var provider = egGridDataProvider.instance(args);
1350 provider.get = function(offset, count) {
1352 // no query means no call
1353 if (!provider.query ||
1354 angular.equals(provider.query, {}))
1357 // find all of the currently visible columns
1358 var queryFields = {}
1359 angular.forEach(provider.columnsProvider.columns,
1361 // only query IDL-tracked columns
1362 if (!col.adhoc && (col.required || col.visible))
1363 queryFields[col.name] = col.path;
1367 return egCore.net.request(
1369 'open-ils.fielder.flattened_search',
1370 egCore.auth.token(), provider.idlClass,
1371 queryFields, provider.query,
1372 { sort : provider.sort,
1378 //provider.itemFieldValue = provider.flatItemFieldValue;
1385 .directive('egGridColumnDragSource', function() {
1388 require : '^egGrid',
1389 link : function(scope, element, attrs, egGridCtrl) {
1390 angular.element(element).attr('draggable', 'true');
1392 element.bind('dragstart', function(e) {
1393 egGridCtrl.dragColumn = attrs.column;
1394 egGridCtrl.dragType = attrs.dragType || 'move'; // or resize
1395 egGridCtrl.colResizeDir = 0;
1397 if (egGridCtrl.dragType == 'move') {
1398 // style the column getting moved
1399 angular.element(e.target).addClass(
1400 'eg-grid-column-move-handle-active');
1404 element.bind('dragend', function(e) {
1405 if (egGridCtrl.dragType == 'move') {
1406 angular.element(e.target).removeClass(
1407 'eg-grid-column-move-handle-active');
1414 .directive('egGridColumnDragDest', function() {
1417 require : '^egGrid',
1418 link : function(scope, element, attrs, egGridCtrl) {
1420 element.bind('dragover', function(e) { // required for drop
1421 e.stopPropagation();
1423 e.dataTransfer.dropEffect = 'move';
1425 if (egGridCtrl.colResizeDir == 0) return; // move
1427 var cols = egGridCtrl.columnsProvider;
1428 var srcCol = egGridCtrl.dragColumn;
1429 var srcColIdx = cols.indexOf(srcCol);
1431 if (egGridCtrl.colResizeDir == -1) {
1432 if (cols.indexOf(attrs.column) <= srcColIdx) {
1433 egGridCtrl.modifyColumnFlex(
1434 egGridCtrl.columnsProvider.findColumn(
1435 egGridCtrl.dragColumn), -1);
1436 if (cols.columns[srcColIdx+1]) {
1437 // source column shrinks by one, column to the
1438 // right grows by one.
1439 egGridCtrl.modifyColumnFlex(
1440 cols.columns[srcColIdx+1], 1);
1445 if (cols.indexOf(attrs.column) > srcColIdx) {
1446 egGridCtrl.modifyColumnFlex(
1447 egGridCtrl.columnsProvider.findColumn(
1448 egGridCtrl.dragColumn), 1);
1449 if (cols.columns[srcColIdx+1]) {
1450 // source column grows by one, column to the
1451 // right grows by one.
1452 egGridCtrl.modifyColumnFlex(
1453 cols.columns[srcColIdx+1], -1);
1461 element.bind('dragenter', function(e) {
1462 e.stopPropagation();
1464 if (egGridCtrl.dragType == 'move') {
1465 angular.element(e.target).addClass('eg-grid-col-hover');
1467 // resize grips are on the right side of each column.
1468 // dragenter will either occur on the source column
1469 // (dragging left) or the column to the right.
1470 if (egGridCtrl.colResizeDir == 0) {
1471 if (egGridCtrl.dragColumn == attrs.column) {
1472 egGridCtrl.colResizeDir = -1; // west
1474 egGridCtrl.colResizeDir = 1; // east
1480 element.bind('dragleave', function(e) {
1481 e.stopPropagation();
1483 if (egGridCtrl.dragType == 'move') {
1484 angular.element(e.target).removeClass('eg-grid-col-hover');
1488 element.bind('drop', function(e) {
1489 e.stopPropagation();
1491 egGridCtrl.colResizeDir = 0;
1492 if (egGridCtrl.dragType == 'move') {
1493 angular.element(e.target).removeClass('eg-grid-col-hover');
1494 egGridCtrl.onColumnDrop(attrs.column); // move the column
1501 .directive('egGridMenuItem', function() {
1504 require : '^egGrid',
1507 handler : '=', // onclick handler function
1508 divider : '=', // if true, show a divider only
1509 handlerData : '=', // if set, passed as second argument to handler
1510 disabled : '=', // function
1511 hidden : '=' // function
1513 link : function(scope, element, attrs, egGridCtrl) {
1514 egGridCtrl.addMenuItem({
1515 label : scope.label,
1516 handler : scope.handler,
1517 divider : scope.divider,
1518 disabled : scope.disabled,
1519 hidden : scope.hidden,
1520 handlerData : scope.handlerData
1530 * Translates bare IDL object values into display values.
1531 * 1. Passes dates through the angular date filter
1532 * 2. Translates bools to Booleans so the browser can display translated
1533 * value. (Though we could manually translate instead..)
1534 * Others likely to follow...
1536 .filter('egGridValueFilter', ['$filter', function($filter) {
1537 return function(value, column) {
1538 switch(column.datatype) {
1541 // Browser will translate true/false for us
1543 case '1' : // legacy
1547 case '0' : // legacy
1550 // value may be null, '', etc.
1551 default : return '';
1554 // canned angular date filter FTW
1555 if (!column.dateformat)
1556 column.dateformat = 'shortDate';
1557 return $filter('date')(value, column.dateformat);
1559 return $filter('currency')(value);