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
37 // -multiselect : only one row at a time can be selected;
38 // choosing this also disables the checkbox
42 // optional primary grid label
45 // if true, use the IDL class label as the mainLabel
48 // optional context menu label
51 // Hash of control functions.
53 // These functions are defined by the calling scope and
54 // invoked as-is by the grid w/ the specified parameters.
56 // itemRetrieved : function(item) {}
57 // allItemsRetrieved : function() {}
60 // If defined, the grid will watch the return value from
61 // the function defined at watchQuery on each digest and
62 // re-draw the grid when query changes occur.
64 // watchQuery : function() { /* return grid query */ }
67 // These functions are defined by the grid and thus
68 // replace any values defined for these attributes from the
71 // activateItem : function(item) {}
72 // allItems : function(allItems) {}
73 // selectedItems : function(selected) {}
74 // selectItems : function(ids) {}
75 // setQuery : function(queryStruct) {} // causes reload
76 // setSort : function(sortSturct) {} // causes reload
80 // TODO: avoid hard-coded url
81 templateUrl : '/eg/staff/share/t_autogrid',
83 link : function(scope, element, attrs) {
84 // link() is called after page compilation, which means our
85 // eg-grid-field's have been parsed and loaded. Now it's
86 // safe to perform our initial page load.
88 // load auto fields after eg-grid-field's so they are not clobbered
89 scope.handleAutoFields();
92 scope.grid_element = element;
94 .find('.eg-grid-content-body')
95 .bind('contextmenu', scope.showActionContextMenu);
99 '$scope','$q','egCore','egGridFlatDataProvider','$location',
100 'egGridColumnsProvider','$filter','$window','$sce','$timeout',
101 function($scope, $q , egCore, egGridFlatDataProvider , $location,
102 egGridColumnsProvider , $filter , $window , $sce , $timeout) {
106 grid.init = function() {
109 $scope.showGridConf = false;
110 grid.totalCount = -1;
111 $scope.selected = {};
112 $scope.actionGroups = [{actions:[]}]; // Grouped actions for selected items
113 $scope.menuItems = []; // global actions
115 // remove some unneeded values from the scope to reduce bloat
117 grid.idlClass = $scope.idlClass;
118 delete $scope.idlClass;
120 grid.persistKey = $scope.persistKey;
121 delete $scope.persistKey;
123 var stored_limit = 0;
124 if (grid.persistKey) {
125 var stored_limit = Number(
126 egCore.hatch.getLocalItem('eg.grid.' + grid.persistKey + '.limit')
129 grid.limit = Number(stored_limit) || Number($scope.pageSize) || 25;
131 grid.indexField = $scope.idField;
132 delete $scope.idField;
134 grid.dataProvider = $scope.itemsProvider;
136 var features = ($scope.features) ?
137 $scope.features.split(',') : [];
138 delete $scope.features;
140 if (!grid.indexField && grid.idlClass)
141 grid.indexField = egCore.idl.classes[grid.idlClass].pkey;
143 grid.columnsProvider = egGridColumnsProvider.instance({
144 idlClass : grid.idlClass,
145 defaultToHidden : (features.indexOf('-display') > -1),
146 defaultToNoSort : (features.indexOf('-sort') > -1),
147 defaultToNoMultiSort : (features.indexOf('-multisort') > -1)
149 $scope.canMultiSelect = (features.indexOf('-multiselect') == -1);
151 $scope.handleAutoFields = function() {
152 if ($scope.autoFields) {
153 if (grid.autoLabel) {
155 egCore.idl.classes[grid.idlClass].label;
157 grid.columnsProvider.compileAutoColumns();
158 delete $scope.autoFields;
162 if (!grid.dataProvider) {
163 // no provider, um, provided.
164 // Use a flat data provider
166 grid.selfManagedData = true;
167 grid.dataProvider = egGridFlatDataProvider.instance({
168 indexField : grid.indexField,
169 idlClass : grid.idlClass,
170 columnsProvider : grid.columnsProvider,
175 $scope.itemFieldValue = grid.dataProvider.itemFieldValue;
176 $scope.indexValue = function(item) {
177 return grid.indexValue(item)
180 grid.applyControlFunctions();
182 grid.loadConfig().then(function() {
183 // link columns to scope after loadConfig(), since it
184 // replaces the columns array.
185 $scope.columns = grid.columnsProvider.columns;
188 // NOTE: grid.collect() is first called from link(), not here.
191 // link our control functions into the gridControls
192 // scope object so the caller can access them.
193 grid.applyControlFunctions = function() {
195 // we use some of these controls internally, so sett
196 // them up even if the caller doesn't request them.
197 var controls = $scope.gridControls || {};
199 // link in the control functions
200 controls.selectedItems = function() {
201 return grid.getSelectedItems()
204 controls.allItems = function() {
208 controls.selectItems = function(ids) {
210 $scope.selected = {};
211 angular.forEach(ids, function(i) {
212 $scope.selected[''+i] = true;
216 // if the caller provided a functional setQuery,
217 // extract the value before replacing it
218 if (controls.setQuery) {
219 grid.dataProvider.query =
223 controls.setQuery = function(query) {
224 grid.dataProvider.query = query;
228 if (controls.watchQuery) {
229 // capture the initial query value
230 grid.dataProvider.query = controls.watchQuery();
233 $scope.gridWatchQuery = controls.watchQuery;
234 $scope.$watch('gridWatchQuery()', function(newv) {
235 controls.setQuery(newv);
239 // if the caller provided a functional setSort
240 // extract the value before replacing it
241 grid.dataProvider.sort =
242 controls.setSort ? controls.setSort() : [];
244 controls.setSort = function(sort) {
248 controls.refresh = function(noReset) {
249 if (!noReset) grid.offset = 0;
253 controls.setLimit = function(limit,forget) {
254 if (!forget && grid.persistKey)
255 egCore.hatch.setLocalItem('eg.grid.' + grid.persistKey + '.limit', limit);
258 controls.getLimit = function() {
261 controls.setOffset = function(offset) {
262 grid.offset = offset;
264 controls.getOffset = function() {
268 grid.dataProvider.refresh = controls.refresh;
269 grid.controls = controls;
272 // If a menu item provides its own HTML template, translate it,
273 // using the menu item for the template scope.
274 // note: $sce is required to avoid security restrictions and
275 // is OK here, since the template comes directly from a
276 // local HTML template (not user input).
277 $scope.translateMenuItemTemplate = function(item) {
278 var html = egCore.strings.$replace(item.template, {item : item});
279 return $sce.trustAsHtml(html);
282 // add a new (global) grid menu item
283 grid.addMenuItem = function(item) {
284 $scope.menuItems.push(item);
285 var handler = item.handler;
286 item.handler = function() {
287 $scope.gridMenuIsOpen = false; // close menu
290 item.handlerData, grid.getSelectedItems());
295 // add a selected-items action
296 grid.addAction = function(act) {
298 $scope.actionGroups.forEach(function(g){
299 if (g.label === act.group) {
305 $scope.actionGroups.push({
312 // remove the stored column configuration preferenc, then recover
313 // the column visibility information from the initial page load.
314 $scope.resetColumns = function() {
315 $scope.gridColumnPickerIsOpen = false;
316 egCore.hatch.removeItem('eg.grid.' + grid.persistKey)
318 grid.columnsProvider.reset();
319 if (grid.selfManagedData) grid.collect();
323 $scope.showAllColumns = function() {
324 $scope.gridColumnPickerIsOpen = false;
325 grid.columnsProvider.showAllColumns();
326 if (grid.selfManagedData) grid.collect();
329 $scope.hideAllColumns = function() {
330 $scope.gridColumnPickerIsOpen = false;
331 grid.columnsProvider.hideAllColumns();
332 // note: no need to fetch new data if no columns are visible
335 $scope.toggleColumnVisibility = function(col) {
336 $scope.gridColumnPickerIsOpen = false;
337 col.visible = !col.visible;
339 // egGridFlatDataProvider only retrieves data to be
340 // displayed. When column visibility changes, it's
341 // necessary to fetch the newly visible column data.
342 if (grid.selfManagedData) grid.collect();
345 // save the columns configuration (position, sort, width) to
346 // eg.grid.<persist-key>
347 $scope.saveConfig = function() {
348 $scope.gridColumnPickerIsOpen = false;
350 if (!grid.persistKey) {
352 "Cannot save settings without a grid persist-key");
356 // only store information about visible columns.
357 var conf = grid.columnsProvider.columns.filter(
358 function(col) {return Boolean(col.visible) });
360 // now scrunch the data down to just the needed info
361 conf = conf.map(function(col) {
362 var c = {name : col.name}
363 // Apart from the name, only store non-default values.
364 // No need to store col.visible, since that's implicit
365 if (col.align != 'left') c.align = col.align;
366 if (col.flex != 2) c.flex = col.flex;
367 if (Number(col.sort)) c.sort = Number(c.sort);
371 egCore.hatch.setItem('eg.grid.' + grid.persistKey, conf)
373 // Save operation performed from the grid configuration UI.
374 // Hide the configuration UI and re-draw w/ sort applied
375 if ($scope.showGridConf)
376 $scope.toggleConfDisplay();
380 // load the columns configuration (position, sort, width) from
381 // eg.grid.<persist-key> and apply the loaded settings to the
382 // columns on our columnsProvider
383 grid.loadConfig = function() {
384 if (!grid.persistKey) return $q.when();
386 return egCore.hatch.getItem('eg.grid.' + grid.persistKey)
387 .then(function(conf) {
390 var columns = grid.columnsProvider.columns;
393 angular.forEach(conf, function(col) {
394 var grid_col = columns.filter(
395 function(c) {return c.name == col.name})[0];
398 // saved column does not match a column in the
399 // current grid. skip it.
403 grid_col.align = col.align || 'left';
404 grid_col.flex = col.flex || 2;
405 grid_col.sort = col.sort || 0;
406 // all saved columns are assumed to be true
407 grid_col.visible = true;
408 new_cols.push(grid_col);
411 // columns which are not expressed within the saved
412 // configuration are marked as non-visible and
413 // appended to the end of the new list of columns.
414 angular.forEach(columns, function(col) {
415 var found = conf.filter(
416 function(c) {return (c.name == col.name)})[0];
423 grid.columnsProvider.columns = new_cols;
428 $scope.onContextMenu = function($event) {
429 var col = angular.element($event.target).attr('column');
430 console.log('selected column ' + col);
433 $scope.page = function() {
434 return (grid.offset / grid.limit) + 1;
437 $scope.goToPage = function(page) {
439 if (angular.isNumber(page) && page > 0) {
440 grid.offset = (page - 1) * grid.limit;
445 $scope.offset = function(o) {
446 if (angular.isNumber(o))
451 $scope.limit = function(l) {
452 if (angular.isNumber(l)) {
454 egCore.hatch.setLocalItem('eg.grid.' + grid.persistKey + '.limit', l);
460 $scope.onFirstPage = function() {
461 return grid.offset == 0;
464 $scope.hasNextPage = function() {
465 // we have less data than requested, there must
466 // not be any more pages
467 if (grid.count() < grid.limit) return false;
469 // if the total count is not known, assume that a full
470 // page of data implies more pages are available.
471 if (grid.totalCount == -1) return true;
473 // we have a full page of data, but is there more?
474 return grid.totalCount > (grid.offset + grid.count());
477 $scope.incrementPage = function() {
478 grid.offset += grid.limit;
482 $scope.decrementPage = function() {
483 if (grid.offset < grid.limit) {
486 grid.offset -= grid.limit;
491 // number of items loaded for the current page of results
492 grid.count = function() {
493 return $scope.items.length;
496 // returns the unique identifier value for the provided item
497 // for internal consistency, indexValue is always coerced
499 grid.indexValue = function(item) {
500 if (angular.isObject(item)) {
502 if (angular.isFunction(item[grid.indexField]))
503 return ''+item[grid.indexField]();
504 return ''+item[grid.indexField]; // flat data
507 // passed a non-object; assume it's an index
511 // fires the hide handler function for a context action
512 $scope.actionHide = function(action) {
516 return action.hide(action);
519 // fires the action handler function for a context action
520 $scope.actionLauncher = function(action) {
521 if (!action.handler) {
523 'No handler specified for "' + action.label + '"');
527 action.handler(grid.getSelectedItems());
529 console.error('Error executing handler for "'
530 + action.label + '" => ' + E + "\n" + E.stack);
533 if ($scope.action_context_showing) $scope.hideActionContextMenu();
538 $scope.hideActionContextMenu = function () {
539 $($scope.menu_dom).css({
541 width: $scope.action_context_width,
542 top: $scope.action_context_y,
543 left: $scope.action_context_x
545 $($scope.action_context_parent).append($scope.menu_dom);
546 $scope.action_context_oldy = $scope.action_context_oldx = 0;
547 $('body').unbind('click.remove_context_menu_'+$scope.action_context_index);
548 $scope.action_context_showing = false;
551 $scope.action_context_showing = false;
552 $scope.showActionContextMenu = function ($event) {
554 // Have to gather these here, instead of inside link()
555 if (!$scope.menu_dom) $scope.menu_dom = $($scope.grid_element).find('.grid-action-dropdown')[0];
556 if (!$scope.action_context_parent) $scope.action_context_parent = $($scope.menu_dom).parent();
558 if (!grid.getSelectedItems().length) // Nothing selected, fire the click event
559 $event.target.click();
561 if (!$scope.action_context_showing) {
562 $scope.action_context_width = $($scope.menu_dom).css('width');
563 $scope.action_context_y = $($scope.menu_dom).css('top');
564 $scope.action_context_x = $($scope.menu_dom).css('left');
565 $scope.action_context_showing = true;
566 $scope.action_context_index = Math.floor((Math.random() * 1000) + 1);
568 $('body').append($($scope.menu_dom));
569 $('body').bind('click.remove_context_menu_'+$scope.action_context_index, $scope.hideActionContextMenu);
572 $($scope.menu_dom).css({
574 width: $scope.action_context_width,
582 // returns the list of selected item objects
583 grid.getSelectedItems = function() {
584 return $scope.items.filter(
586 return Boolean($scope.selected[grid.indexValue(item)]);
591 grid.getItemByIndex = function(index) {
592 for (var i = 0; i < $scope.items.length; i++) {
593 var item = $scope.items[i];
594 if (grid.indexValue(item) == index)
599 // selects one row after deselecting all of the others
600 grid.selectOneItem = function(index) {
601 $scope.selected = {};
602 $scope.selected[index] = true;
605 // selects or deselects an item, without affecting the others.
606 // returns true if the item is selected; false if de-selected.
607 grid.toggleSelectOneItem = function(index) {
608 if ($scope.selected[index]) {
609 delete $scope.selected[index];
612 return $scope.selected[index] = true;
616 grid.selectAllItems = function() {
617 angular.forEach($scope.items, function(item) {
618 $scope.selected[grid.indexValue(item)] = true
622 $scope.$watch('selectAll', function(newVal) {
624 grid.selectAllItems();
626 $scope.selected = {};
630 // returns true if item1 appears in the list before item2;
631 // false otherwise. this is slightly more efficient that
632 // finding the position of each then comparing them.
633 // item1 / item2 may be an item or an item index
634 grid.itemComesBefore = function(itemOrIndex1, itemOrIndex2) {
635 var idx1 = grid.indexValue(itemOrIndex1);
636 var idx2 = grid.indexValue(itemOrIndex2);
638 // use for() for early exit
639 for (var i = 0; i < $scope.items.length; i++) {
640 var idx = grid.indexValue($scope.items[i]);
641 if (idx == idx1) return true;
642 if (idx == idx2) return false;
647 // 0-based position of item in the current data set
648 grid.indexOf = function(item) {
649 var idx = grid.indexValue(item);
650 for (var i = 0; i < $scope.items.length; i++) {
651 if (grid.indexValue($scope.items[i]) == idx)
657 grid.modifyColumnFlex = function(column, val) {
659 // prevent flex:0; use hiding instead
663 $scope.modifyColumnFlex = function(col, val) {
664 grid.modifyColumnFlex(col, val);
667 // handles click, control-click, and shift-click
668 $scope.handleRowClick = function($event, item) {
669 var index = grid.indexValue(item);
671 var origSelected = Object.keys($scope.selected);
673 if (!$scope.canMultiSelect) {
674 grid.selectOneItem(index);
675 grid.lastSelectedItemIndex = index;
679 if ($event.ctrlKey || $event.metaKey /* mac command */) {
681 if (grid.toggleSelectOneItem(index))
682 grid.lastSelectedItemIndex = index;
684 } else if ($event.shiftKey) {
687 if (!grid.lastSelectedItemIndex ||
688 index == grid.lastSelectedItemIndex) {
689 grid.selectOneItem(index);
690 grid.lastSelectedItemIndex = index;
694 var selecting = false;
695 var ascending = grid.itemComesBefore(
696 grid.lastSelectedItemIndex, item);
698 grid.indexOf(grid.lastSelectedItemIndex);
700 // update to new last-selected
701 grid.lastSelectedItemIndex = index;
703 // select each row between the last selected and
704 // currently selected items
706 startPos += ascending ? 1 : -1;
707 var curItem = $scope.items[startPos];
709 var curIdx = grid.indexValue(curItem);
710 $scope.selected[curIdx] = true;
711 if (curIdx == index) break; // all done
716 grid.selectOneItem(index);
717 grid.lastSelectedItemIndex = index;
721 // Builds a sort expression from column sort priorities.
722 // called on page load and any time the priorities are modified.
723 grid.compileSort = function() {
724 var sortList = grid.columnsProvider.columns.filter(
725 function(col) { return Number(col.sort) != 0 }
728 if (Math.abs(a.sort) < Math.abs(b.sort))
734 if (sortList.length) {
735 grid.dataProvider.sort = sortList.map(function(col) {
737 blob[col.name] = col.sort < 0 ? 'desc' : 'asc';
743 // builds a sort expression using a single column,
744 // toggling between ascending and descending sort.
745 $scope.quickSort = function(col_name) {
746 var sort = grid.dataProvider.sort;
747 if (sort && sort.length &&
748 sort[0] == col_name) {
750 blob[col_name] = 'desc';
751 grid.dataProvider.sort = [blob];
753 grid.dataProvider.sort = [col_name];
760 // show / hide the grid configuration row
761 $scope.toggleConfDisplay = function() {
762 if ($scope.showGridConf) {
763 $scope.showGridConf = false;
764 if (grid.columnsProvider.hasSortableColumn()) {
765 // only refresh the grid if the user has the
766 // ability to modify the sort priorities.
772 $scope.showGridConf = true;
775 $scope.gridColumnPickerIsOpen = false;
778 // called when a dragged column is dropped onto itself
779 // or any other column
780 grid.onColumnDrop = function(target) {
781 if (angular.isUndefined(target)) return;
782 if (target == grid.dragColumn) return;
783 var srcIdx, targetIdx, srcCol;
784 angular.forEach(grid.columnsProvider.columns,
786 if (col.name == grid.dragColumn) {
789 } else if (col.name == target) {
795 if (srcIdx < targetIdx) targetIdx--;
797 // move src column from old location to new location in
798 // the columns array, then force a page refresh
799 grid.columnsProvider.columns.splice(srcIdx, 1);
800 grid.columnsProvider.columns.splice(targetIdx, 0, srcCol);
804 // prepares a string for inclusion within a CSV document
805 // by escaping commas and quotes and removing newlines.
806 grid.csvDatum = function(str) {
809 str = str.replace(/\n/g, '');
810 if (str.match(/\,/) || str.match(/"/)) {
811 str = str.replace(/"/g, '""');
812 str = '"' + str + '"';
817 // sets the download file name and inserts the current CSV
818 // into a Blob URL for browser download.
819 $scope.generateCSVExportURL = function() {
820 $scope.gridColumnPickerIsOpen = false;
822 // let the file name describe the grid
823 $scope.csvExportFileName =
824 ($scope.mainLabel || grid.persistKey || 'eg_grid_data')
825 .replace(/\s+/g, '_') + '_' + $scope.page();
827 // toss the CSV into a Blob and update the export URL
828 var csv = grid.generateCSV();
829 var blob = new Blob([csv], {type : 'text/plain'});
830 $scope.csvExportURL =
831 ($window.URL || $window.webkitURL).createObjectURL(blob);
834 $scope.printCSV = function() {
835 $scope.gridColumnPickerIsOpen = false;
838 content : grid.generateCSV(),
839 content_type : 'text/plain'
843 // generates CSV for the currently visible grid contents
844 grid.generateCSV = function() {
846 var colCount = grid.columnsProvider.columns.length;
849 angular.forEach(grid.columnsProvider.columns,
851 if (!col.visible) return;
852 csvStr += grid.csvDatum(col.label);
857 csvStr = csvStr.replace(/,$/,'\n');
860 angular.forEach($scope.items, function(item) {
861 angular.forEach(grid.columnsProvider.columns,
863 if (!col.visible) return;
865 var val = grid.dataProvider.itemFieldValue(item, col);
866 // filtered value (dates, etc.)
867 val = $filter('egGridValueFilter')(val, col);
868 csvStr += grid.csvDatum(val);
872 csvStr = csvStr.replace(/,$/,'\n');
878 // Interpolate the value for column.linkpath within the context
879 // of the row item to generate the final link URL.
880 $scope.generateLinkPath = function(col, item) {
881 return egCore.strings.$replace(col.linkpath, {item : item});
884 // If a column provides its own HTML template, translate it,
885 // using the current item for the template scope.
886 // note: $sce is required to avoid security restrictions and
887 // is OK here, since the template comes directly from a
888 // local HTML template (not user input).
889 $scope.translateCellTemplate = function(col, item) {
890 var html = egCore.strings.$replace(col.template, {item : item});
891 return $sce.trustAsHtml(html);
894 $scope.collect = function() { grid.collect() }
896 // asks the dataProvider for a page of data
897 grid.collect = function() {
899 // avoid firing the collect if there is nothing to collect.
900 if (grid.selfManagedData && !grid.dataProvider.query) return;
902 if (grid.collecting) return; // avoid parallel collect()
903 grid.collecting = true;
905 console.debug('egGrid.collect() offset='
906 + grid.offset + '; limit=' + grid.limit);
908 // ensure all of our dropdowns are closed
909 // TODO: git rid of these and just use dropdown-toggle,
910 // which is more reliable.
911 $scope.gridColumnPickerIsOpen = false;
912 $scope.gridRowCountIsOpen = false;
913 $scope.gridPageSelectIsOpen = false;
916 $scope.selected = {};
917 grid.dataProvider.get(grid.offset, grid.limit).then(
919 if (grid.controls.allItemsRetrieved)
920 grid.controls.allItemsRetrieved();
925 $scope.items.push(item)
926 if (grid.controls.itemRetrieved)
927 grid.controls.itemRetrieved(item);
929 }).finally(function() {
930 console.debug('egGrid.collect() complete');
931 grid.collecting = false
941 * eg-grid-field : used for collecting custom field data from the templates.
942 * This directive does not direct display, it just passes data up to the
945 .directive('egGridField', function() {
950 name : '@', // required; unique name
951 path : '@', // optional; flesh path
952 ignore: '@', // optional; fields to ignore when path is a wildcard
953 label : '@', // optional; display label
954 flex : '@', // optional; default flex width
955 align : '@', // optional; default alignment, left/center/right
956 dateformat : '@', // optional: passed down to egGridValueFilter
958 // if a field is part of an IDL object, but we are unable to
959 // determine the class, because it's nested within a hash
960 // (i.e. we can't navigate directly to the object via the IDL),
961 // idlClass lets us specify the class. This is particularly
962 // useful for nested wildcard fields.
963 parentIdlClass : '@',
965 // optional: for non-IDL columns, specifying a datatype
966 // lets the caller control which display filter is used.
967 // datatype should match the standard IDL datatypes.
970 link : function(scope, element, attrs, egGridCtrl) {
972 // boolean fields are presented as value-less attributes
981 'required' // if set, always fetch data for this column
984 if (angular.isDefined(attrs[field]))
989 // any HTML content within the field is its custom template
990 var tmpl = element.html();
991 if (tmpl && !tmpl.match(/^\s*$/))
992 scope.template = tmpl
994 egGridCtrl.columnsProvider.add(scope);
1001 * eg-grid-action : used for specifying actions which may be applied
1002 * to items within the grid.
1004 .directive('egGridAction', function() {
1006 require : '^egGrid',
1010 group : '@', // Action group, ungrouped if not set
1011 label : '@', // Action label
1012 handler : '=', // Action function handler
1016 link : function(scope, element, attrs, egGridCtrl) {
1017 egGridCtrl.addAction({
1019 group : scope.group,
1020 label : scope.label,
1021 divider : scope.divider,
1022 handler : scope.handler
1029 .factory('egGridColumnsProvider', ['egCore', function(egCore) {
1031 function ColumnsProvider(args) {
1034 cols.stockVisible = [];
1035 cols.idlClass = args.idlClass;
1036 cols.defaultToHidden = args.defaultToHidden;
1037 cols.defaultToNoSort = args.defaultToNoSort;
1038 cols.defaultToNoMultiSort = args.defaultToNoMultiSort;
1040 // resets column width, visibility, and sort behavior
1041 // Visibility resets to the visibility settings defined in the
1042 // template (i.e. the original egGridField values).
1043 cols.reset = function() {
1044 angular.forEach(cols.columns, function(col) {
1048 if (cols.stockVisible.indexOf(col.name) > -1) {
1051 col.visible = false;
1056 // returns true if any columns are sortable
1057 cols.hasSortableColumn = function() {
1058 return cols.columns.filter(
1060 return col.sortable || col.multisortable;
1065 cols.showAllColumns = function() {
1066 angular.forEach(cols.columns, function(column) {
1067 column.visible = true;
1071 cols.hideAllColumns = function() {
1072 angular.forEach(cols.columns, function(col) {
1077 cols.indexOf = function(name) {
1078 for (var i = 0; i < cols.columns.length; i++) {
1079 if (cols.columns[i].name == name)
1085 cols.findColumn = function(name) {
1086 return cols.columns[cols.indexOf(name)];
1089 cols.compileAutoColumns = function() {
1090 var idl_class = egCore.idl.classes[cols.idlClass];
1093 idl_class.fields.sort(
1094 function(a, b) { return a.name < b.name ? -1 : 1 }),
1096 if (field.virtual) return;
1097 if (field.datatype == 'link' || field.datatype == 'org_unit') {
1098 // if the field is a link and the linked class has a
1099 // "selector" field specified, use the selector field
1100 // as the display field for the columns.
1101 // flattener will take care of the fleshing.
1102 if (field['class']) {
1103 var selector_field = egCore.idl.classes[field['class']].fields
1104 .filter(function(f) { return Boolean(f.selector) })[0];
1105 if (selector_field) {
1106 field.path = field.name + '.' + selector_field.selector;
1110 cols.add(field, true);
1115 // if a column definition has a path with a wildcard, create
1116 // columns for all non-virtual fields at the specified
1117 // position in the path.
1118 cols.expandPath = function(colSpec) {
1120 var ignoreList = [];
1122 ignoreList = colSpec.ignore.split(' ');
1124 var dotpath = colSpec.path.replace(/\.?\*$/,'');
1128 if (colSpec.parentIdlClass) {
1129 class_obj = egCore.idl.classes[colSpec.parentIdlClass];
1131 class_obj = egCore.idl.classes[cols.idlClass];
1134 if (!class_obj) return;
1136 console.debug('egGrid: auto dotpath is: ' + dotpath);
1137 var path_parts = dotpath.split(/\./);
1139 // find the IDL class definition for the last element in the
1140 // path before the .*
1141 // an empty path_parts means expand the root class
1143 for (var path_idx in path_parts) {
1144 var part = path_parts[path_idx];
1145 idl_field = class_obj.field_map[part];
1147 // unless we're at the end of the list, this field should
1148 // link to another class.
1149 if (idl_field && idl_field['class'] && (
1150 idl_field.datatype == 'link' ||
1151 idl_field.datatype == 'org_unit')) {
1152 class_obj = egCore.idl.classes[idl_field['class']];
1154 if (path_idx < (path_parts.length - 1)) {
1155 // we ran out of classes to hop through before
1156 // we ran out of path components
1157 console.error("egGrid: invalid IDL path: " + dotpath);
1164 angular.forEach(class_obj.fields, function(field) {
1166 // Only show wildcard fields where we have data to show
1167 // Virtual and un-fleshed links will not have any data.
1168 if (field.virtual ||
1169 (field.datatype == 'link' || field.datatype == 'org_unit') ||
1170 ignoreList.indexOf(field.name) > -1
1174 var col = cols.cloneFromScope(colSpec);
1175 col.path = (dotpath ? dotpath + '.' + field.name : field.name);
1176 console.debug('egGrid: field: ' +field.name + '; parent field: ' + js2JSON(idl_field));
1177 cols.add(col, false, true,
1178 {idl_parent : idl_field, idl_field : field, idl_class : class_obj});
1181 cols.columns = cols.columns.sort(
1183 if (a.explicit) return -1;
1184 if (b.explicit) return 1;
1185 if (a.idlclass && b.idlclass) {
1186 return a.idlclass < b.idlclass ? -1 : 1;
1187 return a.idlclass > b.idlclass ? 1 : -1;
1189 if (a.path && b.path) {
1190 return a.path < b.path ? -1 : 1;
1191 return a.path > b.path ? 1 : -1;
1194 return a.label < b.label ? -1 : 1;
1201 "egGrid: wildcard path does not resolve to an object: "
1206 // angular.clone(scopeObject) is not permittable. Manually copy
1207 // the fields over that we need (so the scope object can go away).
1208 cols.cloneFromScope = function(colSpec) {
1210 name : colSpec.name,
1211 label : colSpec.label,
1212 path : colSpec.path,
1213 align : colSpec.align || 'left',
1214 flex : Number(colSpec.flex) || 2,
1215 sort : Number(colSpec.sort) || 0,
1216 required : colSpec.required,
1217 linkpath : colSpec.linkpath,
1218 template : colSpec.template,
1219 visible : colSpec.visible,
1220 hidden : colSpec.hidden,
1221 datatype : colSpec.datatype,
1222 sortable : colSpec.sortable,
1223 nonsortable : colSpec.nonsortable,
1224 multisortable : colSpec.multisortable,
1225 nonmultisortable : colSpec.nonmultisortable,
1226 dateformat : colSpec.dateformat,
1227 parentIdlClass : colSpec.parentIdlClass
1232 // Add a column to the columns collection.
1233 // Columns may come from a slim eg-columns-field or
1234 // directly from the IDL.
1235 cols.add = function(colSpec, fromIDL, fromExpand, idl_info) {
1237 // First added column with the specified path takes precedence.
1238 // This allows for specific definitions followed by wildcard
1239 // definitions. If a match is found, back out.
1240 if (cols.columns.filter(function(c) {
1241 return (c.path == colSpec.path) })[0]) {
1242 console.debug('skipping pre-existing column ' + colSpec.path);
1246 var column = fromExpand ? colSpec : cols.cloneFromScope(colSpec);
1248 if (column.path && column.path.match(/\*$/))
1249 return cols.expandPath(colSpec);
1251 if (!fromExpand) column.explicit = true;
1253 if (!column.name) column.name = column.path;
1254 if (!column.path) column.path = column.name;
1256 if (column.visible || (!cols.defaultToHidden && !column.hidden))
1257 column.visible = true;
1259 if (column.sortable || (!cols.defaultToNoSort && !column.nonsortable))
1260 column.sortable = true;
1262 if (column.multisortable ||
1263 (!cols.defaultToNoMultiSort && !column.nonmultisortable))
1264 column.multisortable = true;
1266 cols.columns.push(column);
1268 // Track which columns are visible by default in case we
1269 // need to reset column visibility
1271 cols.stockVisible.push(column.name);
1273 if (fromIDL) return; // directly from egIDL. nothing left to do.
1275 // lookup the matching IDL field
1276 if (!idl_info && cols.idlClass)
1277 idl_info = cols.idlFieldFromPath(column.path);
1280 // column is not represented within the IDL
1281 column.adhoc = true;
1285 column.datatype = idl_info.idl_field.datatype;
1287 if (!column.label) {
1288 column.label = idl_info.idl_field.label || column.name;
1291 if (fromExpand && idl_info.idl_class) {
1292 column.idlclass = '';
1293 if (idl_info.idl_parent) {
1294 column.idlclass = idl_info.idl_parent.label || idl_info.idl_parent.name;
1296 column.idlclass += idl_info.idl_class.label || idl_info.idl_class.name;
1301 // finds the IDL field from the dotpath, using the columns
1302 // idlClass as the base.
1303 cols.idlFieldFromPath = function(dotpath) {
1304 var class_obj = egCore.idl.classes[cols.idlClass];
1305 var path_parts = dotpath.split(/\./);
1309 for (var path_idx in path_parts) {
1310 var part = path_parts[path_idx];
1311 idl_parent = idl_field;
1312 idl_field = class_obj.field_map[part];
1314 if (idl_field && idl_field['class'] && (
1315 idl_field.datatype == 'link' ||
1316 idl_field.datatype == 'org_unit')) {
1317 class_obj = egCore.idl.classes[idl_field['class']];
1319 // else, path is not in the IDL, which is fine
1322 if (!idl_field) return null;
1325 idl_parent: idl_parent,
1326 idl_field : idl_field,
1327 idl_class : class_obj
1333 instance : function(args) { return new ColumnsProvider(args) }
1339 * Generic data provider template class. This is basically an abstract
1340 * class factory service whose instances can be locally modified to
1341 * meet the needs of each individual grid.
1343 .factory('egGridDataProvider',
1344 ['$q','$timeout','$filter','egCore',
1345 function($q , $timeout , $filter , egCore) {
1347 function GridDataProvider(args) {
1348 var gridData = this;
1349 if (!args) args = {};
1352 gridData.get = args.get;
1353 gridData.query = args.query;
1354 gridData.idlClass = args.idlClass;
1355 gridData.columnsProvider = args.columnsProvider;
1357 // Delivers a stream of array data via promise.notify()
1358 // Useful for passing an array of data to egGrid.get()
1359 // If a count is provided, the array will be trimmed to
1360 // the range defined by count and offset
1361 gridData.arrayNotifier = function(arr, offset, count) {
1362 if (!arr || arr.length == 0) return $q.when();
1363 if (count) arr = arr.slice(offset, offset + count);
1364 var def = $q.defer();
1365 // promise notifications are only witnessed when delivered
1366 // after the caller has his hands on the promise object
1367 $timeout(function() {
1368 angular.forEach(arr, def.notify);
1374 // Calls the grid refresh function. Once instantiated, the
1375 // grid will replace this function with it's own refresh()
1376 gridData.refresh = function(noReset) { }
1378 if (!gridData.get) {
1379 // returns a promise whose notify() delivers items
1380 gridData.get = function(index, count) {
1381 console.error("egGridDataProvider.get() not implemented");
1385 // attempts a flat field lookup first. If the column is not
1386 // found on the top-level object, attempts a nested lookup
1387 // TODO: consider a caching layer to speed up template
1388 // rendering, particularly for nested objects?
1389 gridData.itemFieldValue = function(item, column) {
1390 if (column.name in item) {
1391 if (typeof item[column.name] == 'function') {
1392 return item[column.name]();
1394 return item[column.name];
1397 return gridData.nestedItemFieldValue(item, column);
1401 // TODO: deprecate me
1402 gridData.flatItemFieldValue = function(item, column) {
1403 console.warn('gridData.flatItemFieldValue deprecated; '
1404 + 'leave provider.itemFieldValue unset');
1405 return item[column.name];
1408 // given an object and a dot-separated path to a field,
1409 // extract the value of the field. The path can refer
1410 // to function names or object attributes. If the final
1411 // value is an IDL field, run the value through its
1412 // corresponding output filter.
1413 gridData.nestedItemFieldValue = function(obj, column) {
1414 if (obj === null || obj === undefined || obj === '') return '';
1415 if (!column.path) return obj;
1418 var parts = column.path.split('.');
1420 angular.forEach(parts, function(step, idx) {
1421 // object is not fleshed to the expected extent
1422 if (!obj || typeof obj != 'object') {
1427 var cls = obj.classname;
1428 if (cls && (class_obj = egCore.idl.classes[cls])) {
1429 idl_field = class_obj.field_map[step];
1430 obj = obj[step] ? obj[step]() : '';
1432 if (angular.isFunction(obj[step])) {
1440 // We found a nested IDL object which may or may not have
1441 // been configured as a top-level column. Grab the datatype.
1442 if (idl_field && !column.datatype)
1443 column.datatype = idl_field.datatype;
1445 if (obj === null || obj === undefined || obj === '') return '';
1451 instance : function(args) {
1452 return new GridDataProvider(args);
1459 // Factory service for egGridDataManager instances, which are
1460 // responsible for collecting flattened grid data.
1461 .factory('egGridFlatDataProvider',
1462 ['$q','egCore','egGridDataProvider',
1463 function($q , egCore , egGridDataProvider) {
1466 instance : function(args) {
1467 var provider = egGridDataProvider.instance(args);
1469 provider.get = function(offset, count) {
1471 // no query means no call
1472 if (!provider.query ||
1473 angular.equals(provider.query, {}))
1476 // find all of the currently visible columns
1477 var queryFields = {}
1478 angular.forEach(provider.columnsProvider.columns,
1480 // only query IDL-tracked columns
1481 if (!col.adhoc && (col.required || col.visible))
1482 queryFields[col.name] = col.path;
1486 return egCore.net.request(
1488 'open-ils.fielder.flattened_search',
1489 egCore.auth.token(), provider.idlClass,
1490 queryFields, provider.query,
1491 { sort : provider.sort,
1497 //provider.itemFieldValue = provider.flatItemFieldValue;
1504 .directive('egGridColumnDragSource', function() {
1507 require : '^egGrid',
1508 link : function(scope, element, attrs, egGridCtrl) {
1509 angular.element(element).attr('draggable', 'true');
1511 element.bind('dragstart', function(e) {
1512 egGridCtrl.dragColumn = attrs.column;
1513 egGridCtrl.dragType = attrs.dragType || 'move'; // or resize
1514 egGridCtrl.colResizeDir = 0;
1516 if (egGridCtrl.dragType == 'move') {
1517 // style the column getting moved
1518 angular.element(e.target).addClass(
1519 'eg-grid-column-move-handle-active');
1523 element.bind('dragend', function(e) {
1524 if (egGridCtrl.dragType == 'move') {
1525 angular.element(e.target).removeClass(
1526 'eg-grid-column-move-handle-active');
1533 .directive('egGridColumnDragDest', function() {
1536 require : '^egGrid',
1537 link : function(scope, element, attrs, egGridCtrl) {
1539 element.bind('dragover', function(e) { // required for drop
1540 e.stopPropagation();
1542 e.dataTransfer.dropEffect = 'move';
1544 if (egGridCtrl.colResizeDir == 0) return; // move
1546 var cols = egGridCtrl.columnsProvider;
1547 var srcCol = egGridCtrl.dragColumn;
1548 var srcColIdx = cols.indexOf(srcCol);
1550 if (egGridCtrl.colResizeDir == -1) {
1551 if (cols.indexOf(attrs.column) <= srcColIdx) {
1552 egGridCtrl.modifyColumnFlex(
1553 egGridCtrl.columnsProvider.findColumn(
1554 egGridCtrl.dragColumn), -1);
1555 if (cols.columns[srcColIdx+1]) {
1556 // source column shrinks by one, column to the
1557 // right grows by one.
1558 egGridCtrl.modifyColumnFlex(
1559 cols.columns[srcColIdx+1], 1);
1564 if (cols.indexOf(attrs.column) > srcColIdx) {
1565 egGridCtrl.modifyColumnFlex(
1566 egGridCtrl.columnsProvider.findColumn(
1567 egGridCtrl.dragColumn), 1);
1568 if (cols.columns[srcColIdx+1]) {
1569 // source column grows by one, column to the
1570 // right grows by one.
1571 egGridCtrl.modifyColumnFlex(
1572 cols.columns[srcColIdx+1], -1);
1580 element.bind('dragenter', function(e) {
1581 e.stopPropagation();
1583 if (egGridCtrl.dragType == 'move') {
1584 angular.element(e.target).addClass('eg-grid-col-hover');
1586 // resize grips are on the right side of each column.
1587 // dragenter will either occur on the source column
1588 // (dragging left) or the column to the right.
1589 if (egGridCtrl.colResizeDir == 0) {
1590 if (egGridCtrl.dragColumn == attrs.column) {
1591 egGridCtrl.colResizeDir = -1; // west
1593 egGridCtrl.colResizeDir = 1; // east
1599 element.bind('dragleave', function(e) {
1600 e.stopPropagation();
1602 if (egGridCtrl.dragType == 'move') {
1603 angular.element(e.target).removeClass('eg-grid-col-hover');
1607 element.bind('drop', function(e) {
1608 e.stopPropagation();
1610 egGridCtrl.colResizeDir = 0;
1611 if (egGridCtrl.dragType == 'move') {
1612 angular.element(e.target).removeClass('eg-grid-col-hover');
1613 egGridCtrl.onColumnDrop(attrs.column); // move the column
1620 .directive('egGridMenuItem', function() {
1623 require : '^egGrid',
1629 handler : '=', // onclick handler function
1630 divider : '=', // if true, show a divider only
1631 handlerData : '=', // if set, passed as second argument to handler
1632 disabled : '=', // function
1633 hidden : '=' // function
1635 link : function(scope, element, attrs, egGridCtrl) {
1636 egGridCtrl.addMenuItem({
1637 checkbox : scope.checkbox,
1638 checked : scope.checked ? true : false,
1639 label : scope.label,
1640 standalone : scope.standalone ? true : false,
1641 handler : scope.handler,
1642 divider : scope.divider,
1643 disabled : scope.disabled,
1644 hidden : scope.hidden,
1645 handlerData : scope.handlerData
1655 * Translates bare IDL object values into display values.
1656 * 1. Passes dates through the angular date filter
1657 * 2. Translates bools to Booleans so the browser can display translated
1658 * value. (Though we could manually translate instead..)
1659 * Others likely to follow...
1661 .filter('egGridValueFilter', ['$filter', function($filter) {
1662 return function(value, column) {
1663 switch(column.datatype) {
1666 // Browser will translate true/false for us
1668 case '1' : // legacy
1672 case '0' : // legacy
1675 // value may be null, '', etc.
1676 default : return '';
1679 // canned angular date filter FTW
1680 if (!column.dateformat)
1681 column.dateformat = 'shortDate';
1682 return $filter('date')(value, column.dateformat);
1684 return $filter('currency')(value);