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 // If defined, the grid will watch the return value from
58 // the function defined at watchQuery on each digest and
59 // re-draw the grid when query changes occur.
61 // watchQuery : function() { /* return grid query */ }
64 // These functions are defined by the grid and thus
65 // replace any values defined for these attributes from the
68 // activateItem : function(item) {}
69 // allItems : function(allItems) {}
70 // selectedItems : function(selected) {}
71 // selectItems : function(ids) {}
72 // setQuery : function(queryStruct) {} // causes reload
73 // setSort : function(sortSturct) {} // causes reload
77 // TODO: avoid hard-coded url
78 templateUrl : '/eg/staff/share/t_autogrid',
80 link : function(scope, element, attrs) {
81 // link() is called after page compilation, which means our
82 // eg-grid-field's have been parsed and loaded. Now it's
83 // safe to perform our initial page load.
85 // load auto fields after eg-grid-field's so they are not clobbered
86 scope.handleAutoFields();
89 scope.grid_element = element;
91 .find('.eg-grid-content-body')
92 .bind('contextmenu', scope.showActionContextMenu);
96 '$scope','$q','egCore','egGridFlatDataProvider','$location',
97 'egGridColumnsProvider','$filter','$window','$sce','$timeout',
98 function($scope, $q , egCore, egGridFlatDataProvider , $location,
99 egGridColumnsProvider , $filter , $window , $sce , $timeout) {
103 grid.init = function() {
106 $scope.showGridConf = false;
107 grid.totalCount = -1;
108 $scope.selected = {};
109 $scope.actions = []; // actions for selected items
110 $scope.menuItems = []; // global actions
112 // remove some unneeded values from the scope to reduce bloat
114 grid.idlClass = $scope.idlClass;
115 delete $scope.idlClass;
117 grid.persistKey = $scope.persistKey;
118 delete $scope.persistKey;
120 var stored_limit = 0;
121 if (grid.persistKey) {
122 var stored_limit = Number(
123 egCore.hatch.getLocalItem('eg.grid.' + grid.persistKey + '.limit')
126 grid.limit = Number(stored_limit) || Number($scope.pageSize) || 25;
128 grid.indexField = $scope.idField;
129 delete $scope.idField;
131 grid.dataProvider = $scope.itemsProvider;
133 var features = ($scope.features) ?
134 $scope.features.split(',') : [];
135 delete $scope.features;
137 if (!grid.indexField && grid.idlClass)
138 grid.indexField = egCore.idl.classes[grid.idlClass].pkey;
140 grid.columnsProvider = egGridColumnsProvider.instance({
141 idlClass : grid.idlClass,
142 defaultToHidden : (features.indexOf('-display') > -1),
143 defaultToNoSort : (features.indexOf('-sort') > -1),
144 defaultToNoMultiSort : (features.indexOf('-multisort') > -1)
147 $scope.handleAutoFields = function() {
148 if ($scope.autoFields) {
149 if (grid.autoLabel) {
151 egCore.idl.classes[grid.idlClass].label;
153 grid.columnsProvider.compileAutoColumns();
154 delete $scope.autoFields;
158 if (!grid.dataProvider) {
159 // no provider, um, provided.
160 // Use a flat data provider
162 grid.selfManagedData = true;
163 grid.dataProvider = egGridFlatDataProvider.instance({
164 indexField : grid.indexField,
165 idlClass : grid.idlClass,
166 columnsProvider : grid.columnsProvider,
171 $scope.itemFieldValue = grid.dataProvider.itemFieldValue;
172 $scope.indexValue = function(item) {
173 return grid.indexValue(item)
176 grid.applyControlFunctions();
178 grid.loadConfig().then(function() {
179 // link columns to scope after loadConfig(), since it
180 // replaces the columns array.
181 $scope.columns = grid.columnsProvider.columns;
184 // NOTE: grid.collect() is first called from link(), not here.
187 // link our control functions into the gridControls
188 // scope object so the caller can access them.
189 grid.applyControlFunctions = function() {
191 // we use some of these controls internally, so sett
192 // them up even if the caller doesn't request them.
193 var controls = $scope.gridControls || {};
195 // link in the control functions
196 controls.selectedItems = function() {
197 return grid.getSelectedItems()
200 controls.allItems = function() {
204 controls.selectItems = function(ids) {
206 $scope.selected = {};
207 angular.forEach(ids, function(i) {
208 $scope.selected[''+i] = true;
212 // if the caller provided a functional setQuery,
213 // extract the value before replacing it
214 if (controls.setQuery) {
215 grid.dataProvider.query =
219 controls.setQuery = function(query) {
220 grid.dataProvider.query = query;
224 if (controls.watchQuery) {
225 // capture the initial query value
226 grid.dataProvider.query = controls.watchQuery();
229 $scope.gridWatchQuery = controls.watchQuery;
230 $scope.$watch('gridWatchQuery()', function(newv) {
231 controls.setQuery(newv);
235 // if the caller provided a functional setSort
236 // extract the value before replacing it
237 grid.dataProvider.sort =
238 controls.setSort ? controls.setSort() : [];
240 controls.setSort = function(sort) {
244 controls.refresh = function(noReset) {
245 if (!noReset) grid.offset = 0;
249 controls.setLimit = function(limit,forget) {
250 if (!forget && grid.persistKey)
251 egCore.hatch.setLocalItem('eg.grid.' + grid.persistKey + '.limit', limit);
254 controls.getLimit = function() {
257 controls.setOffset = function(offset) {
258 grid.offset = offset;
260 controls.getOffset = function() {
264 grid.dataProvider.refresh = controls.refresh;
265 grid.controls = controls;
268 // add a new (global) grid menu item
269 grid.addMenuItem = function(item) {
270 $scope.menuItems.push(item);
271 var handler = item.handler;
272 item.handler = function() {
273 $scope.gridMenuIsOpen = false; // close menu
276 item.handlerData, grid.getSelectedItems());
281 // add a selected-items action
282 grid.addAction = function(act) {
283 $scope.actions.push(act);
286 // remove the stored column configuration preferenc, then recover
287 // the column visibility information from the initial page load.
288 $scope.resetColumns = function() {
289 $scope.gridColumnPickerIsOpen = false;
290 egCore.hatch.removeItem('eg.grid.' + grid.persistKey)
292 grid.columnsProvider.reset();
293 if (grid.selfManagedData) grid.collect();
297 $scope.showAllColumns = function() {
298 $scope.gridColumnPickerIsOpen = false;
299 grid.columnsProvider.showAllColumns();
300 if (grid.selfManagedData) grid.collect();
303 $scope.hideAllColumns = function() {
304 $scope.gridColumnPickerIsOpen = false;
305 grid.columnsProvider.hideAllColumns();
306 // note: no need to fetch new data if no columns are visible
309 $scope.toggleColumnVisibility = function(col) {
310 $scope.gridColumnPickerIsOpen = false;
311 col.visible = !col.visible;
313 // egGridFlatDataProvider only retrieves data to be
314 // displayed. When column visibility changes, it's
315 // necessary to fetch the newly visible column data.
316 if (grid.selfManagedData) grid.collect();
319 // save the columns configuration (position, sort, width) to
320 // eg.grid.<persist-key>
321 $scope.saveConfig = function() {
322 $scope.gridColumnPickerIsOpen = false;
324 if (!grid.persistKey) {
326 "Cannot save settings without a grid persist-key");
330 // only store information about visible columns.
331 var conf = grid.columnsProvider.columns.filter(
332 function(col) {return Boolean(col.visible) });
334 // now scrunch the data down to just the needed info
335 conf = conf.map(function(col) {
336 var c = {name : col.name}
337 // Apart from the name, only store non-default values.
338 // No need to store col.visible, since that's implicit
339 if (col.flex != 2) c.flex = col.flex;
340 if (Number(col.sort)) c.sort = Number(c.sort);
344 egCore.hatch.setItem('eg.grid.' + grid.persistKey, conf)
346 // Save operation performed from the grid configuration UI.
347 // Hide the configuration UI and re-draw w/ sort applied
348 if ($scope.showGridConf)
349 $scope.toggleConfDisplay();
353 // load the columns configuration (position, sort, width) from
354 // eg.grid.<persist-key> and apply the loaded settings to the
355 // columns on our columnsProvider
356 grid.loadConfig = function() {
357 if (!grid.persistKey) return $q.when();
359 return egCore.hatch.getItem('eg.grid.' + grid.persistKey)
360 .then(function(conf) {
363 var columns = grid.columnsProvider.columns;
366 angular.forEach(conf, function(col) {
367 var grid_col = columns.filter(
368 function(c) {return c.name == col.name})[0];
371 // saved column does not match a column in the
372 // current grid. skip it.
376 grid_col.flex = col.flex || 2;
377 grid_col.sort = col.sort || 0;
378 // all saved columns are assumed to be true
379 grid_col.visible = true;
380 new_cols.push(grid_col);
383 // columns which are not expressed within the saved
384 // configuration are marked as non-visible and
385 // appended to the end of the new list of columns.
386 angular.forEach(columns, function(col) {
387 var found = conf.filter(
388 function(c) {return (c.name == col.name)})[0];
395 grid.columnsProvider.columns = new_cols;
400 $scope.onContextMenu = function($event) {
401 var col = angular.element($event.target).attr('column');
402 console.log('selected column ' + col);
405 $scope.page = function() {
406 return (grid.offset / grid.limit) + 1;
409 $scope.goToPage = function(page) {
411 if (angular.isNumber(page) && page > 0) {
412 grid.offset = (page - 1) * grid.limit;
417 $scope.offset = function(o) {
418 if (angular.isNumber(o))
423 $scope.limit = function(l) {
424 if (angular.isNumber(l)) {
426 egCore.hatch.setLocalItem('eg.grid.' + grid.persistKey + '.limit', l);
432 $scope.onFirstPage = function() {
433 return grid.offset == 0;
436 $scope.hasNextPage = function() {
437 // we have less data than requested, there must
438 // not be any more pages
439 if (grid.count() < grid.limit) return false;
441 // if the total count is not known, assume that a full
442 // page of data implies more pages are available.
443 if (grid.totalCount == -1) return true;
445 // we have a full page of data, but is there more?
446 return grid.totalCount > (grid.offset + grid.count());
449 $scope.incrementPage = function() {
450 grid.offset += grid.limit;
454 $scope.decrementPage = function() {
455 if (grid.offset < grid.limit) {
458 grid.offset -= grid.limit;
463 // number of items loaded for the current page of results
464 grid.count = function() {
465 return $scope.items.length;
468 // returns the unique identifier value for the provided item
469 // for internal consistency, indexValue is always coerced
471 grid.indexValue = function(item) {
472 if (angular.isObject(item)) {
474 if (angular.isFunction(item[grid.indexField]))
475 return ''+item[grid.indexField]();
476 return ''+item[grid.indexField]; // flat data
479 // passed a non-object; assume it's an index
483 // fires the hide handler function for a context action
484 $scope.actionHide = function(action) {
488 return action.hide(action);
491 // fires the action handler function for a context action
492 $scope.actionLauncher = function(action) {
493 if (!action.handler) {
495 'No handler specified for "' + action.label + '"');
499 action.handler(grid.getSelectedItems());
501 console.error('Error executing handler for "'
502 + action.label + '" => ' + E + "\n" + E.stack);
505 if ($scope.action_context_showing) $scope.hideActionContextMenu();
510 $scope.hideActionContextMenu = function () {
511 $($scope.menu_dom).css({
513 width: $scope.action_context_width,
514 top: $scope.action_context_y,
515 left: $scope.action_context_x
517 $($scope.action_context_parent).append($scope.menu_dom);
518 $scope.action_context_oldy = $scope.action_context_oldx = 0;
519 $('body').unbind('click.remove_context_menu_'+$scope.action_context_index);
520 $scope.action_context_showing = false;
523 $scope.action_context_showing = false;
524 $scope.showActionContextMenu = function ($event) {
526 // Have to gather these here, instead of inside link()
527 if (!$scope.menu_dom) $scope.menu_dom = $($scope.grid_element).find('.grid-action-dropdown')[0];
528 if (!$scope.action_context_parent) $scope.action_context_parent = $($scope.menu_dom).parent();
530 if (!grid.getSelectedItems().length) // Nothing selected, fire the click event
531 $event.target.click();
533 if (!$scope.action_context_showing) {
534 $scope.action_context_width = $($scope.menu_dom).css('width');
535 $scope.action_context_y = $($scope.menu_dom).css('top');
536 $scope.action_context_x = $($scope.menu_dom).css('left');
537 $scope.action_context_showing = true;
538 $scope.action_context_index = Math.floor((Math.random() * 1000) + 1);
540 $('body').append($($scope.menu_dom));
541 $('body').bind('click.remove_context_menu_'+$scope.action_context_index, $scope.hideActionContextMenu);
544 $($scope.menu_dom).css({
546 width: $scope.action_context_width,
554 // returns the list of selected item objects
555 grid.getSelectedItems = function() {
556 return $scope.items.filter(
558 return Boolean($scope.selected[grid.indexValue(item)]);
563 grid.getItemByIndex = function(index) {
564 for (var i = 0; i < $scope.items.length; i++) {
565 var item = $scope.items[i];
566 if (grid.indexValue(item) == index)
571 // selects one row after deselecting all of the others
572 grid.selectOneItem = function(index) {
573 $scope.selected = {};
574 $scope.selected[index] = true;
577 // selects or deselects an item, without affecting the others.
578 // returns true if the item is selected; false if de-selected.
579 grid.toggleSelectOneItem = function(index) {
580 if ($scope.selected[index]) {
581 delete $scope.selected[index];
584 return $scope.selected[index] = true;
588 grid.selectAllItems = function() {
589 angular.forEach($scope.items, function(item) {
590 $scope.selected[grid.indexValue(item)] = true
594 $scope.$watch('selectAll', function(newVal) {
596 grid.selectAllItems();
598 $scope.selected = {};
602 // returns true if item1 appears in the list before item2;
603 // false otherwise. this is slightly more efficient that
604 // finding the position of each then comparing them.
605 // item1 / item2 may be an item or an item index
606 grid.itemComesBefore = function(itemOrIndex1, itemOrIndex2) {
607 var idx1 = grid.indexValue(itemOrIndex1);
608 var idx2 = grid.indexValue(itemOrIndex2);
610 // use for() for early exit
611 for (var i = 0; i < $scope.items.length; i++) {
612 var idx = grid.indexValue($scope.items[i]);
613 if (idx == idx1) return true;
614 if (idx == idx2) return false;
619 // 0-based position of item in the current data set
620 grid.indexOf = function(item) {
621 var idx = grid.indexValue(item);
622 for (var i = 0; i < $scope.items.length; i++) {
623 if (grid.indexValue($scope.items[i]) == idx)
629 grid.modifyColumnFlex = function(column, val) {
631 // prevent flex:0; use hiding instead
635 $scope.modifyColumnFlex = function(col, val) {
636 grid.modifyColumnFlex(col, val);
639 // handles click, control-click, and shift-click
640 $scope.handleRowClick = function($event, item) {
641 var index = grid.indexValue(item);
643 var origSelected = Object.keys($scope.selected);
645 if ($event.ctrlKey || $event.metaKey /* mac command */) {
647 if (grid.toggleSelectOneItem(index))
648 grid.lastSelectedItemIndex = index;
650 } else if ($event.shiftKey) {
653 if (!grid.lastSelectedItemIndex ||
654 index == grid.lastSelectedItemIndex) {
655 grid.selectOneItem(index);
656 grid.lastSelectedItemIndex = index;
660 var selecting = false;
661 var ascending = grid.itemComesBefore(
662 grid.lastSelectedItemIndex, item);
664 grid.indexOf(grid.lastSelectedItemIndex);
666 // update to new last-selected
667 grid.lastSelectedItemIndex = index;
669 // select each row between the last selected and
670 // currently selected items
672 startPos += ascending ? 1 : -1;
673 var curItem = $scope.items[startPos];
675 var curIdx = grid.indexValue(curItem);
676 $scope.selected[curIdx] = true;
677 if (curIdx == index) break; // all done
682 grid.selectOneItem(index);
683 grid.lastSelectedItemIndex = index;
687 // Builds a sort expression from column sort priorities.
688 // called on page load and any time the priorities are modified.
689 grid.compileSort = function() {
690 var sortList = grid.columnsProvider.columns.filter(
691 function(col) { return Number(col.sort) != 0 }
694 if (Math.abs(a.sort) < Math.abs(b.sort))
700 if (sortList.length) {
701 grid.dataProvider.sort = sortList.map(function(col) {
703 blob[col.name] = col.sort < 0 ? 'desc' : 'asc';
709 // builds a sort expression using a single column,
710 // toggling between ascending and descending sort.
711 $scope.quickSort = function(col_name) {
712 var sort = grid.dataProvider.sort;
713 if (sort && sort.length &&
714 sort[0] == col_name) {
716 blob[col_name] = 'desc';
717 grid.dataProvider.sort = [blob];
719 grid.dataProvider.sort = [col_name];
726 // show / hide the grid configuration row
727 $scope.toggleConfDisplay = function() {
728 if ($scope.showGridConf) {
729 $scope.showGridConf = false;
730 if (grid.columnsProvider.hasSortableColumn()) {
731 // only refresh the grid if the user has the
732 // ability to modify the sort priorities.
738 $scope.showGridConf = true;
741 $scope.gridColumnPickerIsOpen = false;
744 // called when a dragged column is dropped onto itself
745 // or any other column
746 grid.onColumnDrop = function(target) {
747 if (angular.isUndefined(target)) return;
748 if (target == grid.dragColumn) return;
749 var srcIdx, targetIdx, srcCol;
750 angular.forEach(grid.columnsProvider.columns,
752 if (col.name == grid.dragColumn) {
755 } else if (col.name == target) {
761 if (srcIdx < targetIdx) targetIdx--;
763 // move src column from old location to new location in
764 // the columns array, then force a page refresh
765 grid.columnsProvider.columns.splice(srcIdx, 1);
766 grid.columnsProvider.columns.splice(targetIdx, 0, srcCol);
770 // prepares a string for inclusion within a CSV document
771 // by escaping commas and quotes and removing newlines.
772 grid.csvDatum = function(str) {
775 str = str.replace(/\n/g, '');
776 if (str.match(/\,/) || str.match(/"/)) {
777 str = str.replace(/"/g, '""');
778 str = '"' + str + '"';
783 // sets the download file name and inserts the current CSV
784 // into a Blob URL for browser download.
785 $scope.generateCSVExportURL = function() {
786 $scope.gridColumnPickerIsOpen = false;
788 // let the file name describe the grid
789 $scope.csvExportFileName =
790 ($scope.mainLabel || grid.persistKey || 'eg_grid_data')
791 .replace(/\s+/g, '_') + '_' + $scope.page();
793 // toss the CSV into a Blob and update the export URL
794 var csv = grid.generateCSV();
795 var blob = new Blob([csv], {type : 'text/plain'});
796 $scope.csvExportURL =
797 ($window.URL || $window.webkitURL).createObjectURL(blob);
800 $scope.printCSV = function() {
801 $scope.gridColumnPickerIsOpen = false;
804 content : grid.generateCSV(),
805 content_type : 'text/plain'
809 // generates CSV for the currently visible grid contents
810 grid.generateCSV = function() {
812 var colCount = grid.columnsProvider.columns.length;
815 angular.forEach(grid.columnsProvider.columns,
817 if (!col.visible) return;
818 csvStr += grid.csvDatum(col.label);
823 csvStr = csvStr.replace(/,$/,'\n');
826 angular.forEach($scope.items, function(item) {
827 angular.forEach(grid.columnsProvider.columns,
829 if (!col.visible) return;
831 var val = grid.dataProvider.itemFieldValue(item, col);
832 // filtered value (dates, etc.)
833 val = $filter('egGridValueFilter')(val, col);
834 csvStr += grid.csvDatum(val);
838 csvStr = csvStr.replace(/,$/,'\n');
844 // Interpolate the value for column.linkpath within the context
845 // of the row item to generate the final link URL.
846 $scope.generateLinkPath = function(col, item) {
847 return egCore.strings.$replace(col.linkpath, {item : item});
850 // If a column provides its own HTML template, translate it,
851 // using the current item for the template scope.
852 // note: $sce is required to avoid security restrictions and
853 // is OK here, since the template comes directly from a
854 // local HTML template (not user input).
855 $scope.translateCellTemplate = function(col, item) {
856 var html = egCore.strings.$replace(col.template, {item : item});
857 return $sce.trustAsHtml(html);
860 $scope.collect = function() { grid.collect() }
862 // asks the dataProvider for a page of data
863 grid.collect = function() {
865 // avoid firing the collect if there is nothing to collect.
866 if (grid.selfManagedData && !grid.dataProvider.query) return;
868 if (grid.collecting) return; // avoid parallel collect()
869 grid.collecting = true;
871 console.debug('egGrid.collect() offset='
872 + grid.offset + '; limit=' + grid.limit);
874 // ensure all of our dropdowns are closed
875 // TODO: git rid of these and just use dropdown-toggle,
876 // which is more reliable.
877 $scope.gridColumnPickerIsOpen = false;
878 $scope.gridRowCountIsOpen = false;
879 $scope.gridPageSelectIsOpen = false;
882 $scope.selected = {};
883 grid.dataProvider.get(grid.offset, grid.limit).then(
885 if (grid.controls.allItemsRetrieved)
886 grid.controls.allItemsRetrieved();
891 $scope.items.push(item)
892 if (grid.controls.itemRetrieved)
893 grid.controls.itemRetrieved(item);
895 }).finally(function() {
896 console.debug('egGrid.collect() complete');
897 grid.collecting = false
907 * eg-grid-field : used for collecting custom field data from the templates.
908 * This directive does not direct display, it just passes data up to the
911 .directive('egGridField', function() {
916 name : '@', // required; unique name
917 path : '@', // optional; flesh path
918 ignore: '@', // optional; fields to ignore when path is a wildcard
919 label : '@', // optional; display label
920 flex : '@', // optional; default flex width
921 dateformat : '@', // optional: passed down to egGridValueFilter
923 // if a field is part of an IDL object, but we are unable to
924 // determine the class, because it's nested within a hash
925 // (i.e. we can't navigate directly to the object via the IDL),
926 // idlClass lets us specify the class. This is particularly
927 // useful for nested wildcard fields.
928 parentIdlClass : '@',
930 // optional: for non-IDL columns, specifying a datatype
931 // lets the caller control which display filter is used.
932 // datatype should match the standard IDL datatypes.
935 link : function(scope, element, attrs, egGridCtrl) {
937 // boolean fields are presented as value-less attributes
946 'required' // if set, always fetch data for this column
949 if (angular.isDefined(attrs[field]))
954 // any HTML content within the field is its custom template
955 var tmpl = element.html();
956 if (tmpl && !tmpl.match(/^\s*$/))
957 scope.template = tmpl
959 egGridCtrl.columnsProvider.add(scope);
966 * eg-grid-action : used for specifying actions which may be applied
967 * to items within the grid.
969 .directive('egGridAction', function() {
975 label : '@', // Action label
976 handler : '=', // Action function handler
980 link : function(scope, element, attrs, egGridCtrl) {
981 egGridCtrl.addAction({
984 divider : scope.divider,
985 handler : scope.handler
992 .factory('egGridColumnsProvider', ['egCore', function(egCore) {
994 function ColumnsProvider(args) {
997 cols.stockVisible = [];
998 cols.idlClass = args.idlClass;
999 cols.defaultToHidden = args.defaultToHidden;
1000 cols.defaultToNoSort = args.defaultToNoSort;
1001 cols.defaultToNoMultiSort = args.defaultToNoMultiSort;
1003 // resets column width, visibility, and sort behavior
1004 // Visibility resets to the visibility settings defined in the
1005 // template (i.e. the original egGridField values).
1006 cols.reset = function() {
1007 angular.forEach(cols.columns, function(col) {
1010 if (cols.stockVisible.indexOf(col.name) > -1) {
1013 col.visible = false;
1018 // returns true if any columns are sortable
1019 cols.hasSortableColumn = function() {
1020 return cols.columns.filter(
1022 return col.sortable || col.multisortable;
1027 cols.showAllColumns = function() {
1028 angular.forEach(cols.columns, function(column) {
1029 column.visible = true;
1033 cols.hideAllColumns = function() {
1034 angular.forEach(cols.columns, function(col) {
1039 cols.indexOf = function(name) {
1040 for (var i = 0; i < cols.columns.length; i++) {
1041 if (cols.columns[i].name == name)
1047 cols.findColumn = function(name) {
1048 return cols.columns[cols.indexOf(name)];
1051 cols.compileAutoColumns = function() {
1052 var idl_class = egCore.idl.classes[cols.idlClass];
1055 idl_class.fields.sort(
1056 function(a, b) { return a.name < b.name ? -1 : 1 }),
1058 if (field.virtual) return;
1059 if (field.datatype == 'link' || field.datatype == 'org_unit') {
1060 // if the field is a link and the linked class has a
1061 // "selector" field specified, use the selector field
1062 // as the display field for the columns.
1063 // flattener will take care of the fleshing.
1064 if (field['class']) {
1065 var selector_field = egCore.idl.classes[field['class']].fields
1066 .filter(function(f) { return Boolean(f.selector) })[0];
1067 if (selector_field) {
1068 field.path = field.name + '.' + selector_field.selector;
1072 cols.add(field, true);
1077 // if a column definition has a path with a wildcard, create
1078 // columns for all non-virtual fields at the specified
1079 // position in the path.
1080 cols.expandPath = function(colSpec) {
1082 var ignoreList = [];
1084 ignoreList = colSpec.ignore.split(' ');
1086 var dotpath = colSpec.path.replace(/\.?\*$/,'');
1090 if (colSpec.parentIdlClass) {
1091 class_obj = egCore.idl.classes[colSpec.parentIdlClass];
1093 class_obj = egCore.idl.classes[cols.idlClass];
1096 if (!class_obj) return;
1098 console.debug('egGrid: auto dotpath is: ' + dotpath);
1099 var path_parts = dotpath.split(/\./);
1101 // find the IDL class definition for the last element in the
1102 // path before the .*
1103 // an empty path_parts means expand the root class
1105 for (var path_idx in path_parts) {
1106 var part = path_parts[path_idx];
1107 idl_field = class_obj.field_map[part];
1109 // unless we're at the end of the list, this field should
1110 // link to another class.
1111 if (idl_field && idl_field['class'] && (
1112 idl_field.datatype == 'link' ||
1113 idl_field.datatype == 'org_unit')) {
1114 class_obj = egCore.idl.classes[idl_field['class']];
1116 if (path_idx < (path_parts.length - 1)) {
1117 // we ran out of classes to hop through before
1118 // we ran out of path components
1119 console.error("egGrid: invalid IDL path: " + dotpath);
1126 angular.forEach(class_obj.fields, function(field) {
1128 // Only show wildcard fields where we have data to show
1129 // Virtual and un-fleshed links will not have any data.
1130 if (field.virtual ||
1131 (field.datatype == 'link' || field.datatype == 'org_unit') ||
1132 ignoreList.indexOf(field.name) > -1
1136 var col = cols.cloneFromScope(colSpec);
1137 col.path = dotpath + '.' + field.name;
1138 console.debug('egGrid: field: ' +field.name + '; parent field: ' + js2JSON(idl_field));
1139 cols.add(col, false, true,
1140 {idl_parent : idl_field, idl_field : field, idl_class : class_obj});
1143 cols.columns = cols.columns.sort(
1145 if (a.explicit) return -1;
1146 if (b.explicit) return 1;
1147 if (a.idlclass && b.idlclass) {
1148 return a.idlclass < b.idlclass ? -1 : 1;
1149 return a.idlclass > b.idlclass ? 1 : -1;
1151 if (a.path && b.path) {
1152 return a.path < b.path ? -1 : 1;
1153 return a.path > b.path ? 1 : -1;
1156 return a.label < b.label ? -1 : 1;
1163 "egGrid: wildcard path does not resolve to an object: "
1168 // angular.clone(scopeObject) is not permittable. Manually copy
1169 // the fields over that we need (so the scope object can go away).
1170 cols.cloneFromScope = function(colSpec) {
1172 name : colSpec.name,
1173 label : colSpec.label,
1174 path : colSpec.path,
1175 flex : Number(colSpec.flex) || 2,
1176 sort : Number(colSpec.sort) || 0,
1177 required : colSpec.required,
1178 linkpath : colSpec.linkpath,
1179 template : colSpec.template,
1180 visible : colSpec.visible,
1181 hidden : colSpec.hidden,
1182 datatype : colSpec.datatype,
1183 sortable : colSpec.sortable,
1184 nonsortable : colSpec.nonsortable,
1185 multisortable : colSpec.multisortable,
1186 nonmultisortable : colSpec.nonmultisortable,
1187 dateformat : colSpec.dateformat,
1188 parentIdlClass : colSpec.parentIdlClass
1193 // Add a column to the columns collection.
1194 // Columns may come from a slim eg-columns-field or
1195 // directly from the IDL.
1196 cols.add = function(colSpec, fromIDL, fromExpand, idl_info) {
1198 // First added column with the specified path takes precedence.
1199 // This allows for specific definitions followed by wildcard
1200 // definitions. If a match is found, back out.
1201 if (cols.columns.filter(function(c) {
1202 return (c.path == colSpec.path) })[0]) {
1203 console.debug('skipping pre-existing column ' + colSpec.path);
1207 var column = fromExpand ? colSpec : cols.cloneFromScope(colSpec);
1209 if (column.path && column.path.match(/\*$/))
1210 return cols.expandPath(colSpec);
1212 if (!fromExpand) column.explicit = true;
1214 if (!column.name) column.name = column.path;
1215 if (!column.path) column.path = column.name;
1217 if (column.visible || (!cols.defaultToHidden && !column.hidden))
1218 column.visible = true;
1220 if (column.sortable || (!cols.defaultToNoSort && !column.nonsortable))
1221 column.sortable = true;
1223 if (column.multisortable ||
1224 (!cols.defaultToNoMultiSort && !column.nonmultisortable))
1225 column.multisortable = true;
1227 cols.columns.push(column);
1229 // Track which columns are visible by default in case we
1230 // need to reset column visibility
1232 cols.stockVisible.push(column.name);
1234 if (fromIDL) return; // directly from egIDL. nothing left to do.
1236 // lookup the matching IDL field
1237 if (!idl_info && cols.idlClass)
1238 idl_info = cols.idlFieldFromPath(column.path);
1241 // column is not represented within the IDL
1242 column.adhoc = true;
1246 column.datatype = idl_info.idl_field.datatype;
1248 if (!column.label) {
1249 column.label = idl_info.idl_field.label || column.name;
1252 if (fromExpand && idl_info.idl_class) {
1253 column.idlclass = '';
1254 if (idl_info.idl_parent) {
1255 column.idlclass = idl_info.idl_parent.label || idl_info.idl_parent.name;
1257 column.idlclass += idl_info.idl_class.label || idl_info.idl_class.name;
1262 // finds the IDL field from the dotpath, using the columns
1263 // idlClass as the base.
1264 cols.idlFieldFromPath = function(dotpath) {
1265 var class_obj = egCore.idl.classes[cols.idlClass];
1266 var path_parts = dotpath.split(/\./);
1270 for (var path_idx in path_parts) {
1271 var part = path_parts[path_idx];
1272 idl_parent = idl_field;
1273 idl_field = class_obj.field_map[part];
1275 if (idl_field && idl_field['class'] && (
1276 idl_field.datatype == 'link' ||
1277 idl_field.datatype == 'org_unit')) {
1278 class_obj = egCore.idl.classes[idl_field['class']];
1280 // else, path is not in the IDL, which is fine
1283 if (!idl_field) return null;
1286 idl_parent: idl_parent,
1287 idl_field : idl_field,
1288 idl_class : class_obj
1294 instance : function(args) { return new ColumnsProvider(args) }
1300 * Generic data provider template class. This is basically an abstract
1301 * class factory service whose instances can be locally modified to
1302 * meet the needs of each individual grid.
1304 .factory('egGridDataProvider',
1305 ['$q','$timeout','$filter','egCore',
1306 function($q , $timeout , $filter , egCore) {
1308 function GridDataProvider(args) {
1309 var gridData = this;
1310 if (!args) args = {};
1313 gridData.get = args.get;
1314 gridData.query = args.query;
1315 gridData.idlClass = args.idlClass;
1316 gridData.columnsProvider = args.columnsProvider;
1318 // Delivers a stream of array data via promise.notify()
1319 // Useful for passing an array of data to egGrid.get()
1320 // If a count is provided, the array will be trimmed to
1321 // the range defined by count and offset
1322 gridData.arrayNotifier = function(arr, offset, count) {
1323 if (!arr || arr.length == 0) return $q.when();
1324 if (count) arr = arr.slice(offset, offset + count);
1325 var def = $q.defer();
1326 // promise notifications are only witnessed when delivered
1327 // after the caller has his hands on the promise object
1328 $timeout(function() {
1329 angular.forEach(arr, def.notify);
1335 // Calls the grid refresh function. Once instantiated, the
1336 // grid will replace this function with it's own refresh()
1337 gridData.refresh = function(noReset) { }
1339 if (!gridData.get) {
1340 // returns a promise whose notify() delivers items
1341 gridData.get = function(index, count) {
1342 console.error("egGridDataProvider.get() not implemented");
1346 // attempts a flat field lookup first. If the column is not
1347 // found on the top-level object, attempts a nested lookup
1348 // TODO: consider a caching layer to speed up template
1349 // rendering, particularly for nested objects?
1350 gridData.itemFieldValue = function(item, column) {
1351 if (column.name in item) {
1352 if (typeof item[column.name] == 'function') {
1353 return item[column.name]();
1355 return item[column.name];
1358 return gridData.nestedItemFieldValue(item, column);
1362 // TODO: deprecate me
1363 gridData.flatItemFieldValue = function(item, column) {
1364 console.warn('gridData.flatItemFieldValue deprecated; '
1365 + 'leave provider.itemFieldValue unset');
1366 return item[column.name];
1369 // given an object and a dot-separated path to a field,
1370 // extract the value of the field. The path can refer
1371 // to function names or object attributes. If the final
1372 // value is an IDL field, run the value through its
1373 // corresponding output filter.
1374 gridData.nestedItemFieldValue = function(obj, column) {
1375 if (obj === null || obj === undefined || obj === '') return '';
1376 if (!column.path) return obj;
1379 var parts = column.path.split('.');
1381 angular.forEach(parts, function(step, idx) {
1382 // object is not fleshed to the expected extent
1383 if (!obj || typeof obj != 'object') {
1388 var cls = obj.classname;
1389 if (cls && (class_obj = egCore.idl.classes[cls])) {
1390 idl_field = class_obj.field_map[step];
1391 obj = obj[step] ? obj[step]() : '';
1393 if (angular.isFunction(obj[step])) {
1401 // We found a nested IDL object which may or may not have
1402 // been configured as a top-level column. Grab the datatype.
1403 if (idl_field && !column.datatype)
1404 column.datatype = idl_field.datatype;
1406 if (obj === null || obj === undefined || obj === '') return '';
1412 instance : function(args) {
1413 return new GridDataProvider(args);
1420 // Factory service for egGridDataManager instances, which are
1421 // responsible for collecting flattened grid data.
1422 .factory('egGridFlatDataProvider',
1423 ['$q','egCore','egGridDataProvider',
1424 function($q , egCore , egGridDataProvider) {
1427 instance : function(args) {
1428 var provider = egGridDataProvider.instance(args);
1430 provider.get = function(offset, count) {
1432 // no query means no call
1433 if (!provider.query ||
1434 angular.equals(provider.query, {}))
1437 // find all of the currently visible columns
1438 var queryFields = {}
1439 angular.forEach(provider.columnsProvider.columns,
1441 // only query IDL-tracked columns
1442 if (!col.adhoc && (col.required || col.visible))
1443 queryFields[col.name] = col.path;
1447 return egCore.net.request(
1449 'open-ils.fielder.flattened_search',
1450 egCore.auth.token(), provider.idlClass,
1451 queryFields, provider.query,
1452 { sort : provider.sort,
1458 //provider.itemFieldValue = provider.flatItemFieldValue;
1465 .directive('egGridColumnDragSource', function() {
1468 require : '^egGrid',
1469 link : function(scope, element, attrs, egGridCtrl) {
1470 angular.element(element).attr('draggable', 'true');
1472 element.bind('dragstart', function(e) {
1473 egGridCtrl.dragColumn = attrs.column;
1474 egGridCtrl.dragType = attrs.dragType || 'move'; // or resize
1475 egGridCtrl.colResizeDir = 0;
1477 if (egGridCtrl.dragType == 'move') {
1478 // style the column getting moved
1479 angular.element(e.target).addClass(
1480 'eg-grid-column-move-handle-active');
1484 element.bind('dragend', function(e) {
1485 if (egGridCtrl.dragType == 'move') {
1486 angular.element(e.target).removeClass(
1487 'eg-grid-column-move-handle-active');
1494 .directive('egGridColumnDragDest', function() {
1497 require : '^egGrid',
1498 link : function(scope, element, attrs, egGridCtrl) {
1500 element.bind('dragover', function(e) { // required for drop
1501 e.stopPropagation();
1503 e.dataTransfer.dropEffect = 'move';
1505 if (egGridCtrl.colResizeDir == 0) return; // move
1507 var cols = egGridCtrl.columnsProvider;
1508 var srcCol = egGridCtrl.dragColumn;
1509 var srcColIdx = cols.indexOf(srcCol);
1511 if (egGridCtrl.colResizeDir == -1) {
1512 if (cols.indexOf(attrs.column) <= srcColIdx) {
1513 egGridCtrl.modifyColumnFlex(
1514 egGridCtrl.columnsProvider.findColumn(
1515 egGridCtrl.dragColumn), -1);
1516 if (cols.columns[srcColIdx+1]) {
1517 // source column shrinks by one, column to the
1518 // right grows by one.
1519 egGridCtrl.modifyColumnFlex(
1520 cols.columns[srcColIdx+1], 1);
1525 if (cols.indexOf(attrs.column) > srcColIdx) {
1526 egGridCtrl.modifyColumnFlex(
1527 egGridCtrl.columnsProvider.findColumn(
1528 egGridCtrl.dragColumn), 1);
1529 if (cols.columns[srcColIdx+1]) {
1530 // source column grows by one, column to the
1531 // right grows by one.
1532 egGridCtrl.modifyColumnFlex(
1533 cols.columns[srcColIdx+1], -1);
1541 element.bind('dragenter', function(e) {
1542 e.stopPropagation();
1544 if (egGridCtrl.dragType == 'move') {
1545 angular.element(e.target).addClass('eg-grid-col-hover');
1547 // resize grips are on the right side of each column.
1548 // dragenter will either occur on the source column
1549 // (dragging left) or the column to the right.
1550 if (egGridCtrl.colResizeDir == 0) {
1551 if (egGridCtrl.dragColumn == attrs.column) {
1552 egGridCtrl.colResizeDir = -1; // west
1554 egGridCtrl.colResizeDir = 1; // east
1560 element.bind('dragleave', function(e) {
1561 e.stopPropagation();
1563 if (egGridCtrl.dragType == 'move') {
1564 angular.element(e.target).removeClass('eg-grid-col-hover');
1568 element.bind('drop', function(e) {
1569 e.stopPropagation();
1571 egGridCtrl.colResizeDir = 0;
1572 if (egGridCtrl.dragType == 'move') {
1573 angular.element(e.target).removeClass('eg-grid-col-hover');
1574 egGridCtrl.onColumnDrop(attrs.column); // move the column
1581 .directive('egGridMenuItem', function() {
1584 require : '^egGrid',
1587 handler : '=', // onclick handler function
1588 divider : '=', // if true, show a divider only
1589 handlerData : '=', // if set, passed as second argument to handler
1590 disabled : '=', // function
1591 hidden : '=' // function
1593 link : function(scope, element, attrs, egGridCtrl) {
1594 egGridCtrl.addMenuItem({
1595 label : scope.label,
1596 handler : scope.handler,
1597 divider : scope.divider,
1598 disabled : scope.disabled,
1599 hidden : scope.hidden,
1600 handlerData : scope.handlerData
1610 * Translates bare IDL object values into display values.
1611 * 1. Passes dates through the angular date filter
1612 * 2. Translates bools to Booleans so the browser can display translated
1613 * value. (Though we could manually translate instead..)
1614 * Others likely to follow...
1616 .filter('egGridValueFilter', ['$filter', function($filter) {
1617 return function(value, column) {
1618 switch(column.datatype) {
1621 // Browser will translate true/false for us
1623 case '1' : // legacy
1627 case '0' : // legacy
1630 // value may be null, '', etc.
1631 default : return '';
1634 // canned angular date filter FTW
1635 if (!column.dateformat)
1636 column.dateformat = 'shortDate';
1637 return $filter('date')(value, column.dateformat);
1639 return $filter('currency')(value);