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 // startSelected : init the grid with all rows selected by default
35 // -menu : don't show any menu buttons (or use space for them)
36 // -picker : don't show the column picker
37 // -pagination : don't show any pagination elements, and set
39 // -actions : don't show the actions dropdown
40 // -index : don't show the row index column (can't use "index"
41 // as the idField in this case)
42 // -display : columns are hidden by default
43 // -sort : columns are unsortable by default
44 // -multisort : sort priorities config disabled by default
45 // -multiselect : only one row at a time can be selected;
46 // choosing this also disables the checkbox
50 // optional primary grid label
53 // if true, use the IDL class label as the mainLabel
56 // optional context menu label
59 // Hash of control functions.
61 // These functions are defined by the calling scope and
62 // invoked as-is by the grid w/ the specified parameters.
64 // itemRetrieved : function(item) {}
65 // allItemsRetrieved : function() {}
68 // If defined, the grid will watch the return value from
69 // the function defined at watchQuery on each digest and
70 // re-draw the grid when query changes occur.
72 // watchQuery : function() { /* return grid query */ }
75 // These functions are defined by the grid and thus
76 // replace any values defined for these attributes from the
79 // activateItem : function(item) {}
80 // allItems : function(allItems) {}
81 // selectedItems : function(selected) {}
82 // selectItems : function(ids) {}
83 // setQuery : function(queryStruct) {} // causes reload
84 // setSort : function(sortSturct) {} // causes reload
88 // TODO: avoid hard-coded url
89 templateUrl : '/eg/staff/share/t_autogrid',
91 link : function(scope, element, attrs) {
92 // link() is called after page compilation, which means our
93 // eg-grid-field's have been parsed and loaded. Now it's
94 // safe to perform our initial page load.
96 // load auto fields after eg-grid-field's so they are not clobbered
97 scope.handleAutoFields();
100 scope.grid_element = element;
102 .find('.eg-grid-content-body')
103 .bind('contextmenu', scope.showActionContextMenu);
107 '$scope','$q','egCore','egGridFlatDataProvider','$location',
108 'egGridColumnsProvider','$filter','$window','$sce','$timeout',
109 function($scope, $q , egCore, egGridFlatDataProvider , $location,
110 egGridColumnsProvider , $filter , $window , $sce , $timeout) {
114 grid.init = function() {
117 $scope.showGridConf = false;
118 grid.totalCount = -1;
119 $scope.selected = {};
120 $scope.actionGroups = [{actions:[]}]; // Grouped actions for selected items
121 $scope.menuItems = []; // global actions
123 $scope.showIndex = ($scope.features.indexOf('-index') == -1);
125 $scope.startSelected = $scope.selectAll = ($scope.features.indexOf('startSelected') > -1);
126 $scope.showActions = ($scope.features.indexOf('-actions') == -1);
127 $scope.showPagination = ($scope.features.indexOf('-pagination') == -1);
128 $scope.showPicker = ($scope.features.indexOf('-picker') == -1);
130 $scope.showMenu = ($scope.features.indexOf('-menu') == -1);
132 // remove some unneeded values from the scope to reduce bloat
134 grid.idlClass = $scope.idlClass;
135 delete $scope.idlClass;
137 grid.persistKey = $scope.persistKey;
138 delete $scope.persistKey;
140 var stored_limit = 0;
141 if ($scope.showPagination) {
142 if (grid.persistKey) {
143 var stored_limit = Number(
144 egCore.hatch.getLocalItem('eg.grid.' + grid.persistKey + '.limit')
148 stored_limit = 10000; // maybe support "Inf"?
151 grid.limit = Number(stored_limit) || Number($scope.pageSize) || 25;
153 grid.indexField = $scope.idField;
154 delete $scope.idField;
156 grid.dataProvider = $scope.itemsProvider;
158 var features = ($scope.features) ?
159 $scope.features.split(',') : [];
160 delete $scope.features;
162 if (!grid.indexField && grid.idlClass)
163 grid.indexField = egCore.idl.classes[grid.idlClass].pkey;
165 grid.columnsProvider = egGridColumnsProvider.instance({
166 idlClass : grid.idlClass,
167 defaultToHidden : (features.indexOf('-display') > -1),
168 defaultToNoSort : (features.indexOf('-sort') > -1),
169 defaultToNoMultiSort : (features.indexOf('-multisort') > -1)
171 $scope.canMultiSelect = (features.indexOf('-multiselect') == -1);
173 $scope.handleAutoFields = function() {
174 if ($scope.autoFields) {
175 if (grid.autoLabel) {
177 egCore.idl.classes[grid.idlClass].label;
179 grid.columnsProvider.compileAutoColumns();
180 delete $scope.autoFields;
184 if (!grid.dataProvider) {
185 // no provider, um, provided.
186 // Use a flat data provider
188 grid.selfManagedData = true;
189 grid.dataProvider = egGridFlatDataProvider.instance({
190 indexField : grid.indexField,
191 idlClass : grid.idlClass,
192 columnsProvider : grid.columnsProvider,
197 $scope.itemFieldValue = grid.dataProvider.itemFieldValue;
198 $scope.indexValue = function(item) {
199 return grid.indexValue(item)
202 grid.applyControlFunctions();
204 grid.loadConfig().then(function() {
205 // link columns to scope after loadConfig(), since it
206 // replaces the columns array.
207 $scope.columns = grid.columnsProvider.columns;
210 // NOTE: grid.collect() is first called from link(), not here.
213 // link our control functions into the gridControls
214 // scope object so the caller can access them.
215 grid.applyControlFunctions = function() {
217 // we use some of these controls internally, so sett
218 // them up even if the caller doesn't request them.
219 var controls = $scope.gridControls || {};
221 // link in the control functions
222 controls.selectedItems = function() {
223 return grid.getSelectedItems()
226 controls.allItems = function() {
230 controls.selectItems = function(ids) {
232 $scope.selected = {};
233 angular.forEach(ids, function(i) {
234 $scope.selected[''+i] = true;
238 // if the caller provided a functional setQuery,
239 // extract the value before replacing it
240 if (controls.setQuery) {
241 grid.dataProvider.query =
245 controls.setQuery = function(query) {
246 grid.dataProvider.query = query;
250 if (controls.watchQuery) {
251 // capture the initial query value
252 grid.dataProvider.query = controls.watchQuery();
255 $scope.gridWatchQuery = controls.watchQuery;
256 $scope.$watch('gridWatchQuery()', function(newv) {
257 controls.setQuery(newv);
261 // if the caller provided a functional setSort
262 // extract the value before replacing it
263 grid.dataProvider.sort =
264 controls.setSort ? controls.setSort() : [];
266 controls.setSort = function(sort) {
270 controls.refresh = function(noReset) {
271 if (!noReset) grid.offset = 0;
275 controls.setLimit = function(limit,forget) {
276 if (!forget && grid.persistKey)
277 egCore.hatch.setLocalItem('eg.grid.' + grid.persistKey + '.limit', limit);
280 controls.getLimit = function() {
283 controls.setOffset = function(offset) {
284 grid.offset = offset;
286 controls.getOffset = function() {
290 grid.dataProvider.refresh = controls.refresh;
291 grid.controls = controls;
294 // If a menu item provides its own HTML template, translate it,
295 // using the menu item for the template scope.
296 // note: $sce is required to avoid security restrictions and
297 // is OK here, since the template comes directly from a
298 // local HTML template (not user input).
299 $scope.translateMenuItemTemplate = function(item) {
300 var html = egCore.strings.$replace(item.template, {item : item});
301 return $sce.trustAsHtml(html);
304 // add a new (global) grid menu item
305 grid.addMenuItem = function(item) {
306 $scope.menuItems.push(item);
307 var handler = item.handler;
308 item.handler = function() {
309 $scope.gridMenuIsOpen = false; // close menu
312 item.handlerData, grid.getSelectedItems());
317 // add a selected-items action
318 grid.addAction = function(act) {
320 $scope.actionGroups.forEach(function(g){
321 if (g.label === act.group) {
327 $scope.actionGroups.push({
334 // remove the stored column configuration preferenc, then recover
335 // the column visibility information from the initial page load.
336 $scope.resetColumns = function() {
337 $scope.gridColumnPickerIsOpen = false;
338 egCore.hatch.removeItem('eg.grid.' + grid.persistKey)
340 grid.columnsProvider.reset();
341 if (grid.selfManagedData) grid.collect();
345 $scope.showAllColumns = function() {
346 $scope.gridColumnPickerIsOpen = false;
347 grid.columnsProvider.showAllColumns();
348 if (grid.selfManagedData) grid.collect();
351 $scope.hideAllColumns = function() {
352 $scope.gridColumnPickerIsOpen = false;
353 grid.columnsProvider.hideAllColumns();
354 // note: no need to fetch new data if no columns are visible
357 $scope.toggleColumnVisibility = function(col) {
358 $scope.gridColumnPickerIsOpen = false;
359 col.visible = !col.visible;
361 // egGridFlatDataProvider only retrieves data to be
362 // displayed. When column visibility changes, it's
363 // necessary to fetch the newly visible column data.
364 if (grid.selfManagedData) grid.collect();
367 // save the columns configuration (position, sort, width) to
368 // eg.grid.<persist-key>
369 $scope.saveConfig = function() {
370 $scope.gridColumnPickerIsOpen = false;
372 if (!grid.persistKey) {
374 "Cannot save settings without a grid persist-key");
378 // only store information about visible columns.
379 var conf = grid.columnsProvider.columns.filter(
380 function(col) {return Boolean(col.visible) });
382 // now scrunch the data down to just the needed info
383 conf = conf.map(function(col) {
384 var c = {name : col.name}
385 // Apart from the name, only store non-default values.
386 // No need to store col.visible, since that's implicit
387 if (col.align != 'left') c.align = col.align;
388 if (col.flex != 2) c.flex = col.flex;
389 if (Number(col.sort)) c.sort = Number(c.sort);
393 egCore.hatch.setItem('eg.grid.' + grid.persistKey, conf)
395 // Save operation performed from the grid configuration UI.
396 // Hide the configuration UI and re-draw w/ sort applied
397 if ($scope.showGridConf)
398 $scope.toggleConfDisplay();
402 // load the columns configuration (position, sort, width) from
403 // eg.grid.<persist-key> and apply the loaded settings to the
404 // columns on our columnsProvider
405 grid.loadConfig = function() {
406 if (!grid.persistKey) return $q.when();
408 return egCore.hatch.getItem('eg.grid.' + grid.persistKey)
409 .then(function(conf) {
412 var columns = grid.columnsProvider.columns;
415 angular.forEach(conf, function(col) {
416 var grid_col = columns.filter(
417 function(c) {return c.name == col.name})[0];
420 // saved column does not match a column in the
421 // current grid. skip it.
425 grid_col.align = col.align || 'left';
426 grid_col.flex = col.flex || 2;
427 grid_col.sort = col.sort || 0;
428 // all saved columns are assumed to be true
429 grid_col.visible = true;
430 new_cols.push(grid_col);
433 // columns which are not expressed within the saved
434 // configuration are marked as non-visible and
435 // appended to the end of the new list of columns.
436 angular.forEach(columns, function(col) {
437 var found = conf.filter(
438 function(c) {return (c.name == col.name)})[0];
445 grid.columnsProvider.columns = new_cols;
450 $scope.onContextMenu = function($event) {
451 var col = angular.element($event.target).attr('column');
452 console.log('selected column ' + col);
455 $scope.page = function() {
456 return (grid.offset / grid.limit) + 1;
459 $scope.goToPage = function(page) {
461 if (angular.isNumber(page) && page > 0) {
462 grid.offset = (page - 1) * grid.limit;
467 $scope.offset = function(o) {
468 if (angular.isNumber(o))
473 $scope.limit = function(l) {
474 if (angular.isNumber(l)) {
476 egCore.hatch.setLocalItem('eg.grid.' + grid.persistKey + '.limit', l);
482 $scope.onFirstPage = function() {
483 return grid.offset == 0;
486 $scope.hasNextPage = function() {
487 // we have less data than requested, there must
488 // not be any more pages
489 if (grid.count() < grid.limit) return false;
491 // if the total count is not known, assume that a full
492 // page of data implies more pages are available.
493 if (grid.totalCount == -1) return true;
495 // we have a full page of data, but is there more?
496 return grid.totalCount > (grid.offset + grid.count());
499 $scope.incrementPage = function() {
500 grid.offset += grid.limit;
504 $scope.decrementPage = function() {
505 if (grid.offset < grid.limit) {
508 grid.offset -= grid.limit;
513 // number of items loaded for the current page of results
514 grid.count = function() {
515 return $scope.items.length;
518 // returns the unique identifier value for the provided item
519 // for internal consistency, indexValue is always coerced
521 grid.indexValue = function(item) {
522 if (angular.isObject(item)) {
524 if (angular.isFunction(item[grid.indexField]))
525 return ''+item[grid.indexField]();
526 return ''+item[grid.indexField]; // flat data
529 // passed a non-object; assume it's an index
533 // fires the hide handler function for a context action
534 $scope.actionHide = function(action) {
538 return action.hide(action);
541 // fires the disable handler function for a context action
542 $scope.actionDisable = function(action) {
543 if (!action.disabled) {
546 return action.disabled(action);
549 // fires the action handler function for a context action
550 $scope.actionLauncher = function(action) {
551 if (!action.handler) {
553 'No handler specified for "' + action.label + '"');
557 action.handler(grid.getSelectedItems());
559 console.error('Error executing handler for "'
560 + action.label + '" => ' + E + "\n" + E.stack);
563 if ($scope.action_context_showing) $scope.hideActionContextMenu();
568 $scope.hideActionContextMenu = function () {
569 $($scope.menu_dom).css({
571 width: $scope.action_context_width,
572 top: $scope.action_context_y,
573 left: $scope.action_context_x
575 $($scope.action_context_parent).append($scope.menu_dom);
576 $scope.action_context_oldy = $scope.action_context_oldx = 0;
577 $('body').unbind('click.remove_context_menu_'+$scope.action_context_index);
578 $scope.action_context_showing = false;
581 $scope.action_context_showing = false;
582 $scope.showActionContextMenu = function ($event) {
584 // Have to gather these here, instead of inside link()
585 if (!$scope.menu_dom) $scope.menu_dom = $($scope.grid_element).find('.grid-action-dropdown')[0];
586 if (!$scope.action_context_parent) $scope.action_context_parent = $($scope.menu_dom).parent();
588 if (!grid.getSelectedItems().length) // Nothing selected, fire the click event
589 $event.target.click();
591 if (!$scope.action_context_showing) {
592 $scope.action_context_width = $($scope.menu_dom).css('width');
593 $scope.action_context_y = $($scope.menu_dom).css('top');
594 $scope.action_context_x = $($scope.menu_dom).css('left');
595 $scope.action_context_showing = true;
596 $scope.action_context_index = Math.floor((Math.random() * 1000) + 1);
598 $('body').append($($scope.menu_dom));
599 $('body').bind('click.remove_context_menu_'+$scope.action_context_index, $scope.hideActionContextMenu);
602 $($scope.menu_dom).css({
604 width: $scope.action_context_width,
612 // returns the list of selected item objects
613 grid.getSelectedItems = function() {
614 return $scope.items.filter(
616 return Boolean($scope.selected[grid.indexValue(item)]);
621 grid.getItemByIndex = function(index) {
622 for (var i = 0; i < $scope.items.length; i++) {
623 var item = $scope.items[i];
624 if (grid.indexValue(item) == index)
629 // selects one row after deselecting all of the others
630 grid.selectOneItem = function(index) {
631 $scope.selected = {};
632 $scope.selected[index] = true;
635 // selects or deselects an item, without affecting the others.
636 // returns true if the item is selected; false if de-selected.
637 grid.toggleSelectOneItem = function(index) {
638 if ($scope.selected[index]) {
639 delete $scope.selected[index];
642 return $scope.selected[index] = true;
646 grid.selectAllItems = function() {
647 angular.forEach($scope.items, function(item) {
648 $scope.selected[grid.indexValue(item)] = true
652 $scope.$watch('selectAll', function(newVal) {
654 grid.selectAllItems();
656 $scope.selected = {};
660 // returns true if item1 appears in the list before item2;
661 // false otherwise. this is slightly more efficient that
662 // finding the position of each then comparing them.
663 // item1 / item2 may be an item or an item index
664 grid.itemComesBefore = function(itemOrIndex1, itemOrIndex2) {
665 var idx1 = grid.indexValue(itemOrIndex1);
666 var idx2 = grid.indexValue(itemOrIndex2);
668 // use for() for early exit
669 for (var i = 0; i < $scope.items.length; i++) {
670 var idx = grid.indexValue($scope.items[i]);
671 if (idx == idx1) return true;
672 if (idx == idx2) return false;
677 // 0-based position of item in the current data set
678 grid.indexOf = function(item) {
679 var idx = grid.indexValue(item);
680 for (var i = 0; i < $scope.items.length; i++) {
681 if (grid.indexValue($scope.items[i]) == idx)
687 grid.modifyColumnFlex = function(column, val) {
689 // prevent flex:0; use hiding instead
693 $scope.modifyColumnFlex = function(col, val) {
694 grid.modifyColumnFlex(col, val);
697 // handles click, control-click, and shift-click
698 $scope.handleRowClick = function($event, item) {
699 var index = grid.indexValue(item);
701 var origSelected = Object.keys($scope.selected);
703 if (!$scope.canMultiSelect) {
704 grid.selectOneItem(index);
705 grid.lastSelectedItemIndex = index;
709 if ($event.ctrlKey || $event.metaKey /* mac command */) {
711 if (grid.toggleSelectOneItem(index))
712 grid.lastSelectedItemIndex = index;
714 } else if ($event.shiftKey) {
717 if (!grid.lastSelectedItemIndex ||
718 index == grid.lastSelectedItemIndex) {
719 grid.selectOneItem(index);
720 grid.lastSelectedItemIndex = index;
724 var selecting = false;
725 var ascending = grid.itemComesBefore(
726 grid.lastSelectedItemIndex, item);
728 grid.indexOf(grid.lastSelectedItemIndex);
730 // update to new last-selected
731 grid.lastSelectedItemIndex = index;
733 // select each row between the last selected and
734 // currently selected items
736 startPos += ascending ? 1 : -1;
737 var curItem = $scope.items[startPos];
739 var curIdx = grid.indexValue(curItem);
740 $scope.selected[curIdx] = true;
741 if (curIdx == index) break; // all done
746 grid.selectOneItem(index);
747 grid.lastSelectedItemIndex = index;
751 // Builds a sort expression from column sort priorities.
752 // called on page load and any time the priorities are modified.
753 grid.compileSort = function() {
754 var sortList = grid.columnsProvider.columns.filter(
755 function(col) { return Number(col.sort) != 0 }
758 if (Math.abs(a.sort) < Math.abs(b.sort))
764 if (sortList.length) {
765 grid.dataProvider.sort = sortList.map(function(col) {
767 blob[col.name] = col.sort < 0 ? 'desc' : 'asc';
773 // builds a sort expression using a single column,
774 // toggling between ascending and descending sort.
775 $scope.quickSort = function(col_name) {
776 var sort = grid.dataProvider.sort;
777 if (sort && sort.length &&
778 sort[0] == col_name) {
780 blob[col_name] = 'desc';
781 grid.dataProvider.sort = [blob];
783 grid.dataProvider.sort = [col_name];
790 // show / hide the grid configuration row
791 $scope.toggleConfDisplay = function() {
792 if ($scope.showGridConf) {
793 $scope.showGridConf = false;
794 if (grid.columnsProvider.hasSortableColumn()) {
795 // only refresh the grid if the user has the
796 // ability to modify the sort priorities.
802 $scope.showGridConf = true;
805 $scope.gridColumnPickerIsOpen = false;
808 // called when a dragged column is dropped onto itself
809 // or any other column
810 grid.onColumnDrop = function(target) {
811 if (angular.isUndefined(target)) return;
812 if (target == grid.dragColumn) return;
813 var srcIdx, targetIdx, srcCol;
814 angular.forEach(grid.columnsProvider.columns,
816 if (col.name == grid.dragColumn) {
819 } else if (col.name == target) {
825 if (srcIdx < targetIdx) targetIdx--;
827 // move src column from old location to new location in
828 // the columns array, then force a page refresh
829 grid.columnsProvider.columns.splice(srcIdx, 1);
830 grid.columnsProvider.columns.splice(targetIdx, 0, srcCol);
834 // prepares a string for inclusion within a CSV document
835 // by escaping commas and quotes and removing newlines.
836 grid.csvDatum = function(str) {
839 str = str.replace(/\n/g, '');
840 if (str.match(/\,/) || str.match(/"/)) {
841 str = str.replace(/"/g, '""');
842 str = '"' + str + '"';
847 // sets the download file name and inserts the current CSV
848 // into a Blob URL for browser download.
849 $scope.generateCSVExportURL = function() {
850 $scope.gridColumnPickerIsOpen = false;
852 // let the file name describe the grid
853 $scope.csvExportFileName =
854 ($scope.mainLabel || grid.persistKey || 'eg_grid_data')
855 .replace(/\s+/g, '_') + '_' + $scope.page();
857 // toss the CSV into a Blob and update the export URL
858 var csv = grid.generateCSV();
859 var blob = new Blob([csv], {type : 'text/plain'});
860 $scope.csvExportURL =
861 ($window.URL || $window.webkitURL).createObjectURL(blob);
864 $scope.printCSV = function() {
865 $scope.gridColumnPickerIsOpen = false;
868 content : grid.generateCSV(),
869 content_type : 'text/plain'
873 // generates CSV for the currently visible grid contents
874 grid.generateCSV = function() {
876 var colCount = grid.columnsProvider.columns.length;
879 angular.forEach(grid.columnsProvider.columns,
881 if (!col.visible) return;
882 csvStr += grid.csvDatum(col.label);
887 csvStr = csvStr.replace(/,$/,'\n');
890 angular.forEach($scope.items, function(item) {
891 angular.forEach(grid.columnsProvider.columns,
893 if (!col.visible) return;
895 var val = grid.dataProvider.itemFieldValue(item, col);
896 // filtered value (dates, etc.)
897 val = $filter('egGridValueFilter')(val, col);
898 csvStr += grid.csvDatum(val);
902 csvStr = csvStr.replace(/,$/,'\n');
908 // Interpolate the value for column.linkpath within the context
909 // of the row item to generate the final link URL.
910 $scope.generateLinkPath = function(col, item) {
911 return egCore.strings.$replace(col.linkpath, {item : item});
914 // If a column provides its own HTML template, translate it,
915 // using the current item for the template scope.
916 // note: $sce is required to avoid security restrictions and
917 // is OK here, since the template comes directly from a
918 // local HTML template (not user input).
919 $scope.translateCellTemplate = function(col, item) {
920 var html = egCore.strings.$replace(col.template, {item : item});
921 return $sce.trustAsHtml(html);
924 $scope.collect = function() { grid.collect() }
926 // asks the dataProvider for a page of data
927 grid.collect = function() {
929 // avoid firing the collect if there is nothing to collect.
930 if (grid.selfManagedData && !grid.dataProvider.query) return;
932 if (grid.collecting) return; // avoid parallel collect()
933 grid.collecting = true;
935 console.debug('egGrid.collect() offset='
936 + grid.offset + '; limit=' + grid.limit);
938 // ensure all of our dropdowns are closed
939 // TODO: git rid of these and just use dropdown-toggle,
940 // which is more reliable.
941 $scope.gridColumnPickerIsOpen = false;
942 $scope.gridRowCountIsOpen = false;
943 $scope.gridPageSelectIsOpen = false;
946 $scope.selected = {};
947 grid.dataProvider.get(grid.offset, grid.limit).then(
949 if (grid.controls.allItemsRetrieved)
950 grid.controls.allItemsRetrieved();
955 $scope.items.push(item)
956 if (grid.controls.itemRetrieved)
957 grid.controls.itemRetrieved(item);
958 if ($scope.selectAll)
959 $scope.selected[grid.indexValue(item)] = true
961 }).finally(function() {
962 console.debug('egGrid.collect() complete');
963 grid.collecting = false
973 * eg-grid-field : used for collecting custom field data from the templates.
974 * This directive does not direct display, it just passes data up to the
977 .directive('egGridField', function() {
982 name : '@', // required; unique name
983 path : '@', // optional; flesh path
984 ignore: '@', // optional; fields to ignore when path is a wildcard
985 label : '@', // optional; display label
986 flex : '@', // optional; default flex width
987 align : '@', // optional; default alignment, left/center/right
988 dateformat : '@', // optional: passed down to egGridValueFilter
990 // if a field is part of an IDL object, but we are unable to
991 // determine the class, because it's nested within a hash
992 // (i.e. we can't navigate directly to the object via the IDL),
993 // idlClass lets us specify the class. This is particularly
994 // useful for nested wildcard fields.
995 parentIdlClass : '@',
997 // optional: for non-IDL columns, specifying a datatype
998 // lets the caller control which display filter is used.
999 // datatype should match the standard IDL datatypes.
1002 link : function(scope, element, attrs, egGridCtrl) {
1004 // boolean fields are presented as value-less attributes
1013 'required' // if set, always fetch data for this column
1016 if (angular.isDefined(attrs[field]))
1017 scope[field] = true;
1021 // any HTML content within the field is its custom template
1022 var tmpl = element.html();
1023 if (tmpl && !tmpl.match(/^\s*$/))
1024 scope.template = tmpl
1026 egGridCtrl.columnsProvider.add(scope);
1033 * eg-grid-action : used for specifying actions which may be applied
1034 * to items within the grid.
1036 .directive('egGridAction', function() {
1038 require : '^egGrid',
1042 group : '@', // Action group, ungrouped if not set
1043 label : '@', // Action label
1044 handler : '=', // Action function handler
1046 disabled : '=', // function
1049 link : function(scope, element, attrs, egGridCtrl) {
1050 egGridCtrl.addAction({
1052 group : scope.group,
1053 label : scope.label,
1054 divider : scope.divider,
1055 handler : scope.handler,
1056 disabled : scope.disabled,
1063 .factory('egGridColumnsProvider', ['egCore', function(egCore) {
1065 function ColumnsProvider(args) {
1068 cols.stockVisible = [];
1069 cols.idlClass = args.idlClass;
1070 cols.defaultToHidden = args.defaultToHidden;
1071 cols.defaultToNoSort = args.defaultToNoSort;
1072 cols.defaultToNoMultiSort = args.defaultToNoMultiSort;
1074 // resets column width, visibility, and sort behavior
1075 // Visibility resets to the visibility settings defined in the
1076 // template (i.e. the original egGridField values).
1077 cols.reset = function() {
1078 angular.forEach(cols.columns, function(col) {
1082 if (cols.stockVisible.indexOf(col.name) > -1) {
1085 col.visible = false;
1090 // returns true if any columns are sortable
1091 cols.hasSortableColumn = function() {
1092 return cols.columns.filter(
1094 return col.sortable || col.multisortable;
1099 cols.showAllColumns = function() {
1100 angular.forEach(cols.columns, function(column) {
1101 column.visible = true;
1105 cols.hideAllColumns = function() {
1106 angular.forEach(cols.columns, function(col) {
1111 cols.indexOf = function(name) {
1112 for (var i = 0; i < cols.columns.length; i++) {
1113 if (cols.columns[i].name == name)
1119 cols.findColumn = function(name) {
1120 return cols.columns[cols.indexOf(name)];
1123 cols.compileAutoColumns = function() {
1124 var idl_class = egCore.idl.classes[cols.idlClass];
1127 idl_class.fields.sort(
1128 function(a, b) { return a.name < b.name ? -1 : 1 }),
1130 if (field.virtual) return;
1131 if (field.datatype == 'link' || field.datatype == 'org_unit') {
1132 // if the field is a link and the linked class has a
1133 // "selector" field specified, use the selector field
1134 // as the display field for the columns.
1135 // flattener will take care of the fleshing.
1136 if (field['class']) {
1137 var selector_field = egCore.idl.classes[field['class']].fields
1138 .filter(function(f) { return Boolean(f.selector) })[0];
1139 if (selector_field) {
1140 field.path = field.name + '.' + selector_field.selector;
1144 cols.add(field, true);
1149 // if a column definition has a path with a wildcard, create
1150 // columns for all non-virtual fields at the specified
1151 // position in the path.
1152 cols.expandPath = function(colSpec) {
1154 var ignoreList = [];
1156 ignoreList = colSpec.ignore.split(' ');
1158 var dotpath = colSpec.path.replace(/\.?\*$/,'');
1162 if (colSpec.parentIdlClass) {
1163 class_obj = egCore.idl.classes[colSpec.parentIdlClass];
1165 class_obj = egCore.idl.classes[cols.idlClass];
1168 if (!class_obj) return;
1170 console.debug('egGrid: auto dotpath is: ' + dotpath);
1171 var path_parts = dotpath.split(/\./);
1173 // find the IDL class definition for the last element in the
1174 // path before the .*
1175 // an empty path_parts means expand the root class
1177 for (var path_idx in path_parts) {
1178 var part = path_parts[path_idx];
1179 idl_field = class_obj.field_map[part];
1181 // unless we're at the end of the list, this field should
1182 // link to another class.
1183 if (idl_field && idl_field['class'] && (
1184 idl_field.datatype == 'link' ||
1185 idl_field.datatype == 'org_unit')) {
1186 class_obj = egCore.idl.classes[idl_field['class']];
1188 if (path_idx < (path_parts.length - 1)) {
1189 // we ran out of classes to hop through before
1190 // we ran out of path components
1191 console.error("egGrid: invalid IDL path: " + dotpath);
1198 angular.forEach(class_obj.fields, function(field) {
1200 // Only show wildcard fields where we have data to show
1201 // Virtual and un-fleshed links will not have any data.
1202 if (field.virtual ||
1203 (field.datatype == 'link' || field.datatype == 'org_unit') ||
1204 ignoreList.indexOf(field.name) > -1
1208 var col = cols.cloneFromScope(colSpec);
1209 col.path = (dotpath ? dotpath + '.' + field.name : field.name);
1210 console.debug('egGrid: field: ' +field.name + '; parent field: ' + js2JSON(idl_field));
1211 cols.add(col, false, true,
1212 {idl_parent : idl_field, idl_field : field, idl_class : class_obj});
1215 cols.columns = cols.columns.sort(
1217 if (a.explicit) return -1;
1218 if (b.explicit) return 1;
1219 if (a.idlclass && b.idlclass) {
1220 return a.idlclass < b.idlclass ? -1 : 1;
1221 return a.idlclass > b.idlclass ? 1 : -1;
1223 if (a.path && b.path) {
1224 return a.path < b.path ? -1 : 1;
1225 return a.path > b.path ? 1 : -1;
1228 return a.label < b.label ? -1 : 1;
1235 "egGrid: wildcard path does not resolve to an object: "
1240 // angular.clone(scopeObject) is not permittable. Manually copy
1241 // the fields over that we need (so the scope object can go away).
1242 cols.cloneFromScope = function(colSpec) {
1244 name : colSpec.name,
1245 label : colSpec.label,
1246 path : colSpec.path,
1247 align : colSpec.align || 'left',
1248 flex : Number(colSpec.flex) || 2,
1249 sort : Number(colSpec.sort) || 0,
1250 required : colSpec.required,
1251 linkpath : colSpec.linkpath,
1252 template : colSpec.template,
1253 visible : colSpec.visible,
1254 hidden : colSpec.hidden,
1255 datatype : colSpec.datatype,
1256 sortable : colSpec.sortable,
1257 nonsortable : colSpec.nonsortable,
1258 multisortable : colSpec.multisortable,
1259 nonmultisortable : colSpec.nonmultisortable,
1260 dateformat : colSpec.dateformat,
1261 parentIdlClass : colSpec.parentIdlClass
1266 // Add a column to the columns collection.
1267 // Columns may come from a slim eg-columns-field or
1268 // directly from the IDL.
1269 cols.add = function(colSpec, fromIDL, fromExpand, idl_info) {
1271 // First added column with the specified path takes precedence.
1272 // This allows for specific definitions followed by wildcard
1273 // definitions. If a match is found, back out.
1274 if (cols.columns.filter(function(c) {
1275 return (c.path == colSpec.path) })[0]) {
1276 console.debug('skipping pre-existing column ' + colSpec.path);
1280 var column = fromExpand ? colSpec : cols.cloneFromScope(colSpec);
1282 if (column.path && column.path.match(/\*$/))
1283 return cols.expandPath(colSpec);
1285 if (!fromExpand) column.explicit = true;
1287 if (!column.name) column.name = column.path;
1288 if (!column.path) column.path = column.name;
1290 if (column.visible || (!cols.defaultToHidden && !column.hidden))
1291 column.visible = true;
1293 if (column.sortable || (!cols.defaultToNoSort && !column.nonsortable))
1294 column.sortable = true;
1296 if (column.multisortable ||
1297 (!cols.defaultToNoMultiSort && !column.nonmultisortable))
1298 column.multisortable = true;
1300 cols.columns.push(column);
1302 // Track which columns are visible by default in case we
1303 // need to reset column visibility
1305 cols.stockVisible.push(column.name);
1307 if (fromIDL) return; // directly from egIDL. nothing left to do.
1309 // lookup the matching IDL field
1310 if (!idl_info && cols.idlClass)
1311 idl_info = cols.idlFieldFromPath(column.path);
1314 // column is not represented within the IDL
1315 column.adhoc = true;
1319 column.datatype = idl_info.idl_field.datatype;
1321 if (!column.label) {
1322 column.label = idl_info.idl_field.label || column.name;
1325 if (fromExpand && idl_info.idl_class) {
1326 column.idlclass = '';
1327 if (idl_info.idl_parent) {
1328 column.idlclass = idl_info.idl_parent.label || idl_info.idl_parent.name;
1330 column.idlclass += idl_info.idl_class.label || idl_info.idl_class.name;
1335 // finds the IDL field from the dotpath, using the columns
1336 // idlClass as the base.
1337 cols.idlFieldFromPath = function(dotpath) {
1338 var class_obj = egCore.idl.classes[cols.idlClass];
1339 var path_parts = dotpath.split(/\./);
1343 for (var path_idx in path_parts) {
1344 var part = path_parts[path_idx];
1345 idl_parent = idl_field;
1346 idl_field = class_obj.field_map[part];
1348 if (idl_field && idl_field['class'] && (
1349 idl_field.datatype == 'link' ||
1350 idl_field.datatype == 'org_unit')) {
1351 class_obj = egCore.idl.classes[idl_field['class']];
1353 // else, path is not in the IDL, which is fine
1356 if (!idl_field) return null;
1359 idl_parent: idl_parent,
1360 idl_field : idl_field,
1361 idl_class : class_obj
1367 instance : function(args) { return new ColumnsProvider(args) }
1373 * Generic data provider template class. This is basically an abstract
1374 * class factory service whose instances can be locally modified to
1375 * meet the needs of each individual grid.
1377 .factory('egGridDataProvider',
1378 ['$q','$timeout','$filter','egCore',
1379 function($q , $timeout , $filter , egCore) {
1381 function GridDataProvider(args) {
1382 var gridData = this;
1383 if (!args) args = {};
1386 gridData.get = args.get;
1387 gridData.query = args.query;
1388 gridData.idlClass = args.idlClass;
1389 gridData.columnsProvider = args.columnsProvider;
1391 // Delivers a stream of array data via promise.notify()
1392 // Useful for passing an array of data to egGrid.get()
1393 // If a count is provided, the array will be trimmed to
1394 // the range defined by count and offset
1395 gridData.arrayNotifier = function(arr, offset, count) {
1396 if (!arr || arr.length == 0) return $q.when();
1397 if (count) arr = arr.slice(offset, offset + count);
1398 var def = $q.defer();
1399 // promise notifications are only witnessed when delivered
1400 // after the caller has his hands on the promise object
1401 $timeout(function() {
1402 angular.forEach(arr, def.notify);
1408 // Calls the grid refresh function. Once instantiated, the
1409 // grid will replace this function with it's own refresh()
1410 gridData.refresh = function(noReset) { }
1412 if (!gridData.get) {
1413 // returns a promise whose notify() delivers items
1414 gridData.get = function(index, count) {
1415 console.error("egGridDataProvider.get() not implemented");
1419 // attempts a flat field lookup first. If the column is not
1420 // found on the top-level object, attempts a nested lookup
1421 // TODO: consider a caching layer to speed up template
1422 // rendering, particularly for nested objects?
1423 gridData.itemFieldValue = function(item, column) {
1424 if (column.name in item) {
1425 if (typeof item[column.name] == 'function') {
1426 return item[column.name]();
1428 return item[column.name];
1431 return gridData.nestedItemFieldValue(item, column);
1435 // TODO: deprecate me
1436 gridData.flatItemFieldValue = function(item, column) {
1437 console.warn('gridData.flatItemFieldValue deprecated; '
1438 + 'leave provider.itemFieldValue unset');
1439 return item[column.name];
1442 // given an object and a dot-separated path to a field,
1443 // extract the value of the field. The path can refer
1444 // to function names or object attributes. If the final
1445 // value is an IDL field, run the value through its
1446 // corresponding output filter.
1447 gridData.nestedItemFieldValue = function(obj, column) {
1448 if (obj === null || obj === undefined || obj === '') return '';
1449 if (!column.path) return obj;
1452 var parts = column.path.split('.');
1454 angular.forEach(parts, function(step, idx) {
1455 // object is not fleshed to the expected extent
1456 if (!obj || typeof obj != 'object') {
1461 var cls = obj.classname;
1462 if (cls && (class_obj = egCore.idl.classes[cls])) {
1463 idl_field = class_obj.field_map[step];
1464 obj = obj[step] ? obj[step]() : '';
1466 if (angular.isFunction(obj[step])) {
1474 // We found a nested IDL object which may or may not have
1475 // been configured as a top-level column. Grab the datatype.
1476 if (idl_field && !column.datatype)
1477 column.datatype = idl_field.datatype;
1479 if (obj === null || obj === undefined || obj === '') return '';
1485 instance : function(args) {
1486 return new GridDataProvider(args);
1493 // Factory service for egGridDataManager instances, which are
1494 // responsible for collecting flattened grid data.
1495 .factory('egGridFlatDataProvider',
1496 ['$q','egCore','egGridDataProvider',
1497 function($q , egCore , egGridDataProvider) {
1500 instance : function(args) {
1501 var provider = egGridDataProvider.instance(args);
1503 provider.get = function(offset, count) {
1505 // no query means no call
1506 if (!provider.query ||
1507 angular.equals(provider.query, {}))
1510 // find all of the currently visible columns
1511 var queryFields = {}
1512 angular.forEach(provider.columnsProvider.columns,
1514 // only query IDL-tracked columns
1515 if (!col.adhoc && (col.required || col.visible))
1516 queryFields[col.name] = col.path;
1520 return egCore.net.request(
1522 'open-ils.fielder.flattened_search',
1523 egCore.auth.token(), provider.idlClass,
1524 queryFields, provider.query,
1525 { sort : provider.sort,
1531 //provider.itemFieldValue = provider.flatItemFieldValue;
1538 .directive('egGridColumnDragSource', function() {
1541 require : '^egGrid',
1542 link : function(scope, element, attrs, egGridCtrl) {
1543 angular.element(element).attr('draggable', 'true');
1545 element.bind('dragstart', function(e) {
1546 egGridCtrl.dragColumn = attrs.column;
1547 egGridCtrl.dragType = attrs.dragType || 'move'; // or resize
1548 egGridCtrl.colResizeDir = 0;
1550 if (egGridCtrl.dragType == 'move') {
1551 // style the column getting moved
1552 angular.element(e.target).addClass(
1553 'eg-grid-column-move-handle-active');
1557 element.bind('dragend', function(e) {
1558 if (egGridCtrl.dragType == 'move') {
1559 angular.element(e.target).removeClass(
1560 'eg-grid-column-move-handle-active');
1567 .directive('egGridColumnDragDest', function() {
1570 require : '^egGrid',
1571 link : function(scope, element, attrs, egGridCtrl) {
1573 element.bind('dragover', function(e) { // required for drop
1574 e.stopPropagation();
1576 e.dataTransfer.dropEffect = 'move';
1578 if (egGridCtrl.colResizeDir == 0) return; // move
1580 var cols = egGridCtrl.columnsProvider;
1581 var srcCol = egGridCtrl.dragColumn;
1582 var srcColIdx = cols.indexOf(srcCol);
1584 if (egGridCtrl.colResizeDir == -1) {
1585 if (cols.indexOf(attrs.column) <= srcColIdx) {
1586 egGridCtrl.modifyColumnFlex(
1587 egGridCtrl.columnsProvider.findColumn(
1588 egGridCtrl.dragColumn), -1);
1589 if (cols.columns[srcColIdx+1]) {
1590 // source column shrinks by one, column to the
1591 // right grows by one.
1592 egGridCtrl.modifyColumnFlex(
1593 cols.columns[srcColIdx+1], 1);
1598 if (cols.indexOf(attrs.column) > srcColIdx) {
1599 egGridCtrl.modifyColumnFlex(
1600 egGridCtrl.columnsProvider.findColumn(
1601 egGridCtrl.dragColumn), 1);
1602 if (cols.columns[srcColIdx+1]) {
1603 // source column grows by one, column to the
1604 // right grows by one.
1605 egGridCtrl.modifyColumnFlex(
1606 cols.columns[srcColIdx+1], -1);
1614 element.bind('dragenter', function(e) {
1615 e.stopPropagation();
1617 if (egGridCtrl.dragType == 'move') {
1618 angular.element(e.target).addClass('eg-grid-col-hover');
1620 // resize grips are on the right side of each column.
1621 // dragenter will either occur on the source column
1622 // (dragging left) or the column to the right.
1623 if (egGridCtrl.colResizeDir == 0) {
1624 if (egGridCtrl.dragColumn == attrs.column) {
1625 egGridCtrl.colResizeDir = -1; // west
1627 egGridCtrl.colResizeDir = 1; // east
1633 element.bind('dragleave', function(e) {
1634 e.stopPropagation();
1636 if (egGridCtrl.dragType == 'move') {
1637 angular.element(e.target).removeClass('eg-grid-col-hover');
1641 element.bind('drop', function(e) {
1642 e.stopPropagation();
1644 egGridCtrl.colResizeDir = 0;
1645 if (egGridCtrl.dragType == 'move') {
1646 angular.element(e.target).removeClass('eg-grid-col-hover');
1647 egGridCtrl.onColumnDrop(attrs.column); // move the column
1654 .directive('egGridMenuItem', function() {
1657 require : '^egGrid',
1663 handler : '=', // onclick handler function
1664 divider : '=', // if true, show a divider only
1665 handlerData : '=', // if set, passed as second argument to handler
1666 disabled : '=', // function
1667 hidden : '=' // function
1669 link : function(scope, element, attrs, egGridCtrl) {
1670 egGridCtrl.addMenuItem({
1671 checkbox : scope.checkbox,
1672 checked : scope.checked ? true : false,
1673 label : scope.label,
1674 standalone : scope.standalone ? true : false,
1675 handler : scope.handler,
1676 divider : scope.divider,
1677 disabled : scope.disabled,
1678 hidden : scope.hidden,
1679 handlerData : scope.handlerData
1689 * Translates bare IDL object values into display values.
1690 * 1. Passes dates through the angular date filter
1691 * 2. Translates bools to Booleans so the browser can display translated
1692 * value. (Though we could manually translate instead..)
1693 * Others likely to follow...
1695 .filter('egGridValueFilter', ['$filter', function($filter) {
1696 return function(value, column) {
1697 switch(column.datatype) {
1700 // Browser will translate true/false for us
1702 case '1' : // legacy
1706 case '0' : // legacy
1709 // value may be null, '', etc.
1710 default : return '';
1713 // canned angular date filter FTW
1714 if (!column.dateformat)
1715 column.dateformat = 'shortDate';
1716 return $filter('date')(value, column.dateformat);
1718 return $filter('currency')(value);