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.actionGroups = [{actions:[]}]; // Grouped 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) {
284 $scope.actionGroups.forEach(function(g){
285 if (g.label === act.group) {
291 $scope.actionGroups.push({
298 // remove the stored column configuration preferenc, then recover
299 // the column visibility information from the initial page load.
300 $scope.resetColumns = function() {
301 $scope.gridColumnPickerIsOpen = false;
302 egCore.hatch.removeItem('eg.grid.' + grid.persistKey)
304 grid.columnsProvider.reset();
305 if (grid.selfManagedData) grid.collect();
309 $scope.showAllColumns = function() {
310 $scope.gridColumnPickerIsOpen = false;
311 grid.columnsProvider.showAllColumns();
312 if (grid.selfManagedData) grid.collect();
315 $scope.hideAllColumns = function() {
316 $scope.gridColumnPickerIsOpen = false;
317 grid.columnsProvider.hideAllColumns();
318 // note: no need to fetch new data if no columns are visible
321 $scope.toggleColumnVisibility = function(col) {
322 $scope.gridColumnPickerIsOpen = false;
323 col.visible = !col.visible;
325 // egGridFlatDataProvider only retrieves data to be
326 // displayed. When column visibility changes, it's
327 // necessary to fetch the newly visible column data.
328 if (grid.selfManagedData) grid.collect();
331 // save the columns configuration (position, sort, width) to
332 // eg.grid.<persist-key>
333 $scope.saveConfig = function() {
334 $scope.gridColumnPickerIsOpen = false;
336 if (!grid.persistKey) {
338 "Cannot save settings without a grid persist-key");
342 // only store information about visible columns.
343 var conf = grid.columnsProvider.columns.filter(
344 function(col) {return Boolean(col.visible) });
346 // now scrunch the data down to just the needed info
347 conf = conf.map(function(col) {
348 var c = {name : col.name}
349 // Apart from the name, only store non-default values.
350 // No need to store col.visible, since that's implicit
351 if (col.align != 'left') c.align = col.align;
352 if (col.flex != 2) c.flex = col.flex;
353 if (Number(col.sort)) c.sort = Number(c.sort);
357 egCore.hatch.setItem('eg.grid.' + grid.persistKey, conf)
359 // Save operation performed from the grid configuration UI.
360 // Hide the configuration UI and re-draw w/ sort applied
361 if ($scope.showGridConf)
362 $scope.toggleConfDisplay();
366 // load the columns configuration (position, sort, width) from
367 // eg.grid.<persist-key> and apply the loaded settings to the
368 // columns on our columnsProvider
369 grid.loadConfig = function() {
370 if (!grid.persistKey) return $q.when();
372 return egCore.hatch.getItem('eg.grid.' + grid.persistKey)
373 .then(function(conf) {
376 var columns = grid.columnsProvider.columns;
379 angular.forEach(conf, function(col) {
380 var grid_col = columns.filter(
381 function(c) {return c.name == col.name})[0];
384 // saved column does not match a column in the
385 // current grid. skip it.
389 grid_col.align = col.align || 'left';
390 grid_col.flex = col.flex || 2;
391 grid_col.sort = col.sort || 0;
392 // all saved columns are assumed to be true
393 grid_col.visible = true;
394 new_cols.push(grid_col);
397 // columns which are not expressed within the saved
398 // configuration are marked as non-visible and
399 // appended to the end of the new list of columns.
400 angular.forEach(columns, function(col) {
401 var found = conf.filter(
402 function(c) {return (c.name == col.name)})[0];
409 grid.columnsProvider.columns = new_cols;
414 $scope.onContextMenu = function($event) {
415 var col = angular.element($event.target).attr('column');
416 console.log('selected column ' + col);
419 $scope.page = function() {
420 return (grid.offset / grid.limit) + 1;
423 $scope.goToPage = function(page) {
425 if (angular.isNumber(page) && page > 0) {
426 grid.offset = (page - 1) * grid.limit;
431 $scope.offset = function(o) {
432 if (angular.isNumber(o))
437 $scope.limit = function(l) {
438 if (angular.isNumber(l)) {
440 egCore.hatch.setLocalItem('eg.grid.' + grid.persistKey + '.limit', l);
446 $scope.onFirstPage = function() {
447 return grid.offset == 0;
450 $scope.hasNextPage = function() {
451 // we have less data than requested, there must
452 // not be any more pages
453 if (grid.count() < grid.limit) return false;
455 // if the total count is not known, assume that a full
456 // page of data implies more pages are available.
457 if (grid.totalCount == -1) return true;
459 // we have a full page of data, but is there more?
460 return grid.totalCount > (grid.offset + grid.count());
463 $scope.incrementPage = function() {
464 grid.offset += grid.limit;
468 $scope.decrementPage = function() {
469 if (grid.offset < grid.limit) {
472 grid.offset -= grid.limit;
477 // number of items loaded for the current page of results
478 grid.count = function() {
479 return $scope.items.length;
482 // returns the unique identifier value for the provided item
483 // for internal consistency, indexValue is always coerced
485 grid.indexValue = function(item) {
486 if (angular.isObject(item)) {
488 if (angular.isFunction(item[grid.indexField]))
489 return ''+item[grid.indexField]();
490 return ''+item[grid.indexField]; // flat data
493 // passed a non-object; assume it's an index
497 // fires the hide handler function for a context action
498 $scope.actionHide = function(action) {
502 return action.hide(action);
505 // fires the action handler function for a context action
506 $scope.actionLauncher = function(action) {
507 if (!action.handler) {
509 'No handler specified for "' + action.label + '"');
513 action.handler(grid.getSelectedItems());
515 console.error('Error executing handler for "'
516 + action.label + '" => ' + E + "\n" + E.stack);
519 if ($scope.action_context_showing) $scope.hideActionContextMenu();
524 $scope.hideActionContextMenu = function () {
525 $($scope.menu_dom).css({
527 width: $scope.action_context_width,
528 top: $scope.action_context_y,
529 left: $scope.action_context_x
531 $($scope.action_context_parent).append($scope.menu_dom);
532 $scope.action_context_oldy = $scope.action_context_oldx = 0;
533 $('body').unbind('click.remove_context_menu_'+$scope.action_context_index);
534 $scope.action_context_showing = false;
537 $scope.action_context_showing = false;
538 $scope.showActionContextMenu = function ($event) {
540 // Have to gather these here, instead of inside link()
541 if (!$scope.menu_dom) $scope.menu_dom = $($scope.grid_element).find('.grid-action-dropdown')[0];
542 if (!$scope.action_context_parent) $scope.action_context_parent = $($scope.menu_dom).parent();
544 if (!grid.getSelectedItems().length) // Nothing selected, fire the click event
545 $event.target.click();
547 if (!$scope.action_context_showing) {
548 $scope.action_context_width = $($scope.menu_dom).css('width');
549 $scope.action_context_y = $($scope.menu_dom).css('top');
550 $scope.action_context_x = $($scope.menu_dom).css('left');
551 $scope.action_context_showing = true;
552 $scope.action_context_index = Math.floor((Math.random() * 1000) + 1);
554 $('body').append($($scope.menu_dom));
555 $('body').bind('click.remove_context_menu_'+$scope.action_context_index, $scope.hideActionContextMenu);
558 $($scope.menu_dom).css({
560 width: $scope.action_context_width,
568 // returns the list of selected item objects
569 grid.getSelectedItems = function() {
570 return $scope.items.filter(
572 return Boolean($scope.selected[grid.indexValue(item)]);
577 grid.getItemByIndex = function(index) {
578 for (var i = 0; i < $scope.items.length; i++) {
579 var item = $scope.items[i];
580 if (grid.indexValue(item) == index)
585 // selects one row after deselecting all of the others
586 grid.selectOneItem = function(index) {
587 $scope.selected = {};
588 $scope.selected[index] = true;
591 // selects or deselects an item, without affecting the others.
592 // returns true if the item is selected; false if de-selected.
593 grid.toggleSelectOneItem = function(index) {
594 if ($scope.selected[index]) {
595 delete $scope.selected[index];
598 return $scope.selected[index] = true;
602 grid.selectAllItems = function() {
603 angular.forEach($scope.items, function(item) {
604 $scope.selected[grid.indexValue(item)] = true
608 $scope.$watch('selectAll', function(newVal) {
610 grid.selectAllItems();
612 $scope.selected = {};
616 // returns true if item1 appears in the list before item2;
617 // false otherwise. this is slightly more efficient that
618 // finding the position of each then comparing them.
619 // item1 / item2 may be an item or an item index
620 grid.itemComesBefore = function(itemOrIndex1, itemOrIndex2) {
621 var idx1 = grid.indexValue(itemOrIndex1);
622 var idx2 = grid.indexValue(itemOrIndex2);
624 // use for() for early exit
625 for (var i = 0; i < $scope.items.length; i++) {
626 var idx = grid.indexValue($scope.items[i]);
627 if (idx == idx1) return true;
628 if (idx == idx2) return false;
633 // 0-based position of item in the current data set
634 grid.indexOf = function(item) {
635 var idx = grid.indexValue(item);
636 for (var i = 0; i < $scope.items.length; i++) {
637 if (grid.indexValue($scope.items[i]) == idx)
643 grid.modifyColumnFlex = function(column, val) {
645 // prevent flex:0; use hiding instead
649 $scope.modifyColumnFlex = function(col, val) {
650 grid.modifyColumnFlex(col, val);
653 // handles click, control-click, and shift-click
654 $scope.handleRowClick = function($event, item) {
655 var index = grid.indexValue(item);
657 var origSelected = Object.keys($scope.selected);
659 if ($event.ctrlKey || $event.metaKey /* mac command */) {
661 if (grid.toggleSelectOneItem(index))
662 grid.lastSelectedItemIndex = index;
664 } else if ($event.shiftKey) {
667 if (!grid.lastSelectedItemIndex ||
668 index == grid.lastSelectedItemIndex) {
669 grid.selectOneItem(index);
670 grid.lastSelectedItemIndex = index;
674 var selecting = false;
675 var ascending = grid.itemComesBefore(
676 grid.lastSelectedItemIndex, item);
678 grid.indexOf(grid.lastSelectedItemIndex);
680 // update to new last-selected
681 grid.lastSelectedItemIndex = index;
683 // select each row between the last selected and
684 // currently selected items
686 startPos += ascending ? 1 : -1;
687 var curItem = $scope.items[startPos];
689 var curIdx = grid.indexValue(curItem);
690 $scope.selected[curIdx] = true;
691 if (curIdx == index) break; // all done
696 grid.selectOneItem(index);
697 grid.lastSelectedItemIndex = index;
701 // Builds a sort expression from column sort priorities.
702 // called on page load and any time the priorities are modified.
703 grid.compileSort = function() {
704 var sortList = grid.columnsProvider.columns.filter(
705 function(col) { return Number(col.sort) != 0 }
708 if (Math.abs(a.sort) < Math.abs(b.sort))
714 if (sortList.length) {
715 grid.dataProvider.sort = sortList.map(function(col) {
717 blob[col.name] = col.sort < 0 ? 'desc' : 'asc';
723 // builds a sort expression using a single column,
724 // toggling between ascending and descending sort.
725 $scope.quickSort = function(col_name) {
726 var sort = grid.dataProvider.sort;
727 if (sort && sort.length &&
728 sort[0] == col_name) {
730 blob[col_name] = 'desc';
731 grid.dataProvider.sort = [blob];
733 grid.dataProvider.sort = [col_name];
740 // show / hide the grid configuration row
741 $scope.toggleConfDisplay = function() {
742 if ($scope.showGridConf) {
743 $scope.showGridConf = false;
744 if (grid.columnsProvider.hasSortableColumn()) {
745 // only refresh the grid if the user has the
746 // ability to modify the sort priorities.
752 $scope.showGridConf = true;
755 $scope.gridColumnPickerIsOpen = false;
758 // called when a dragged column is dropped onto itself
759 // or any other column
760 grid.onColumnDrop = function(target) {
761 if (angular.isUndefined(target)) return;
762 if (target == grid.dragColumn) return;
763 var srcIdx, targetIdx, srcCol;
764 angular.forEach(grid.columnsProvider.columns,
766 if (col.name == grid.dragColumn) {
769 } else if (col.name == target) {
775 if (srcIdx < targetIdx) targetIdx--;
777 // move src column from old location to new location in
778 // the columns array, then force a page refresh
779 grid.columnsProvider.columns.splice(srcIdx, 1);
780 grid.columnsProvider.columns.splice(targetIdx, 0, srcCol);
784 // prepares a string for inclusion within a CSV document
785 // by escaping commas and quotes and removing newlines.
786 grid.csvDatum = function(str) {
789 str = str.replace(/\n/g, '');
790 if (str.match(/\,/) || str.match(/"/)) {
791 str = str.replace(/"/g, '""');
792 str = '"' + str + '"';
797 // sets the download file name and inserts the current CSV
798 // into a Blob URL for browser download.
799 $scope.generateCSVExportURL = function() {
800 $scope.gridColumnPickerIsOpen = false;
802 // let the file name describe the grid
803 $scope.csvExportFileName =
804 ($scope.mainLabel || grid.persistKey || 'eg_grid_data')
805 .replace(/\s+/g, '_') + '_' + $scope.page();
807 // toss the CSV into a Blob and update the export URL
808 var csv = grid.generateCSV();
809 var blob = new Blob([csv], {type : 'text/plain'});
810 $scope.csvExportURL =
811 ($window.URL || $window.webkitURL).createObjectURL(blob);
814 $scope.printCSV = function() {
815 $scope.gridColumnPickerIsOpen = false;
818 content : grid.generateCSV(),
819 content_type : 'text/plain'
823 // generates CSV for the currently visible grid contents
824 grid.generateCSV = function() {
826 var colCount = grid.columnsProvider.columns.length;
829 angular.forEach(grid.columnsProvider.columns,
831 if (!col.visible) return;
832 csvStr += grid.csvDatum(col.label);
837 csvStr = csvStr.replace(/,$/,'\n');
840 angular.forEach($scope.items, function(item) {
841 angular.forEach(grid.columnsProvider.columns,
843 if (!col.visible) return;
845 var val = grid.dataProvider.itemFieldValue(item, col);
846 // filtered value (dates, etc.)
847 val = $filter('egGridValueFilter')(val, col);
848 csvStr += grid.csvDatum(val);
852 csvStr = csvStr.replace(/,$/,'\n');
858 // Interpolate the value for column.linkpath within the context
859 // of the row item to generate the final link URL.
860 $scope.generateLinkPath = function(col, item) {
861 return egCore.strings.$replace(col.linkpath, {item : item});
864 // If a column provides its own HTML template, translate it,
865 // using the current item for the template scope.
866 // note: $sce is required to avoid security restrictions and
867 // is OK here, since the template comes directly from a
868 // local HTML template (not user input).
869 $scope.translateCellTemplate = function(col, item) {
870 var html = egCore.strings.$replace(col.template, {item : item});
871 return $sce.trustAsHtml(html);
874 $scope.collect = function() { grid.collect() }
876 // asks the dataProvider for a page of data
877 grid.collect = function() {
879 // avoid firing the collect if there is nothing to collect.
880 if (grid.selfManagedData && !grid.dataProvider.query) return;
882 if (grid.collecting) return; // avoid parallel collect()
883 grid.collecting = true;
885 console.debug('egGrid.collect() offset='
886 + grid.offset + '; limit=' + grid.limit);
888 // ensure all of our dropdowns are closed
889 // TODO: git rid of these and just use dropdown-toggle,
890 // which is more reliable.
891 $scope.gridColumnPickerIsOpen = false;
892 $scope.gridRowCountIsOpen = false;
893 $scope.gridPageSelectIsOpen = false;
896 $scope.selected = {};
897 grid.dataProvider.get(grid.offset, grid.limit).then(
899 if (grid.controls.allItemsRetrieved)
900 grid.controls.allItemsRetrieved();
905 $scope.items.push(item)
906 if (grid.controls.itemRetrieved)
907 grid.controls.itemRetrieved(item);
909 }).finally(function() {
910 console.debug('egGrid.collect() complete');
911 grid.collecting = false
921 * eg-grid-field : used for collecting custom field data from the templates.
922 * This directive does not direct display, it just passes data up to the
925 .directive('egGridField', function() {
930 name : '@', // required; unique name
931 path : '@', // optional; flesh path
932 ignore: '@', // optional; fields to ignore when path is a wildcard
933 label : '@', // optional; display label
934 flex : '@', // optional; default flex width
935 align : '@', // optional; default alignment, left/center/right
936 dateformat : '@', // optional: passed down to egGridValueFilter
938 // if a field is part of an IDL object, but we are unable to
939 // determine the class, because it's nested within a hash
940 // (i.e. we can't navigate directly to the object via the IDL),
941 // idlClass lets us specify the class. This is particularly
942 // useful for nested wildcard fields.
943 parentIdlClass : '@',
945 // optional: for non-IDL columns, specifying a datatype
946 // lets the caller control which display filter is used.
947 // datatype should match the standard IDL datatypes.
950 link : function(scope, element, attrs, egGridCtrl) {
952 // boolean fields are presented as value-less attributes
961 'required' // if set, always fetch data for this column
964 if (angular.isDefined(attrs[field]))
969 // any HTML content within the field is its custom template
970 var tmpl = element.html();
971 if (tmpl && !tmpl.match(/^\s*$/))
972 scope.template = tmpl
974 egGridCtrl.columnsProvider.add(scope);
981 * eg-grid-action : used for specifying actions which may be applied
982 * to items within the grid.
984 .directive('egGridAction', function() {
990 group : '@', // Action group, ungrouped if not set
991 label : '@', // Action label
992 handler : '=', // Action function handler
996 link : function(scope, element, attrs, egGridCtrl) {
997 egGridCtrl.addAction({
1000 label : scope.label,
1001 divider : scope.divider,
1002 handler : scope.handler
1009 .factory('egGridColumnsProvider', ['egCore', function(egCore) {
1011 function ColumnsProvider(args) {
1014 cols.stockVisible = [];
1015 cols.idlClass = args.idlClass;
1016 cols.defaultToHidden = args.defaultToHidden;
1017 cols.defaultToNoSort = args.defaultToNoSort;
1018 cols.defaultToNoMultiSort = args.defaultToNoMultiSort;
1020 // resets column width, visibility, and sort behavior
1021 // Visibility resets to the visibility settings defined in the
1022 // template (i.e. the original egGridField values).
1023 cols.reset = function() {
1024 angular.forEach(cols.columns, function(col) {
1028 if (cols.stockVisible.indexOf(col.name) > -1) {
1031 col.visible = false;
1036 // returns true if any columns are sortable
1037 cols.hasSortableColumn = function() {
1038 return cols.columns.filter(
1040 return col.sortable || col.multisortable;
1045 cols.showAllColumns = function() {
1046 angular.forEach(cols.columns, function(column) {
1047 column.visible = true;
1051 cols.hideAllColumns = function() {
1052 angular.forEach(cols.columns, function(col) {
1057 cols.indexOf = function(name) {
1058 for (var i = 0; i < cols.columns.length; i++) {
1059 if (cols.columns[i].name == name)
1065 cols.findColumn = function(name) {
1066 return cols.columns[cols.indexOf(name)];
1069 cols.compileAutoColumns = function() {
1070 var idl_class = egCore.idl.classes[cols.idlClass];
1073 idl_class.fields.sort(
1074 function(a, b) { return a.name < b.name ? -1 : 1 }),
1076 if (field.virtual) return;
1077 if (field.datatype == 'link' || field.datatype == 'org_unit') {
1078 // if the field is a link and the linked class has a
1079 // "selector" field specified, use the selector field
1080 // as the display field for the columns.
1081 // flattener will take care of the fleshing.
1082 if (field['class']) {
1083 var selector_field = egCore.idl.classes[field['class']].fields
1084 .filter(function(f) { return Boolean(f.selector) })[0];
1085 if (selector_field) {
1086 field.path = field.name + '.' + selector_field.selector;
1090 cols.add(field, true);
1095 // if a column definition has a path with a wildcard, create
1096 // columns for all non-virtual fields at the specified
1097 // position in the path.
1098 cols.expandPath = function(colSpec) {
1100 var ignoreList = [];
1102 ignoreList = colSpec.ignore.split(' ');
1104 var dotpath = colSpec.path.replace(/\.?\*$/,'');
1108 if (colSpec.parentIdlClass) {
1109 class_obj = egCore.idl.classes[colSpec.parentIdlClass];
1111 class_obj = egCore.idl.classes[cols.idlClass];
1114 if (!class_obj) return;
1116 console.debug('egGrid: auto dotpath is: ' + dotpath);
1117 var path_parts = dotpath.split(/\./);
1119 // find the IDL class definition for the last element in the
1120 // path before the .*
1121 // an empty path_parts means expand the root class
1123 for (var path_idx in path_parts) {
1124 var part = path_parts[path_idx];
1125 idl_field = class_obj.field_map[part];
1127 // unless we're at the end of the list, this field should
1128 // link to another class.
1129 if (idl_field && idl_field['class'] && (
1130 idl_field.datatype == 'link' ||
1131 idl_field.datatype == 'org_unit')) {
1132 class_obj = egCore.idl.classes[idl_field['class']];
1134 if (path_idx < (path_parts.length - 1)) {
1135 // we ran out of classes to hop through before
1136 // we ran out of path components
1137 console.error("egGrid: invalid IDL path: " + dotpath);
1144 angular.forEach(class_obj.fields, function(field) {
1146 // Only show wildcard fields where we have data to show
1147 // Virtual and un-fleshed links will not have any data.
1148 if (field.virtual ||
1149 (field.datatype == 'link' || field.datatype == 'org_unit') ||
1150 ignoreList.indexOf(field.name) > -1
1154 var col = cols.cloneFromScope(colSpec);
1155 col.path = dotpath + '.' + field.name;
1156 console.debug('egGrid: field: ' +field.name + '; parent field: ' + js2JSON(idl_field));
1157 cols.add(col, false, true,
1158 {idl_parent : idl_field, idl_field : field, idl_class : class_obj});
1161 cols.columns = cols.columns.sort(
1163 if (a.explicit) return -1;
1164 if (b.explicit) return 1;
1165 if (a.idlclass && b.idlclass) {
1166 return a.idlclass < b.idlclass ? -1 : 1;
1167 return a.idlclass > b.idlclass ? 1 : -1;
1169 if (a.path && b.path) {
1170 return a.path < b.path ? -1 : 1;
1171 return a.path > b.path ? 1 : -1;
1174 return a.label < b.label ? -1 : 1;
1181 "egGrid: wildcard path does not resolve to an object: "
1186 // angular.clone(scopeObject) is not permittable. Manually copy
1187 // the fields over that we need (so the scope object can go away).
1188 cols.cloneFromScope = function(colSpec) {
1190 name : colSpec.name,
1191 label : colSpec.label,
1192 path : colSpec.path,
1193 align : colSpec.align || 'left',
1194 flex : Number(colSpec.flex) || 2,
1195 sort : Number(colSpec.sort) || 0,
1196 required : colSpec.required,
1197 linkpath : colSpec.linkpath,
1198 template : colSpec.template,
1199 visible : colSpec.visible,
1200 hidden : colSpec.hidden,
1201 datatype : colSpec.datatype,
1202 sortable : colSpec.sortable,
1203 nonsortable : colSpec.nonsortable,
1204 multisortable : colSpec.multisortable,
1205 nonmultisortable : colSpec.nonmultisortable,
1206 dateformat : colSpec.dateformat,
1207 parentIdlClass : colSpec.parentIdlClass
1212 // Add a column to the columns collection.
1213 // Columns may come from a slim eg-columns-field or
1214 // directly from the IDL.
1215 cols.add = function(colSpec, fromIDL, fromExpand, idl_info) {
1217 // First added column with the specified path takes precedence.
1218 // This allows for specific definitions followed by wildcard
1219 // definitions. If a match is found, back out.
1220 if (cols.columns.filter(function(c) {
1221 return (c.path == colSpec.path) })[0]) {
1222 console.debug('skipping pre-existing column ' + colSpec.path);
1226 var column = fromExpand ? colSpec : cols.cloneFromScope(colSpec);
1228 if (column.path && column.path.match(/\*$/))
1229 return cols.expandPath(colSpec);
1231 if (!fromExpand) column.explicit = true;
1233 if (!column.name) column.name = column.path;
1234 if (!column.path) column.path = column.name;
1236 if (column.visible || (!cols.defaultToHidden && !column.hidden))
1237 column.visible = true;
1239 if (column.sortable || (!cols.defaultToNoSort && !column.nonsortable))
1240 column.sortable = true;
1242 if (column.multisortable ||
1243 (!cols.defaultToNoMultiSort && !column.nonmultisortable))
1244 column.multisortable = true;
1246 cols.columns.push(column);
1248 // Track which columns are visible by default in case we
1249 // need to reset column visibility
1251 cols.stockVisible.push(column.name);
1253 if (fromIDL) return; // directly from egIDL. nothing left to do.
1255 // lookup the matching IDL field
1256 if (!idl_info && cols.idlClass)
1257 idl_info = cols.idlFieldFromPath(column.path);
1260 // column is not represented within the IDL
1261 column.adhoc = true;
1265 column.datatype = idl_info.idl_field.datatype;
1267 if (!column.label) {
1268 column.label = idl_info.idl_field.label || column.name;
1271 if (fromExpand && idl_info.idl_class) {
1272 column.idlclass = '';
1273 if (idl_info.idl_parent) {
1274 column.idlclass = idl_info.idl_parent.label || idl_info.idl_parent.name;
1276 column.idlclass += idl_info.idl_class.label || idl_info.idl_class.name;
1281 // finds the IDL field from the dotpath, using the columns
1282 // idlClass as the base.
1283 cols.idlFieldFromPath = function(dotpath) {
1284 var class_obj = egCore.idl.classes[cols.idlClass];
1285 var path_parts = dotpath.split(/\./);
1289 for (var path_idx in path_parts) {
1290 var part = path_parts[path_idx];
1291 idl_parent = idl_field;
1292 idl_field = class_obj.field_map[part];
1294 if (idl_field && idl_field['class'] && (
1295 idl_field.datatype == 'link' ||
1296 idl_field.datatype == 'org_unit')) {
1297 class_obj = egCore.idl.classes[idl_field['class']];
1299 // else, path is not in the IDL, which is fine
1302 if (!idl_field) return null;
1305 idl_parent: idl_parent,
1306 idl_field : idl_field,
1307 idl_class : class_obj
1313 instance : function(args) { return new ColumnsProvider(args) }
1319 * Generic data provider template class. This is basically an abstract
1320 * class factory service whose instances can be locally modified to
1321 * meet the needs of each individual grid.
1323 .factory('egGridDataProvider',
1324 ['$q','$timeout','$filter','egCore',
1325 function($q , $timeout , $filter , egCore) {
1327 function GridDataProvider(args) {
1328 var gridData = this;
1329 if (!args) args = {};
1332 gridData.get = args.get;
1333 gridData.query = args.query;
1334 gridData.idlClass = args.idlClass;
1335 gridData.columnsProvider = args.columnsProvider;
1337 // Delivers a stream of array data via promise.notify()
1338 // Useful for passing an array of data to egGrid.get()
1339 // If a count is provided, the array will be trimmed to
1340 // the range defined by count and offset
1341 gridData.arrayNotifier = function(arr, offset, count) {
1342 if (!arr || arr.length == 0) return $q.when();
1343 if (count) arr = arr.slice(offset, offset + count);
1344 var def = $q.defer();
1345 // promise notifications are only witnessed when delivered
1346 // after the caller has his hands on the promise object
1347 $timeout(function() {
1348 angular.forEach(arr, def.notify);
1354 // Calls the grid refresh function. Once instantiated, the
1355 // grid will replace this function with it's own refresh()
1356 gridData.refresh = function(noReset) { }
1358 if (!gridData.get) {
1359 // returns a promise whose notify() delivers items
1360 gridData.get = function(index, count) {
1361 console.error("egGridDataProvider.get() not implemented");
1365 // attempts a flat field lookup first. If the column is not
1366 // found on the top-level object, attempts a nested lookup
1367 // TODO: consider a caching layer to speed up template
1368 // rendering, particularly for nested objects?
1369 gridData.itemFieldValue = function(item, column) {
1370 if (column.name in item) {
1371 if (typeof item[column.name] == 'function') {
1372 return item[column.name]();
1374 return item[column.name];
1377 return gridData.nestedItemFieldValue(item, column);
1381 // TODO: deprecate me
1382 gridData.flatItemFieldValue = function(item, column) {
1383 console.warn('gridData.flatItemFieldValue deprecated; '
1384 + 'leave provider.itemFieldValue unset');
1385 return item[column.name];
1388 // given an object and a dot-separated path to a field,
1389 // extract the value of the field. The path can refer
1390 // to function names or object attributes. If the final
1391 // value is an IDL field, run the value through its
1392 // corresponding output filter.
1393 gridData.nestedItemFieldValue = function(obj, column) {
1394 if (obj === null || obj === undefined || obj === '') return '';
1395 if (!column.path) return obj;
1398 var parts = column.path.split('.');
1400 angular.forEach(parts, function(step, idx) {
1401 // object is not fleshed to the expected extent
1402 if (!obj || typeof obj != 'object') {
1407 var cls = obj.classname;
1408 if (cls && (class_obj = egCore.idl.classes[cls])) {
1409 idl_field = class_obj.field_map[step];
1410 obj = obj[step] ? obj[step]() : '';
1412 if (angular.isFunction(obj[step])) {
1420 // We found a nested IDL object which may or may not have
1421 // been configured as a top-level column. Grab the datatype.
1422 if (idl_field && !column.datatype)
1423 column.datatype = idl_field.datatype;
1425 if (obj === null || obj === undefined || obj === '') return '';
1431 instance : function(args) {
1432 return new GridDataProvider(args);
1439 // Factory service for egGridDataManager instances, which are
1440 // responsible for collecting flattened grid data.
1441 .factory('egGridFlatDataProvider',
1442 ['$q','egCore','egGridDataProvider',
1443 function($q , egCore , egGridDataProvider) {
1446 instance : function(args) {
1447 var provider = egGridDataProvider.instance(args);
1449 provider.get = function(offset, count) {
1451 // no query means no call
1452 if (!provider.query ||
1453 angular.equals(provider.query, {}))
1456 // find all of the currently visible columns
1457 var queryFields = {}
1458 angular.forEach(provider.columnsProvider.columns,
1460 // only query IDL-tracked columns
1461 if (!col.adhoc && (col.required || col.visible))
1462 queryFields[col.name] = col.path;
1466 return egCore.net.request(
1468 'open-ils.fielder.flattened_search',
1469 egCore.auth.token(), provider.idlClass,
1470 queryFields, provider.query,
1471 { sort : provider.sort,
1477 //provider.itemFieldValue = provider.flatItemFieldValue;
1484 .directive('egGridColumnDragSource', function() {
1487 require : '^egGrid',
1488 link : function(scope, element, attrs, egGridCtrl) {
1489 angular.element(element).attr('draggable', 'true');
1491 element.bind('dragstart', function(e) {
1492 egGridCtrl.dragColumn = attrs.column;
1493 egGridCtrl.dragType = attrs.dragType || 'move'; // or resize
1494 egGridCtrl.colResizeDir = 0;
1496 if (egGridCtrl.dragType == 'move') {
1497 // style the column getting moved
1498 angular.element(e.target).addClass(
1499 'eg-grid-column-move-handle-active');
1503 element.bind('dragend', function(e) {
1504 if (egGridCtrl.dragType == 'move') {
1505 angular.element(e.target).removeClass(
1506 'eg-grid-column-move-handle-active');
1513 .directive('egGridColumnDragDest', function() {
1516 require : '^egGrid',
1517 link : function(scope, element, attrs, egGridCtrl) {
1519 element.bind('dragover', function(e) { // required for drop
1520 e.stopPropagation();
1522 e.dataTransfer.dropEffect = 'move';
1524 if (egGridCtrl.colResizeDir == 0) return; // move
1526 var cols = egGridCtrl.columnsProvider;
1527 var srcCol = egGridCtrl.dragColumn;
1528 var srcColIdx = cols.indexOf(srcCol);
1530 if (egGridCtrl.colResizeDir == -1) {
1531 if (cols.indexOf(attrs.column) <= srcColIdx) {
1532 egGridCtrl.modifyColumnFlex(
1533 egGridCtrl.columnsProvider.findColumn(
1534 egGridCtrl.dragColumn), -1);
1535 if (cols.columns[srcColIdx+1]) {
1536 // source column shrinks by one, column to the
1537 // right grows by one.
1538 egGridCtrl.modifyColumnFlex(
1539 cols.columns[srcColIdx+1], 1);
1544 if (cols.indexOf(attrs.column) > srcColIdx) {
1545 egGridCtrl.modifyColumnFlex(
1546 egGridCtrl.columnsProvider.findColumn(
1547 egGridCtrl.dragColumn), 1);
1548 if (cols.columns[srcColIdx+1]) {
1549 // source column grows by one, column to the
1550 // right grows by one.
1551 egGridCtrl.modifyColumnFlex(
1552 cols.columns[srcColIdx+1], -1);
1560 element.bind('dragenter', function(e) {
1561 e.stopPropagation();
1563 if (egGridCtrl.dragType == 'move') {
1564 angular.element(e.target).addClass('eg-grid-col-hover');
1566 // resize grips are on the right side of each column.
1567 // dragenter will either occur on the source column
1568 // (dragging left) or the column to the right.
1569 if (egGridCtrl.colResizeDir == 0) {
1570 if (egGridCtrl.dragColumn == attrs.column) {
1571 egGridCtrl.colResizeDir = -1; // west
1573 egGridCtrl.colResizeDir = 1; // east
1579 element.bind('dragleave', function(e) {
1580 e.stopPropagation();
1582 if (egGridCtrl.dragType == 'move') {
1583 angular.element(e.target).removeClass('eg-grid-col-hover');
1587 element.bind('drop', function(e) {
1588 e.stopPropagation();
1590 egGridCtrl.colResizeDir = 0;
1591 if (egGridCtrl.dragType == 'move') {
1592 angular.element(e.target).removeClass('eg-grid-col-hover');
1593 egGridCtrl.onColumnDrop(attrs.column); // move the column
1600 .directive('egGridMenuItem', function() {
1603 require : '^egGrid',
1607 handler : '=', // onclick handler function
1608 divider : '=', // if true, show a divider only
1609 handlerData : '=', // if set, passed as second argument to handler
1610 disabled : '=', // function
1611 hidden : '=' // function
1613 link : function(scope, element, attrs, egGridCtrl) {
1614 egGridCtrl.addMenuItem({
1615 label : scope.label,
1616 standalone : scope.standalone ? true : false,
1617 handler : scope.handler,
1618 divider : scope.divider,
1619 disabled : scope.disabled,
1620 hidden : scope.hidden,
1621 handlerData : scope.handlerData
1631 * Translates bare IDL object values into display values.
1632 * 1. Passes dates through the angular date filter
1633 * 2. Translates bools to Booleans so the browser can display translated
1634 * value. (Though we could manually translate instead..)
1635 * Others likely to follow...
1637 .filter('egGridValueFilter', ['$filter', function($filter) {
1638 return function(value, column) {
1639 switch(column.datatype) {
1642 // Browser will translate true/false for us
1644 case '1' : // legacy
1648 case '0' : // legacy
1651 // value may be null, '', etc.
1652 default : return '';
1655 // canned angular date filter FTW
1656 if (!column.dateformat)
1657 column.dateformat = 'shortDate';
1658 return $filter('date')(value, column.dateformat);
1660 return $filter('currency')(value);