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,forget) {
227 if (!forget && grid.persistKey)
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 hide handler function for a context action
461 $scope.actionHide = function(action) {
465 return action.hide(action);
468 // fires the action handler function for a context action
469 $scope.actionLauncher = function(action) {
470 if (!action.handler) {
472 'No handler specified for "' + action.label + '"');
477 action.handler(grid.getSelectedItems());
479 console.error('Error executing handler for "'
480 + action.label + '" => ' + E + "\n" + E.stack);
484 // returns the list of selected item objects
485 grid.getSelectedItems = function() {
486 return $scope.items.filter(
488 return Boolean($scope.selected[grid.indexValue(item)]);
493 grid.getItemByIndex = function(index) {
494 for (var i = 0; i < $scope.items.length; i++) {
495 var item = $scope.items[i];
496 if (grid.indexValue(item) == index)
501 // selects one row after deselecting all of the others
502 grid.selectOneItem = function(index) {
503 $scope.selected = {};
504 $scope.selected[index] = true;
507 // selects or deselects an item, without affecting the others.
508 // returns true if the item is selected; false if de-selected.
509 grid.toggleSelectOneItem = function(index) {
510 if ($scope.selected[index]) {
511 delete $scope.selected[index];
514 return $scope.selected[index] = true;
518 grid.selectAllItems = function() {
519 angular.forEach($scope.items, function(item) {
520 $scope.selected[grid.indexValue(item)] = true
524 $scope.$watch('selectAll', function(newVal) {
526 grid.selectAllItems();
528 $scope.selected = {};
532 // returns true if item1 appears in the list before item2;
533 // false otherwise. this is slightly more efficient that
534 // finding the position of each then comparing them.
535 // item1 / item2 may be an item or an item index
536 grid.itemComesBefore = function(itemOrIndex1, itemOrIndex2) {
537 var idx1 = grid.indexValue(itemOrIndex1);
538 var idx2 = grid.indexValue(itemOrIndex2);
540 // use for() for early exit
541 for (var i = 0; i < $scope.items.length; i++) {
542 var idx = grid.indexValue($scope.items[i]);
543 if (idx == idx1) return true;
544 if (idx == idx2) return false;
549 // 0-based position of item in the current data set
550 grid.indexOf = function(item) {
551 var idx = grid.indexValue(item);
552 for (var i = 0; i < $scope.items.length; i++) {
553 if (grid.indexValue($scope.items[i]) == idx)
559 grid.modifyColumnFlex = function(column, val) {
561 // prevent flex:0; use hiding instead
565 $scope.modifyColumnFlex = function(col, val) {
566 grid.modifyColumnFlex(col, val);
569 // handles click, control-click, and shift-click
570 $scope.handleRowClick = function($event, item) {
571 var index = grid.indexValue(item);
573 var origSelected = Object.keys($scope.selected);
575 if ($event.ctrlKey || $event.metaKey /* mac command */) {
577 if (grid.toggleSelectOneItem(index))
578 grid.lastSelectedItemIndex = index;
580 } else if ($event.shiftKey) {
583 if (!grid.lastSelectedItemIndex ||
584 index == grid.lastSelectedItemIndex) {
585 grid.selectOneItem(index);
586 grid.lastSelectedItemIndex = index;
590 var selecting = false;
591 var ascending = grid.itemComesBefore(
592 grid.lastSelectedItemIndex, item);
594 grid.indexOf(grid.lastSelectedItemIndex);
596 // update to new last-selected
597 grid.lastSelectedItemIndex = index;
599 // select each row between the last selected and
600 // currently selected items
602 startPos += ascending ? 1 : -1;
603 var curItem = $scope.items[startPos];
605 var curIdx = grid.indexValue(curItem);
606 $scope.selected[curIdx] = true;
607 if (curIdx == index) break; // all done
612 grid.selectOneItem(index);
613 grid.lastSelectedItemIndex = index;
617 // Builds a sort expression from column sort priorities.
618 // called on page load and any time the priorities are modified.
619 grid.compileSort = function() {
620 var sortList = grid.columnsProvider.columns.filter(
621 function(col) { return Number(col.sort) != 0 }
624 if (Math.abs(a.sort) < Math.abs(b.sort))
630 if (sortList.length) {
631 grid.dataProvider.sort = sortList.map(function(col) {
633 blob[col.name] = col.sort < 0 ? 'desc' : 'asc';
639 // builds a sort expression using a single column,
640 // toggling between ascending and descending sort.
641 $scope.quickSort = function(col_name) {
642 var sort = grid.dataProvider.sort;
643 if (sort && sort.length &&
644 sort[0] == col_name) {
646 blob[col_name] = 'desc';
647 grid.dataProvider.sort = [blob];
649 grid.dataProvider.sort = [col_name];
656 // show / hide the grid configuration row
657 $scope.toggleConfDisplay = function() {
658 if ($scope.showGridConf) {
659 $scope.showGridConf = false;
660 if (grid.columnsProvider.hasSortableColumn()) {
661 // only refresh the grid if the user has the
662 // ability to modify the sort priorities.
668 $scope.showGridConf = true;
671 $scope.gridColumnPickerIsOpen = false;
674 // called when a dragged column is dropped onto itself
675 // or any other column
676 grid.onColumnDrop = function(target) {
677 if (angular.isUndefined(target)) return;
678 if (target == grid.dragColumn) return;
679 var srcIdx, targetIdx, srcCol;
680 angular.forEach(grid.columnsProvider.columns,
682 if (col.name == grid.dragColumn) {
685 } else if (col.name == target) {
691 if (srcIdx < targetIdx) targetIdx--;
693 // move src column from old location to new location in
694 // the columns array, then force a page refresh
695 grid.columnsProvider.columns.splice(srcIdx, 1);
696 grid.columnsProvider.columns.splice(targetIdx, 0, srcCol);
700 // prepares a string for inclusion within a CSV document
701 // by escaping commas and quotes and removing newlines.
702 grid.csvDatum = function(str) {
705 str = str.replace(/\n/g, '');
706 if (str.match(/\,/) || str.match(/"/)) {
707 str = str.replace(/"/g, '""');
708 str = '"' + str + '"';
713 // sets the download file name and inserts the current CSV
714 // into a Blob URL for browser download.
715 $scope.generateCSVExportURL = function() {
716 $scope.gridColumnPickerIsOpen = false;
718 // let the file name describe the grid
719 $scope.csvExportFileName =
720 ($scope.mainLabel || grid.persistKey || 'eg_grid_data')
721 .replace(/\s+/g, '_') + '_' + $scope.page();
723 // toss the CSV into a Blob and update the export URL
724 var csv = grid.generateCSV();
725 var blob = new Blob([csv], {type : 'text/plain'});
726 $scope.csvExportURL =
727 ($window.URL || $window.webkitURL).createObjectURL(blob);
730 $scope.printCSV = function() {
731 $scope.gridColumnPickerIsOpen = false;
734 content : grid.generateCSV(),
735 content_type : 'text/plain'
739 // generates CSV for the currently visible grid contents
740 grid.generateCSV = function() {
742 var colCount = grid.columnsProvider.columns.length;
745 angular.forEach(grid.columnsProvider.columns,
747 if (!col.visible) return;
748 csvStr += grid.csvDatum(col.label);
753 csvStr = csvStr.replace(/,$/,'\n');
756 angular.forEach($scope.items, function(item) {
757 angular.forEach(grid.columnsProvider.columns,
759 if (!col.visible) return;
761 var val = grid.dataProvider.itemFieldValue(item, col);
762 // filtered value (dates, etc.)
763 val = $filter('egGridValueFilter')(val, col);
764 csvStr += grid.csvDatum(val);
768 csvStr = csvStr.replace(/,$/,'\n');
774 // Interpolate the value for column.linkpath within the context
775 // of the row item to generate the final link URL.
776 $scope.generateLinkPath = function(col, item) {
777 return egCore.strings.$replace(col.linkpath, {item : item});
780 // If a column provides its own HTML template, translate it,
781 // using the current item for the template scope.
782 // note: $sce is required to avoid security restrictions and
783 // is OK here, since the template comes directly from a
784 // local HTML template (not user input).
785 $scope.translateCellTemplate = function(col, item) {
786 var html = egCore.strings.$replace(col.template, {item : item});
787 return $sce.trustAsHtml(html);
790 $scope.collect = function() { grid.collect() }
792 // asks the dataProvider for a page of data
793 grid.collect = function() {
795 // avoid firing the collect if there is nothing to collect.
796 if (grid.selfManagedData && !grid.dataProvider.query) return;
798 if (grid.collecting) return; // avoid parallel collect()
799 grid.collecting = true;
801 console.debug('egGrid.collect() offset='
802 + grid.offset + '; limit=' + grid.limit);
804 // ensure all of our dropdowns are closed
805 // TODO: git rid of these and just use dropdown-toggle,
806 // which is more reliable.
807 $scope.gridColumnPickerIsOpen = false;
808 $scope.gridRowCountIsOpen = false;
809 $scope.gridPageSelectIsOpen = false;
812 $scope.selected = {};
813 grid.dataProvider.get(grid.offset, grid.limit).then(
815 if (grid.controls.allItemsRetrieved)
816 grid.controls.allItemsRetrieved();
821 $scope.items.push(item)
822 if (grid.controls.itemRetrieved)
823 grid.controls.itemRetrieved(item);
825 }).finally(function() {
826 console.debug('egGrid.collect() complete');
827 grid.collecting = false
837 * eg-grid-field : used for collecting custom field data from the templates.
838 * This directive does not direct display, it just passes data up to the
841 .directive('egGridField', function() {
846 name : '@', // required; unique name
847 path : '@', // optional; flesh path
848 ignore: '@', // optional; fields to ignore when path is a wildcard
849 label : '@', // optional; display label
850 flex : '@', // optional; default flex width
851 dateformat : '@', // optional: passed down to egGridValueFilter
853 // if a field is part of an IDL object, but we are unable to
854 // determine the class, because it's nested within a hash
855 // (i.e. we can't navigate directly to the object via the IDL),
856 // idlClass lets us specify the class. This is particularly
857 // useful for nested wildcard fields.
858 parentIdlClass : '@',
860 // optional: for non-IDL columns, specifying a datatype
861 // lets the caller control which display filter is used.
862 // datatype should match the standard IDL datatypes.
865 link : function(scope, element, attrs, egGridCtrl) {
867 // boolean fields are presented as value-less attributes
876 'required' // if set, always fetch data for this column
879 if (angular.isDefined(attrs[field]))
884 // any HTML content within the field is its custom template
885 var tmpl = element.html();
886 if (tmpl && !tmpl.match(/^\s*$/))
887 scope.template = tmpl
889 egGridCtrl.columnsProvider.add(scope);
896 * eg-grid-action : used for specifying actions which may be applied
897 * to items within the grid.
899 .directive('egGridAction', function() {
905 label : '@', // Action label
906 handler : '=', // Action function handler
910 link : function(scope, element, attrs, egGridCtrl) {
911 egGridCtrl.addAction({
914 divider : scope.divider,
915 handler : scope.handler
922 .factory('egGridColumnsProvider', ['egCore', function(egCore) {
924 function ColumnsProvider(args) {
927 cols.stockVisible = [];
928 cols.idlClass = args.idlClass;
929 cols.defaultToHidden = args.defaultToHidden;
930 cols.defaultToNoSort = args.defaultToNoSort;
931 cols.defaultToNoMultiSort = args.defaultToNoMultiSort;
933 // resets column width, visibility, and sort behavior
934 // Visibility resets to the visibility settings defined in the
935 // template (i.e. the original egGridField values).
936 cols.reset = function() {
937 angular.forEach(cols.columns, function(col) {
940 if (cols.stockVisible.indexOf(col.name) > -1) {
948 // returns true if any columns are sortable
949 cols.hasSortableColumn = function() {
950 return cols.columns.filter(
952 return col.sortable || col.multisortable;
957 cols.showAllColumns = function() {
958 angular.forEach(cols.columns, function(column) {
959 column.visible = true;
963 cols.hideAllColumns = function() {
964 angular.forEach(cols.columns, function(col) {
969 cols.indexOf = function(name) {
970 for (var i = 0; i < cols.columns.length; i++) {
971 if (cols.columns[i].name == name)
977 cols.findColumn = function(name) {
978 return cols.columns[cols.indexOf(name)];
981 cols.compileAutoColumns = function() {
982 var idl_class = egCore.idl.classes[cols.idlClass];
985 idl_class.fields.sort(
986 function(a, b) { return a.name < b.name ? -1 : 1 }),
988 if (field.virtual) return;
989 if (field.datatype == 'link' || field.datatype == 'org_unit') {
990 // if the field is a link and the linked class has a
991 // "selector" field specified, use the selector field
992 // as the display field for the columns.
993 // flattener will take care of the fleshing.
994 if (field['class']) {
995 var selector_field = egCore.idl.classes[field['class']].fields
996 .filter(function(f) { return Boolean(f.selector) })[0];
997 if (selector_field) {
998 field.path = field.name + '.' + selector_field.selector;
1002 cols.add(field, true);
1007 // if a column definition has a path with a wildcard, create
1008 // columns for all non-virtual fields at the specified
1009 // position in the path.
1010 cols.expandPath = function(colSpec) {
1012 var ignoreList = [];
1014 ignoreList = colSpec.ignore.split(' ');
1016 var dotpath = colSpec.path.replace(/\.?\*$/,'');
1020 if (colSpec.parentIdlClass) {
1021 class_obj = egCore.idl.classes[colSpec.parentIdlClass];
1023 class_obj = egCore.idl.classes[cols.idlClass];
1026 if (!class_obj) return;
1028 console.debug('egGrid: auto dotpath is: ' + dotpath);
1029 var path_parts = dotpath.split(/\./);
1031 // find the IDL class definition for the last element in the
1032 // path before the .*
1033 // an empty path_parts means expand the root class
1035 for (var path_idx in path_parts) {
1036 var part = path_parts[path_idx];
1037 idl_field = class_obj.field_map[part];
1039 // unless we're at the end of the list, this field should
1040 // link to another class.
1041 if (idl_field && idl_field['class'] && (
1042 idl_field.datatype == 'link' ||
1043 idl_field.datatype == 'org_unit')) {
1044 class_obj = egCore.idl.classes[idl_field['class']];
1046 if (path_idx < (path_parts.length - 1)) {
1047 // we ran out of classes to hop through before
1048 // we ran out of path components
1049 console.error("egGrid: invalid IDL path: " + dotpath);
1056 angular.forEach(class_obj.fields, function(field) {
1058 // Only show wildcard fields where we have data to show
1059 // Virtual and un-fleshed links will not have any data.
1060 if (field.virtual ||
1061 (field.datatype == 'link' || field.datatype == 'org_unit') ||
1062 ignoreList.indexOf(field.name) > -1
1066 var col = cols.cloneFromScope(colSpec);
1067 col.path = dotpath + '.' + field.name;
1068 console.debug('egGrid: field: ' +field.name + '; parent field: ' + js2JSON(idl_field));
1069 cols.add(col, false, true,
1070 {idl_parent : idl_field, idl_field : field, idl_class : class_obj});
1073 cols.columns = cols.columns.sort(
1075 if (a.explicit) return -1;
1076 if (b.explicit) return 1;
1077 if (a.idlclass && b.idlclass) {
1078 return a.idlclass < b.idlclass ? -1 : 1;
1079 return a.idlclass > b.idlclass ? 1 : -1;
1081 if (a.path && b.path) {
1082 return a.path < b.path ? -1 : 1;
1083 return a.path > b.path ? 1 : -1;
1086 return a.label < b.label ? -1 : 1;
1093 "egGrid: wildcard path does not resolve to an object: "
1098 // angular.clone(scopeObject) is not permittable. Manually copy
1099 // the fields over that we need (so the scope object can go away).
1100 cols.cloneFromScope = function(colSpec) {
1102 name : colSpec.name,
1103 label : colSpec.label,
1104 path : colSpec.path,
1105 flex : Number(colSpec.flex) || 2,
1106 sort : Number(colSpec.sort) || 0,
1107 required : colSpec.required,
1108 linkpath : colSpec.linkpath,
1109 template : colSpec.template,
1110 visible : colSpec.visible,
1111 hidden : colSpec.hidden,
1112 datatype : colSpec.datatype,
1113 sortable : colSpec.sortable,
1114 nonsortable : colSpec.nonsortable,
1115 multisortable : colSpec.multisortable,
1116 nonmultisortable : colSpec.nonmultisortable,
1117 dateformat : colSpec.dateformat,
1118 parentIdlClass : colSpec.parentIdlClass
1123 // Add a column to the columns collection.
1124 // Columns may come from a slim eg-columns-field or
1125 // directly from the IDL.
1126 cols.add = function(colSpec, fromIDL, fromExpand, idl_info) {
1128 // First added column with the specified path takes precedence.
1129 // This allows for specific definitions followed by wildcard
1130 // definitions. If a match is found, back out.
1131 if (cols.columns.filter(function(c) {
1132 return (c.path == colSpec.path) })[0]) {
1133 console.debug('skipping pre-existing column ' + colSpec.path);
1137 var column = fromExpand ? colSpec : cols.cloneFromScope(colSpec);
1139 if (column.path && column.path.match(/\*$/))
1140 return cols.expandPath(colSpec);
1142 if (!fromExpand) column.explicit = true;
1144 if (!column.name) column.name = column.path;
1145 if (!column.path) column.path = column.name;
1147 if (column.visible || (!cols.defaultToHidden && !column.hidden))
1148 column.visible = true;
1150 if (column.sortable || (!cols.defaultToNoSort && !column.nonsortable))
1151 column.sortable = true;
1153 if (column.multisortable ||
1154 (!cols.defaultToNoMultiSort && !column.nonmultisortable))
1155 column.multisortable = true;
1157 cols.columns.push(column);
1159 // Track which columns are visible by default in case we
1160 // need to reset column visibility
1162 cols.stockVisible.push(column.name);
1164 if (fromIDL) return; // directly from egIDL. nothing left to do.
1166 // lookup the matching IDL field
1167 if (!idl_info && cols.idlClass)
1168 idl_info = cols.idlFieldFromPath(column.path);
1171 // column is not represented within the IDL
1172 column.adhoc = true;
1176 column.datatype = idl_info.idl_field.datatype;
1178 if (!column.label) {
1179 column.label = idl_info.idl_field.label || column.name;
1182 if (fromExpand && idl_info.idl_class) {
1183 column.idlclass = '';
1184 if (idl_info.idl_parent) {
1185 column.idlclass = idl_info.idl_parent.label || idl_info.idl_parent.name;
1187 column.idlclass += idl_info.idl_class.label || idl_info.idl_class.name;
1192 // finds the IDL field from the dotpath, using the columns
1193 // idlClass as the base.
1194 cols.idlFieldFromPath = function(dotpath) {
1195 var class_obj = egCore.idl.classes[cols.idlClass];
1196 var path_parts = dotpath.split(/\./);
1200 for (var path_idx in path_parts) {
1201 var part = path_parts[path_idx];
1202 idl_parent = idl_field;
1203 idl_field = class_obj.field_map[part];
1205 if (idl_field && idl_field['class'] && (
1206 idl_field.datatype == 'link' ||
1207 idl_field.datatype == 'org_unit')) {
1208 class_obj = egCore.idl.classes[idl_field['class']];
1210 // else, path is not in the IDL, which is fine
1213 if (!idl_field) return null;
1216 idl_parent: idl_parent,
1217 idl_field : idl_field,
1218 idl_class : class_obj
1224 instance : function(args) { return new ColumnsProvider(args) }
1230 * Generic data provider template class. This is basically an abstract
1231 * class factory service whose instances can be locally modified to
1232 * meet the needs of each individual grid.
1234 .factory('egGridDataProvider',
1235 ['$q','$timeout','$filter','egCore',
1236 function($q , $timeout , $filter , egCore) {
1238 function GridDataProvider(args) {
1239 var gridData = this;
1240 if (!args) args = {};
1243 gridData.get = args.get;
1244 gridData.query = args.query;
1245 gridData.idlClass = args.idlClass;
1246 gridData.columnsProvider = args.columnsProvider;
1248 // Delivers a stream of array data via promise.notify()
1249 // Useful for passing an array of data to egGrid.get()
1250 // If a count is provided, the array will be trimmed to
1251 // the range defined by count and offset
1252 gridData.arrayNotifier = function(arr, offset, count) {
1253 if (!arr || arr.length == 0) return $q.when();
1254 if (count) arr = arr.slice(offset, offset + count);
1255 var def = $q.defer();
1256 // promise notifications are only witnessed when delivered
1257 // after the caller has his hands on the promise object
1258 $timeout(function() {
1259 angular.forEach(arr, def.notify);
1265 // Calls the grid refresh function. Once instantiated, the
1266 // grid will replace this function with it's own refresh()
1267 gridData.refresh = function(noReset) { }
1269 if (!gridData.get) {
1270 // returns a promise whose notify() delivers items
1271 gridData.get = function(index, count) {
1272 console.error("egGridDataProvider.get() not implemented");
1276 // attempts a flat field lookup first. If the column is not
1277 // found on the top-level object, attempts a nested lookup
1278 // TODO: consider a caching layer to speed up template
1279 // rendering, particularly for nested objects?
1280 gridData.itemFieldValue = function(item, column) {
1281 if (column.name in item) {
1282 if (typeof item[column.name] == 'function') {
1283 return item[column.name]();
1285 return item[column.name];
1288 return gridData.nestedItemFieldValue(item, column);
1292 // TODO: deprecate me
1293 gridData.flatItemFieldValue = function(item, column) {
1294 console.warn('gridData.flatItemFieldValue deprecated; '
1295 + 'leave provider.itemFieldValue unset');
1296 return item[column.name];
1299 // given an object and a dot-separated path to a field,
1300 // extract the value of the field. The path can refer
1301 // to function names or object attributes. If the final
1302 // value is an IDL field, run the value through its
1303 // corresponding output filter.
1304 gridData.nestedItemFieldValue = function(obj, column) {
1305 if (obj === null || obj === undefined || obj === '') return '';
1306 if (!column.path) return obj;
1309 var parts = column.path.split('.');
1311 angular.forEach(parts, function(step, idx) {
1312 // object is not fleshed to the expected extent
1313 if (!obj || typeof obj != 'object') {
1318 var cls = obj.classname;
1319 if (cls && (class_obj = egCore.idl.classes[cls])) {
1320 idl_field = class_obj.field_map[step];
1321 obj = obj[step] ? obj[step]() : '';
1323 if (angular.isFunction(obj[step])) {
1331 // We found a nested IDL object which may or may not have
1332 // been configured as a top-level column. Grab the datatype.
1333 if (idl_field && !column.datatype)
1334 column.datatype = idl_field.datatype;
1336 if (obj === null || obj === undefined || obj === '') return '';
1342 instance : function(args) {
1343 return new GridDataProvider(args);
1350 // Factory service for egGridDataManager instances, which are
1351 // responsible for collecting flattened grid data.
1352 .factory('egGridFlatDataProvider',
1353 ['$q','egCore','egGridDataProvider',
1354 function($q , egCore , egGridDataProvider) {
1357 instance : function(args) {
1358 var provider = egGridDataProvider.instance(args);
1360 provider.get = function(offset, count) {
1362 // no query means no call
1363 if (!provider.query ||
1364 angular.equals(provider.query, {}))
1367 // find all of the currently visible columns
1368 var queryFields = {}
1369 angular.forEach(provider.columnsProvider.columns,
1371 // only query IDL-tracked columns
1372 if (!col.adhoc && (col.required || col.visible))
1373 queryFields[col.name] = col.path;
1377 return egCore.net.request(
1379 'open-ils.fielder.flattened_search',
1380 egCore.auth.token(), provider.idlClass,
1381 queryFields, provider.query,
1382 { sort : provider.sort,
1388 //provider.itemFieldValue = provider.flatItemFieldValue;
1395 .directive('egGridColumnDragSource', function() {
1398 require : '^egGrid',
1399 link : function(scope, element, attrs, egGridCtrl) {
1400 angular.element(element).attr('draggable', 'true');
1402 element.bind('dragstart', function(e) {
1403 egGridCtrl.dragColumn = attrs.column;
1404 egGridCtrl.dragType = attrs.dragType || 'move'; // or resize
1405 egGridCtrl.colResizeDir = 0;
1407 if (egGridCtrl.dragType == 'move') {
1408 // style the column getting moved
1409 angular.element(e.target).addClass(
1410 'eg-grid-column-move-handle-active');
1414 element.bind('dragend', function(e) {
1415 if (egGridCtrl.dragType == 'move') {
1416 angular.element(e.target).removeClass(
1417 'eg-grid-column-move-handle-active');
1424 .directive('egGridColumnDragDest', function() {
1427 require : '^egGrid',
1428 link : function(scope, element, attrs, egGridCtrl) {
1430 element.bind('dragover', function(e) { // required for drop
1431 e.stopPropagation();
1433 e.dataTransfer.dropEffect = 'move';
1435 if (egGridCtrl.colResizeDir == 0) return; // move
1437 var cols = egGridCtrl.columnsProvider;
1438 var srcCol = egGridCtrl.dragColumn;
1439 var srcColIdx = cols.indexOf(srcCol);
1441 if (egGridCtrl.colResizeDir == -1) {
1442 if (cols.indexOf(attrs.column) <= srcColIdx) {
1443 egGridCtrl.modifyColumnFlex(
1444 egGridCtrl.columnsProvider.findColumn(
1445 egGridCtrl.dragColumn), -1);
1446 if (cols.columns[srcColIdx+1]) {
1447 // source column shrinks by one, column to the
1448 // right grows by one.
1449 egGridCtrl.modifyColumnFlex(
1450 cols.columns[srcColIdx+1], 1);
1455 if (cols.indexOf(attrs.column) > srcColIdx) {
1456 egGridCtrl.modifyColumnFlex(
1457 egGridCtrl.columnsProvider.findColumn(
1458 egGridCtrl.dragColumn), 1);
1459 if (cols.columns[srcColIdx+1]) {
1460 // source column grows by one, column to the
1461 // right grows by one.
1462 egGridCtrl.modifyColumnFlex(
1463 cols.columns[srcColIdx+1], -1);
1471 element.bind('dragenter', function(e) {
1472 e.stopPropagation();
1474 if (egGridCtrl.dragType == 'move') {
1475 angular.element(e.target).addClass('eg-grid-col-hover');
1477 // resize grips are on the right side of each column.
1478 // dragenter will either occur on the source column
1479 // (dragging left) or the column to the right.
1480 if (egGridCtrl.colResizeDir == 0) {
1481 if (egGridCtrl.dragColumn == attrs.column) {
1482 egGridCtrl.colResizeDir = -1; // west
1484 egGridCtrl.colResizeDir = 1; // east
1490 element.bind('dragleave', function(e) {
1491 e.stopPropagation();
1493 if (egGridCtrl.dragType == 'move') {
1494 angular.element(e.target).removeClass('eg-grid-col-hover');
1498 element.bind('drop', function(e) {
1499 e.stopPropagation();
1501 egGridCtrl.colResizeDir = 0;
1502 if (egGridCtrl.dragType == 'move') {
1503 angular.element(e.target).removeClass('eg-grid-col-hover');
1504 egGridCtrl.onColumnDrop(attrs.column); // move the column
1511 .directive('egGridMenuItem', function() {
1514 require : '^egGrid',
1517 handler : '=', // onclick handler function
1518 divider : '=', // if true, show a divider only
1519 handlerData : '=', // if set, passed as second argument to handler
1520 disabled : '=', // function
1521 hidden : '=' // function
1523 link : function(scope, element, attrs, egGridCtrl) {
1524 egGridCtrl.addMenuItem({
1525 label : scope.label,
1526 handler : scope.handler,
1527 divider : scope.divider,
1528 disabled : scope.disabled,
1529 hidden : scope.hidden,
1530 handlerData : scope.handlerData
1540 * Translates bare IDL object values into display values.
1541 * 1. Passes dates through the angular date filter
1542 * 2. Translates bools to Booleans so the browser can display translated
1543 * value. (Though we could manually translate instead..)
1544 * Others likely to follow...
1546 .filter('egGridValueFilter', ['$filter', function($filter) {
1547 return function(value, column) {
1548 switch(column.datatype) {
1551 // Browser will translate true/false for us
1553 case '1' : // legacy
1557 case '0' : // legacy
1560 // value may be null, '', etc.
1561 default : return '';
1564 // canned angular date filter FTW
1565 if (!column.dateformat)
1566 column.dateformat = 'shortDate';
1567 return $filter('date')(value, column.dateformat);
1569 return $filter('currency')(value);