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 // Reference to externally provided item-selection handler
35 // Reference to externally provided after-item-selection handler
38 // comma-separated list of supported or disabled grid features
39 // supported features:
40 // startSelected : init the grid with all rows selected by default
41 // allowAll : add an "All" option to row count (really 10000)
42 // -menu : don't show any menu buttons (or use space for them)
43 // -picker : don't show the column picker
44 // -pagination : don't show any pagination elements, and set
46 // -actions : don't show the actions dropdown
47 // -index : don't show the row index column (can't use "index"
48 // as the idField in this case)
49 // -display : columns are hidden by default
50 // -sort : columns are unsortable by default
51 // -multisort : sort priorities config disabled by default
52 // -multiselect : only one row at a time can be selected;
53 // choosing this also disables the checkbox
57 // optional primary grid label
60 // if true, use the IDL class label as the mainLabel
63 // optional context menu label
66 dateformat : '@', // optional: passed down to egGridValueFilter
68 // Hash of control functions.
70 // These functions are defined by the calling scope and
71 // invoked as-is by the grid w/ the specified parameters.
73 // collectStarted : function() {}
74 // itemRetrieved : function(item) {}
75 // allItemsRetrieved : function() {}
78 // If defined, the grid will watch the return value from
79 // the function defined at watchQuery on each digest and
80 // re-draw the grid when query changes occur.
82 // watchQuery : function() { /* return grid query */ }
85 // These functions are defined by the grid and thus
86 // replace any values defined for these attributes from the
89 // activateItem : function(item) {}
90 // allItems : function(allItems) {}
91 // selectedItems : function(selected) {}
92 // selectItems : function(ids) {}
93 // setQuery : function(queryStruct) {} // causes reload
94 // setSort : function(sortSturct) {} // causes reload
98 // TODO: avoid hard-coded url
99 templateUrl : '/eg/staff/share/t_autogrid',
101 link : function(scope, element, attrs) {
102 // link() is called after page compilation, which means our
103 // eg-grid-field's have been parsed and loaded. Now it's
104 // safe to perform our initial page load.
106 // load auto fields after eg-grid-field's so they are not clobbered
107 scope.handleAutoFields();
110 scope.grid_element = element;
112 .find('.eg-grid-content-body')
113 .bind('contextmenu', scope.showActionContextMenu);
117 '$scope','$q','egCore','egGridFlatDataProvider','$location',
118 'egGridColumnsProvider','$filter','$window','$sce','$timeout',
119 function($scope, $q , egCore, egGridFlatDataProvider , $location,
120 egGridColumnsProvider , $filter , $window , $sce , $timeout) {
124 grid.init = function() {
127 $scope.showGridConf = false;
128 grid.totalCount = -1;
129 $scope.selected = {};
130 $scope.actionGroups = [{actions:[]}]; // Grouped actions for selected items
131 $scope.menuItems = []; // global actions
133 // returns true if any rows are selected.
134 $scope.hasSelected = function() {
135 return grid.getSelectedItems().length > 0 };
137 var features = ($scope.features) ?
138 $scope.features.split(',') : [];
139 delete $scope.features;
141 $scope.showIndex = (features.indexOf('-index') == -1);
143 $scope.allowAll = (features.indexOf('allowAll') > -1);
144 $scope.startSelected = $scope.selectAll = (features.indexOf('startSelected') > -1);
145 $scope.showActions = (features.indexOf('-actions') == -1);
146 $scope.showPagination = (features.indexOf('-pagination') == -1);
147 $scope.showPicker = (features.indexOf('-picker') == -1);
149 $scope.showMenu = (features.indexOf('-menu') == -1);
151 // remove some unneeded values from the scope to reduce bloat
153 grid.idlClass = $scope.idlClass;
154 delete $scope.idlClass;
156 grid.persistKey = $scope.persistKey;
157 delete $scope.persistKey;
159 var stored_limit = 0;
160 if ($scope.showPagination) {
161 if (grid.persistKey) {
162 var stored_limit = Number(
163 egCore.hatch.getLocalItem('eg.grid.' + grid.persistKey + '.limit')
167 stored_limit = 10000; // maybe support "Inf"?
170 grid.limit = Number(stored_limit) || Number($scope.pageSize) || 25;
172 grid.indexField = $scope.idField;
173 delete $scope.idField;
175 grid.dataProvider = $scope.itemsProvider;
177 if (!grid.indexField && grid.idlClass)
178 grid.indexField = egCore.idl.classes[grid.idlClass].pkey;
180 grid.columnsProvider = egGridColumnsProvider.instance({
181 idlClass : grid.idlClass,
182 defaultToHidden : (features.indexOf('-display') > -1),
183 defaultToNoSort : (features.indexOf('-sort') > -1),
184 defaultToNoMultiSort : (features.indexOf('-multisort') > -1),
185 defaultDateFormat : $scope.dateformat
187 $scope.canMultiSelect = (features.indexOf('-multiselect') == -1);
189 $scope.handleAutoFields = function() {
190 if ($scope.autoFields) {
191 if (grid.autoLabel) {
193 egCore.idl.classes[grid.idlClass].label;
195 grid.columnsProvider.compileAutoColumns();
196 delete $scope.autoFields;
200 if (!grid.dataProvider) {
201 // no provider, um, provided.
202 // Use a flat data provider
204 grid.selfManagedData = true;
205 grid.dataProvider = egGridFlatDataProvider.instance({
206 indexField : grid.indexField,
207 idlClass : grid.idlClass,
208 columnsProvider : grid.columnsProvider,
213 $scope.itemFieldValue = grid.dataProvider.itemFieldValue;
214 $scope.indexValue = function(item) {
215 return grid.indexValue(item)
218 grid.applyControlFunctions();
220 grid.loadConfig().then(function() {
221 // link columns to scope after loadConfig(), since it
222 // replaces the columns array.
223 $scope.columns = grid.columnsProvider.columns;
226 // NOTE: grid.collect() is first called from link(), not here.
229 // link our control functions into the gridControls
230 // scope object so the caller can access them.
231 grid.applyControlFunctions = function() {
233 // we use some of these controls internally, so sett
234 // them up even if the caller doesn't request them.
235 var controls = $scope.gridControls || {};
237 controls.columnMap = function() {
239 angular.forEach(grid.columnsProvider.columns, function (c) {
245 controls.columnsProvider = function() {
246 return grid.columnsProvider;
249 // link in the control functions
250 controls.selectedItems = function() {
251 return grid.getSelectedItems()
254 controls.allItems = function() {
258 controls.selectItems = function(ids) {
260 $scope.selected = {};
261 angular.forEach(ids, function(i) {
262 $scope.selected[''+i] = true;
266 // if the caller provided a functional setQuery,
267 // extract the value before replacing it
268 if (controls.setQuery) {
269 grid.dataProvider.query =
273 controls.setQuery = function(query) {
274 grid.dataProvider.query = query;
278 if (controls.watchQuery) {
279 // capture the initial query value
280 grid.dataProvider.query = controls.watchQuery();
283 $scope.gridWatchQuery = controls.watchQuery;
284 $scope.$watch('gridWatchQuery()', function(newv) {
285 controls.setQuery(newv);
289 // if the caller provided a functional setSort
290 // extract the value before replacing it
291 grid.dataProvider.sort =
292 controls.setSort ? controls.setSort() : [];
294 controls.setSort = function(sort) {
298 controls.refresh = function(noReset) {
299 if (!noReset) grid.offset = 0;
303 controls.setLimit = function(limit,forget) {
304 if (!forget && grid.persistKey)
305 egCore.hatch.setLocalItem('eg.grid.' + grid.persistKey + '.limit', limit);
308 controls.getLimit = function() {
311 controls.setOffset = function(offset) {
312 grid.offset = offset;
314 controls.getOffset = function() {
318 controls.saveConfig = function () {
319 return $scope.saveConfig();
322 grid.dataProvider.refresh = controls.refresh;
323 grid.controls = controls;
326 // If a menu item provides its own HTML template, translate it,
327 // using the menu item for the template scope.
328 // note: $sce is required to avoid security restrictions and
329 // is OK here, since the template comes directly from a
330 // local HTML template (not user input).
331 $scope.translateMenuItemTemplate = function(item) {
332 var html = egCore.strings.$replace(item.template, {item : item});
333 return $sce.trustAsHtml(html);
336 // add a new (global) grid menu item
337 grid.addMenuItem = function(item) {
338 $scope.menuItems.push(item);
339 var handler = item.handler;
340 item.handler = function() {
341 $scope.gridMenuIsOpen = false; // close menu
344 item.handlerData, grid.getSelectedItems());
349 // add a selected-items action
350 grid.addAction = function(act) {
352 $scope.actionGroups.forEach(function(g){
353 if (g.label === act.group) {
359 $scope.actionGroups.push({
366 // remove the stored column configuration preferenc, then recover
367 // the column visibility information from the initial page load.
368 $scope.resetColumns = function() {
369 $scope.gridColumnPickerIsOpen = false;
370 egCore.hatch.removeItem('eg.grid.' + grid.persistKey)
372 grid.columnsProvider.reset();
373 if (grid.selfManagedData) grid.collect();
377 $scope.showAllColumns = function() {
378 $scope.gridColumnPickerIsOpen = false;
379 grid.columnsProvider.showAllColumns();
380 if (grid.selfManagedData) grid.collect();
383 $scope.hideAllColumns = function() {
384 $scope.gridColumnPickerIsOpen = false;
385 grid.columnsProvider.hideAllColumns();
386 // note: no need to fetch new data if no columns are visible
389 $scope.toggleColumnVisibility = function(col) {
390 $scope.gridColumnPickerIsOpen = false;
391 col.visible = !col.visible;
393 // egGridFlatDataProvider only retrieves data to be
394 // displayed. When column visibility changes, it's
395 // necessary to fetch the newly visible column data.
396 if (grid.selfManagedData) grid.collect();
399 // save the columns configuration (position, sort, width) to
400 // eg.grid.<persist-key>
401 $scope.saveConfig = function() {
402 $scope.gridColumnPickerIsOpen = false;
404 if (!grid.persistKey) {
406 "Cannot save settings without a grid persist-key");
410 // only store information about visible columns.
411 var conf = grid.columnsProvider.columns.filter(
412 function(col) {return Boolean(col.visible) });
414 // now scrunch the data down to just the needed info
415 conf = conf.map(function(col) {
416 var c = {name : col.name}
417 // Apart from the name, only store non-default values.
418 // No need to store col.visible, since that's implicit
419 if (col.align != 'left') c.align = col.align;
420 if (col.flex != 2) c.flex = col.flex;
421 if (Number(col.sort)) c.sort = Number(c.sort);
425 egCore.hatch.setItem('eg.grid.' + grid.persistKey, conf)
427 // Save operation performed from the grid configuration UI.
428 // Hide the configuration UI and re-draw w/ sort applied
429 if ($scope.showGridConf)
430 $scope.toggleConfDisplay();
435 // load the columns configuration (position, sort, width) from
436 // eg.grid.<persist-key> and apply the loaded settings to the
437 // columns on our columnsProvider
438 grid.loadConfig = function() {
439 if (!grid.persistKey) return $q.when();
441 return egCore.hatch.getItem('eg.grid.' + grid.persistKey)
442 .then(function(conf) {
445 var columns = grid.columnsProvider.columns;
448 angular.forEach(conf, function(col) {
449 var grid_col = columns.filter(
450 function(c) {return c.name == col.name})[0];
453 // saved column does not match a column in the
454 // current grid. skip it.
458 grid_col.align = col.align || 'left';
459 grid_col.flex = col.flex || 2;
460 grid_col.sort = col.sort || 0;
461 // all saved columns are assumed to be true
462 grid_col.visible = true;
464 .filter(function (c) {
465 return c.name == grid_col.name;
468 new_cols.push(grid_col);
471 // columns which are not expressed within the saved
472 // configuration are marked as non-visible and
473 // appended to the end of the new list of columns.
474 angular.forEach(columns, function(col) {
475 var found = conf.filter(
476 function(c) {return (c.name == col.name)})[0];
483 grid.columnsProvider.columns = new_cols;
489 $scope.onContextMenu = function($event) {
490 var col = angular.element($event.target).attr('column');
491 console.log('selected column ' + col);
494 $scope.page = function() {
495 return (grid.offset / grid.limit) + 1;
498 $scope.goToPage = function(page) {
500 if (angular.isNumber(page) && page > 0) {
501 grid.offset = (page - 1) * grid.limit;
506 $scope.offset = function(o) {
507 if (angular.isNumber(o))
512 $scope.limit = function(l) {
513 if (angular.isNumber(l)) {
515 egCore.hatch.setLocalItem('eg.grid.' + grid.persistKey + '.limit', l);
521 $scope.onFirstPage = function() {
522 return grid.offset == 0;
525 $scope.hasNextPage = function() {
526 // we have less data than requested, there must
527 // not be any more pages
528 if (grid.count() < grid.limit) return false;
530 // if the total count is not known, assume that a full
531 // page of data implies more pages are available.
532 if (grid.totalCount == -1) return true;
534 // we have a full page of data, but is there more?
535 return grid.totalCount > (grid.offset + grid.count());
538 $scope.incrementPage = function() {
539 grid.offset += grid.limit;
543 $scope.decrementPage = function() {
544 if (grid.offset < grid.limit) {
547 grid.offset -= grid.limit;
552 // number of items loaded for the current page of results
553 grid.count = function() {
554 return $scope.items.length;
557 // returns the unique identifier value for the provided item
558 // for internal consistency, indexValue is always coerced
560 grid.indexValue = function(item) {
561 if (angular.isObject(item)) {
563 if (angular.isFunction(item[grid.indexField]))
564 return ''+item[grid.indexField]();
565 return ''+item[grid.indexField]; // flat data
568 // passed a non-object; assume it's an index
572 // fires the hide handler function for a context action
573 $scope.actionHide = function(action) {
574 if (typeof action.hide == 'undefined') {
577 if (angular.isFunction(action.hide))
578 return action.hide(action);
582 // fires the disable handler function for a context action
583 $scope.actionDisable = function(action) {
584 if (typeof action.disabled == 'undefined') {
587 if (angular.isFunction(action.disabled))
588 return action.disabled(action);
589 return action.disabled;
592 // fires the action handler function for a context action
593 $scope.actionLauncher = function(action) {
594 if (!action.handler) {
596 'No handler specified for "' + action.label + '"');
600 action.handler(grid.getSelectedItems());
602 console.error('Error executing handler for "'
603 + action.label + '" => ' + E + "\n" + E.stack);
606 if ($scope.action_context_showing) $scope.hideActionContextMenu();
611 $scope.hideActionContextMenu = function () {
612 $($scope.menu_dom).css({
614 width: $scope.action_context_width,
615 top: $scope.action_context_y,
616 left: $scope.action_context_x
618 $($scope.action_context_parent).append($scope.menu_dom);
619 $scope.action_context_oldy = $scope.action_context_oldx = 0;
620 $('body').unbind('click.remove_context_menu_'+$scope.action_context_index);
621 $scope.action_context_showing = false;
624 $scope.action_context_showing = false;
625 $scope.showActionContextMenu = function ($event) {
627 // Have to gather these here, instead of inside link()
628 if (!$scope.menu_dom) $scope.menu_dom = $($scope.grid_element).find('.grid-action-dropdown')[0];
629 if (!$scope.action_context_parent) $scope.action_context_parent = $($scope.menu_dom).parent();
631 if (!grid.getSelectedItems().length) // Nothing selected, fire the click event
632 $event.target.click();
634 if (!$scope.action_context_showing) {
635 $scope.action_context_width = $($scope.menu_dom).css('width');
636 $scope.action_context_y = $($scope.menu_dom).css('top');
637 $scope.action_context_x = $($scope.menu_dom).css('left');
638 $scope.action_context_showing = true;
639 $scope.action_context_index = Math.floor((Math.random() * 1000) + 1);
641 $('body').append($($scope.menu_dom));
642 $('body').bind('click.remove_context_menu_'+$scope.action_context_index, $scope.hideActionContextMenu);
645 $($scope.menu_dom).css({
647 width: $scope.action_context_width,
655 // returns the list of selected item objects
656 grid.getSelectedItems = function() {
657 return $scope.items.filter(
659 return Boolean($scope.selected[grid.indexValue(item)]);
664 grid.getItemByIndex = function(index) {
665 for (var i = 0; i < $scope.items.length; i++) {
666 var item = $scope.items[i];
667 if (grid.indexValue(item) == index)
672 // selects one row after deselecting all of the others
673 grid.selectOneItem = function(index) {
674 $scope.selected = {};
675 $scope.selected[index] = true;
678 // selects or deselects an item, without affecting the others.
679 // returns true if the item is selected; false if de-selected.
680 // we overwrite the object so that we can watch $scope.selected
681 grid.toggleSelectOneItem = function(index) {
682 if ($scope.selected[index]) {
683 delete $scope.selected[index];
684 $scope.selected = angular.copy($scope.selected);
687 $scope.selected[index] = true;
688 $scope.selected = angular.copy($scope.selected);
693 $scope.updateSelected = function () {
694 return $scope.selected = angular.copy($scope.selected);
697 grid.selectAllItems = function() {
698 angular.forEach($scope.items, function(item) {
699 $scope.selected[grid.indexValue(item)] = true
701 $scope.selected = angular.copy($scope.selected);
704 $scope.$watch('selectAll', function(newVal) {
706 grid.selectAllItems();
708 $scope.selected = {};
712 if ($scope.onSelect) {
713 $scope.$watch('selected', function(newVal) {
714 $scope.onSelect(grid.getSelectedItems());
715 if ($scope.afterSelect) $scope.afterSelect();
719 // returns true if item1 appears in the list before item2;
720 // false otherwise. this is slightly more efficient that
721 // finding the position of each then comparing them.
722 // item1 / item2 may be an item or an item index
723 grid.itemComesBefore = function(itemOrIndex1, itemOrIndex2) {
724 var idx1 = grid.indexValue(itemOrIndex1);
725 var idx2 = grid.indexValue(itemOrIndex2);
727 // use for() for early exit
728 for (var i = 0; i < $scope.items.length; i++) {
729 var idx = grid.indexValue($scope.items[i]);
730 if (idx == idx1) return true;
731 if (idx == idx2) return false;
736 // 0-based position of item in the current data set
737 grid.indexOf = function(item) {
738 var idx = grid.indexValue(item);
739 for (var i = 0; i < $scope.items.length; i++) {
740 if (grid.indexValue($scope.items[i]) == idx)
746 grid.modifyColumnFlex = function(column, val) {
748 // prevent flex:0; use hiding instead
752 $scope.modifyColumnFlex = function(col, val) {
753 $scope.lastModColumn = col.name;
754 grid.modifyColumnFlex(col, val);
757 grid.modifyColumnPos = function(col, diff) {
758 var srcIdx, targetIdx;
759 angular.forEach(grid.columnsProvider.columns,
760 function(c, i) { if (c.name == col.name) srcIdx = i });
762 targetIdx = srcIdx + diff;
765 } else if (targetIdx >= grid.columnsProvider.columns.length) {
766 // Target index follows the last visible column.
768 angular.forEach(grid.columnsProvider.columns,
769 function(column, idx) {
770 if (column.visible) lastVisible = idx;
773 targetIdx = lastVisible + 1;
776 // Splice column out of old position, insert at new position.
777 grid.columnsProvider.columns.splice(srcIdx, 1);
778 grid.columnsProvider.columns.splice(targetIdx, 0, col);
781 $scope.modifyColumnPos = function(col, diff) {
782 $scope.lastModColumn = col.name;
783 return grid.modifyColumnPos(col, diff);
787 // handles click, control-click, and shift-click
788 $scope.handleRowClick = function($event, item) {
789 var index = grid.indexValue(item);
791 var origSelected = Object.keys($scope.selected);
793 if (!$scope.canMultiSelect) {
794 grid.selectOneItem(index);
795 grid.lastSelectedItemIndex = index;
799 if ($event.ctrlKey || $event.metaKey /* mac command */) {
801 if (grid.toggleSelectOneItem(index))
802 grid.lastSelectedItemIndex = index;
804 } else if ($event.shiftKey) {
807 if (!grid.lastSelectedItemIndex ||
808 index == grid.lastSelectedItemIndex) {
809 grid.selectOneItem(index);
810 grid.lastSelectedItemIndex = index;
814 var selecting = false;
815 var ascending = grid.itemComesBefore(
816 grid.lastSelectedItemIndex, item);
818 grid.indexOf(grid.lastSelectedItemIndex);
820 // update to new last-selected
821 grid.lastSelectedItemIndex = index;
823 // select each row between the last selected and
824 // currently selected items
826 startPos += ascending ? 1 : -1;
827 var curItem = $scope.items[startPos];
829 var curIdx = grid.indexValue(curItem);
830 $scope.selected[curIdx] = true;
831 if (curIdx == index) break; // all done
833 $scope.selected = angular.copy($scope.selected);
837 grid.selectOneItem(index);
838 grid.lastSelectedItemIndex = index;
842 // Builds a sort expression from column sort priorities.
843 // called on page load and any time the priorities are modified.
844 grid.compileSort = function() {
845 var sortList = grid.columnsProvider.columns.filter(
846 function(col) { return Number(col.sort) != 0 }
849 if (Math.abs(a.sort) < Math.abs(b.sort))
855 if (sortList.length) {
856 grid.dataProvider.sort = sortList.map(function(col) {
858 blob[col.name] = col.sort < 0 ? 'desc' : 'asc';
864 // builds a sort expression using a single column,
865 // toggling between ascending and descending sort.
866 $scope.quickSort = function(col_name) {
867 var sort = grid.dataProvider.sort;
868 if (sort && sort.length &&
869 sort[0] == col_name) {
871 blob[col_name] = 'desc';
872 grid.dataProvider.sort = [blob];
874 grid.dataProvider.sort = [col_name];
881 // show / hide the grid configuration row
882 $scope.toggleConfDisplay = function() {
883 if ($scope.showGridConf) {
884 $scope.showGridConf = false;
885 if (grid.columnsProvider.hasSortableColumn()) {
886 // only refresh the grid if the user has the
887 // ability to modify the sort priorities.
893 $scope.showGridConf = true;
896 delete $scope.lastModColumn;
897 $scope.gridColumnPickerIsOpen = false;
900 // called when a dragged column is dropped onto itself
901 // or any other column
902 grid.onColumnDrop = function(target) {
903 if (angular.isUndefined(target)) return;
904 if (target == grid.dragColumn) return;
905 var srcIdx, targetIdx, srcCol;
906 angular.forEach(grid.columnsProvider.columns,
908 if (col.name == grid.dragColumn) {
911 } else if (col.name == target) {
917 if (srcIdx < targetIdx) targetIdx--;
919 // move src column from old location to new location in
920 // the columns array, then force a page refresh
921 grid.columnsProvider.columns.splice(srcIdx, 1);
922 grid.columnsProvider.columns.splice(targetIdx, 0, srcCol);
926 // prepares a string for inclusion within a CSV document
927 // by escaping commas and quotes and removing newlines.
928 grid.csvDatum = function(str) {
931 str = str.replace(/\n/g, '');
932 if (str.match(/\,/) || str.match(/"/)) {
933 str = str.replace(/"/g, '""');
934 str = '"' + str + '"';
939 // sets the download file name and inserts the current CSV
940 // into a Blob URL for browser download.
941 $scope.generateCSVExportURL = function() {
942 $scope.gridColumnPickerIsOpen = false;
944 // let the file name describe the grid
945 $scope.csvExportFileName =
946 ($scope.mainLabel || grid.persistKey || 'eg_grid_data')
947 .replace(/\s+/g, '_') + '_' + $scope.page();
949 // toss the CSV into a Blob and update the export URL
950 var csv = grid.generateCSV();
951 var blob = new Blob([csv], {type : 'text/plain'});
952 $scope.csvExportURL =
953 ($window.URL || $window.webkitURL).createObjectURL(blob);
956 $scope.printCSV = function() {
957 $scope.gridColumnPickerIsOpen = false;
960 content : grid.generateCSV(),
961 content_type : 'text/plain'
965 // generates CSV for the currently visible grid contents
966 grid.generateCSV = function() {
968 var colCount = grid.columnsProvider.columns.length;
971 angular.forEach(grid.columnsProvider.columns,
973 if (!col.visible) return;
974 csvStr += grid.csvDatum(col.label);
979 csvStr = csvStr.replace(/,$/,'\n');
982 angular.forEach($scope.items, function(item) {
983 angular.forEach(grid.columnsProvider.columns,
985 if (!col.visible) return;
987 var val = grid.dataProvider.itemFieldValue(item, col);
988 // filtered value (dates, etc.)
989 val = $filter('egGridValueFilter')(val, col);
990 csvStr += grid.csvDatum(val);
994 csvStr = csvStr.replace(/,$/,'\n');
1000 // Interpolate the value for column.linkpath within the context
1001 // of the row item to generate the final link URL.
1002 $scope.generateLinkPath = function(col, item) {
1003 return egCore.strings.$replace(col.linkpath, {item : item});
1006 // If a column provides its own HTML template, translate it,
1007 // using the current item for the template scope.
1008 // note: $sce is required to avoid security restrictions and
1009 // is OK here, since the template comes directly from a
1010 // local HTML template (not user input).
1011 $scope.translateCellTemplate = function(col, item) {
1012 var html = egCore.strings.$replace(col.template, {item : item});
1013 return $sce.trustAsHtml(html);
1016 $scope.collect = function() { grid.collect() }
1018 // asks the dataProvider for a page of data
1019 grid.collect = function() {
1021 // avoid firing the collect if there is nothing to collect.
1022 if (grid.selfManagedData && !grid.dataProvider.query) return;
1024 if (grid.collecting) return; // avoid parallel collect()
1025 grid.collecting = true;
1027 console.debug('egGrid.collect() offset='
1028 + grid.offset + '; limit=' + grid.limit);
1030 // ensure all of our dropdowns are closed
1031 // TODO: git rid of these and just use dropdown-toggle,
1032 // which is more reliable.
1033 $scope.gridColumnPickerIsOpen = false;
1034 $scope.gridRowCountIsOpen = false;
1035 $scope.gridPageSelectIsOpen = false;
1038 $scope.selected = {};
1040 // Inform the caller we've asked the data provider
1041 // for data. This is useful for knowing when collection
1042 // has started (e.g. to display a progress dialg) when
1043 // using the stock (flattener) data provider, where the
1044 // user is not directly defining a get() handler.
1045 if (grid.controls.collectStarted)
1046 grid.controls.collectStarted(grid.offset, grid.limit);
1048 grid.dataProvider.get(grid.offset, grid.limit).then(
1050 if (grid.controls.allItemsRetrieved)
1051 grid.controls.allItemsRetrieved();
1056 $scope.items.push(item)
1057 if (grid.controls.itemRetrieved)
1058 grid.controls.itemRetrieved(item);
1059 if ($scope.selectAll)
1060 $scope.selected[grid.indexValue(item)] = true
1062 }).finally(function() {
1063 console.debug('egGrid.collect() complete');
1064 grid.collecting = false
1065 $scope.selected = angular.copy($scope.selected);
1075 * eg-grid-field : used for collecting custom field data from the templates.
1076 * This directive does not direct display, it just passes data up to the
1079 .directive('egGridField', function() {
1081 require : '^egGrid',
1084 flesher: '=', // optional; function that can flesh a linked field, given the value
1085 name : '@', // required; unique name
1086 path : '@', // optional; flesh path
1087 ignore: '@', // optional; fields to ignore when path is a wildcard
1088 label : '@', // optional; display label
1089 flex : '@', // optional; default flex width
1090 align : '@', // optional; default alignment, left/center/right
1091 dateformat : '@', // optional: passed down to egGridValueFilter
1093 // if a field is part of an IDL object, but we are unable to
1094 // determine the class, because it's nested within a hash
1095 // (i.e. we can't navigate directly to the object via the IDL),
1096 // idlClass lets us specify the class. This is particularly
1097 // useful for nested wildcard fields.
1098 parentIdlClass : '@',
1100 // optional: for non-IDL columns, specifying a datatype
1101 // lets the caller control which display filter is used.
1102 // datatype should match the standard IDL datatypes.
1105 link : function(scope, element, attrs, egGridCtrl) {
1107 // boolean fields are presented as value-less attributes
1116 'required' // if set, always fetch data for this column
1119 if (angular.isDefined(attrs[field]))
1120 scope[field] = true;
1124 // any HTML content within the field is its custom template
1125 var tmpl = element.html();
1126 if (tmpl && !tmpl.match(/^\s*$/))
1127 scope.template = tmpl
1129 egGridCtrl.columnsProvider.add(scope);
1136 * eg-grid-action : used for specifying actions which may be applied
1137 * to items within the grid.
1139 .directive('egGridAction', function() {
1141 require : '^egGrid',
1145 group : '@', // Action group, ungrouped if not set
1146 label : '@', // Action label
1147 handler : '=', // Action function handler
1149 disabled : '=', // function
1152 link : function(scope, element, attrs, egGridCtrl) {
1153 egGridCtrl.addAction({
1155 group : scope.group,
1156 label : scope.label,
1157 divider : scope.divider,
1158 handler : scope.handler,
1159 disabled : scope.disabled,
1166 .factory('egGridColumnsProvider', ['egCore', function(egCore) {
1168 function ColumnsProvider(args) {
1171 cols.stockVisible = [];
1172 cols.idlClass = args.idlClass;
1173 cols.defaultToHidden = args.defaultToHidden;
1174 cols.defaultToNoSort = args.defaultToNoSort;
1175 cols.defaultToNoMultiSort = args.defaultToNoMultiSort;
1176 cols.defaultDateFormat = args.defaultDateFormat;
1178 // resets column width, visibility, and sort behavior
1179 // Visibility resets to the visibility settings defined in the
1180 // template (i.e. the original egGridField values).
1181 cols.reset = function() {
1182 angular.forEach(cols.columns, function(col) {
1186 if (cols.stockVisible.indexOf(col.name) > -1) {
1189 col.visible = false;
1194 // returns true if any columns are sortable
1195 cols.hasSortableColumn = function() {
1196 return cols.columns.filter(
1198 return col.sortable || col.multisortable;
1203 cols.showAllColumns = function() {
1204 angular.forEach(cols.columns, function(column) {
1205 column.visible = true;
1209 cols.hideAllColumns = function() {
1210 angular.forEach(cols.columns, function(col) {
1215 cols.indexOf = function(name) {
1216 for (var i = 0; i < cols.columns.length; i++) {
1217 if (cols.columns[i].name == name)
1223 cols.findColumn = function(name) {
1224 return cols.columns[cols.indexOf(name)];
1227 cols.compileAutoColumns = function() {
1228 var idl_class = egCore.idl.classes[cols.idlClass];
1233 if (field.virtual) return;
1234 if (field.datatype == 'link' || field.datatype == 'org_unit') {
1235 // if the field is a link and the linked class has a
1236 // "selector" field specified, use the selector field
1237 // as the display field for the columns.
1238 // flattener will take care of the fleshing.
1239 if (field['class']) {
1240 var selector_field = egCore.idl.classes[field['class']].fields
1241 .filter(function(f) { return Boolean(f.selector) })[0];
1242 if (selector_field) {
1243 field.path = field.name + '.' + selector_field.selector;
1247 cols.add(field, true);
1252 // if a column definition has a path with a wildcard, create
1253 // columns for all non-virtual fields at the specified
1254 // position in the path.
1255 cols.expandPath = function(colSpec) {
1257 var ignoreList = [];
1259 ignoreList = colSpec.ignore.split(' ');
1261 var dotpath = colSpec.path.replace(/\.?\*$/,'');
1265 if (colSpec.parentIdlClass) {
1266 class_obj = egCore.idl.classes[colSpec.parentIdlClass];
1268 class_obj = egCore.idl.classes[cols.idlClass];
1270 var idl_parent = class_obj;
1271 var old_field_label = '';
1273 if (!class_obj) return;
1275 console.debug('egGrid: auto dotpath is: ' + dotpath);
1276 var path_parts = dotpath.split(/\./);
1278 // find the IDL class definition for the last element in the
1279 // path before the .*
1280 // an empty path_parts means expand the root class
1283 for (var path_idx in path_parts) {
1284 old_field = idl_field;
1286 var part = path_parts[path_idx];
1287 idl_field = class_obj.field_map[part];
1289 // unless we're at the end of the list, this field should
1290 // link to another class.
1291 if (idl_field && idl_field['class'] && (
1292 idl_field.datatype == 'link' ||
1293 idl_field.datatype == 'org_unit')) {
1294 if (old_field_label) old_field_label += ' : ';
1295 old_field_label += idl_field.label;
1296 class_obj = egCore.idl.classes[idl_field['class']];
1297 if (old_field) idl_parent = old_field;
1299 if (path_idx < (path_parts.length - 1)) {
1300 // we ran out of classes to hop through before
1301 // we ran out of path components
1302 console.error("egGrid: invalid IDL path: " + dotpath);
1309 angular.forEach(class_obj.fields, function(field) {
1311 // Only show wildcard fields where we have data to show
1312 // Virtual and un-fleshed links will not have any data.
1313 if (field.virtual ||
1314 (field.datatype == 'link' || field.datatype == 'org_unit') ||
1315 ignoreList.indexOf(field.name) > -1
1319 var col = cols.cloneFromScope(colSpec);
1320 col.path = (dotpath ? dotpath + '.' + field.name : field.name);
1322 // log line below is very chatty. disable until needed.
1323 // console.debug('egGrid: field: ' +field.name + '; parent field: ' + js2JSON(idl_parent));
1324 cols.add(col, false, true,
1325 {idl_parent : idl_parent, idl_field : field, idl_class : class_obj, field_parent_label : old_field_label });
1328 cols.columns = cols.columns.sort(
1330 if (a.explicit) return -1;
1331 if (b.explicit) return 1;
1333 if (a.idlclass && b.idlclass) {
1334 if (a.idlclass < b.idlclass) return -1;
1335 if (b.idlclass < a.idlclass) return 1;
1338 if (a.path && b.path && a.path.lastIndexOf('.') && b.path.lastIndexOf('.')) {
1339 if (a.path.substring(0, a.path.lastIndexOf('.')) < b.path.substring(0, b.path.lastIndexOf('.'))) return -1;
1340 if (b.path.substring(0, b.path.lastIndexOf('.')) < a.path.substring(0, a.path.lastIndexOf('.'))) return 1;
1343 if (a.label && b.label) {
1344 if (a.label < b.label) return -1;
1345 if (b.label < a.label) return 1;
1348 return a.name < b.name ? -1 : 1;
1355 "egGrid: wildcard path does not resolve to an object: "
1360 // angular.clone(scopeObject) is not permittable. Manually copy
1361 // the fields over that we need (so the scope object can go away).
1362 cols.cloneFromScope = function(colSpec) {
1364 flesher : colSpec.flesher,
1365 name : colSpec.name,
1366 label : colSpec.label,
1367 path : colSpec.path,
1368 align : colSpec.align || 'left',
1369 flex : Number(colSpec.flex) || 2,
1370 sort : Number(colSpec.sort) || 0,
1371 required : colSpec.required,
1372 linkpath : colSpec.linkpath,
1373 template : colSpec.template,
1374 visible : colSpec.visible,
1375 hidden : colSpec.hidden,
1376 datatype : colSpec.datatype,
1377 sortable : colSpec.sortable,
1378 nonsortable : colSpec.nonsortable,
1379 multisortable : colSpec.multisortable,
1380 nonmultisortable : colSpec.nonmultisortable,
1381 dateformat : colSpec.dateformat,
1382 parentIdlClass : colSpec.parentIdlClass
1387 // Add a column to the columns collection.
1388 // Columns may come from a slim eg-columns-field or
1389 // directly from the IDL.
1390 cols.add = function(colSpec, fromIDL, fromExpand, idl_info) {
1392 // First added column with the specified path takes precedence.
1393 // This allows for specific definitions followed by wildcard
1394 // definitions. If a match is found, back out.
1395 if (cols.columns.filter(function(c) {
1396 return (c.path == colSpec.path) })[0]) {
1397 console.debug('skipping pre-existing column ' + colSpec.path);
1401 var column = fromExpand ? colSpec : cols.cloneFromScope(colSpec);
1403 if (column.path && column.path.match(/\*$/))
1404 return cols.expandPath(colSpec);
1406 if (!fromExpand) column.explicit = true;
1408 if (!column.name) column.name = column.path;
1409 if (!column.path) column.path = column.name;
1411 if (column.visible || (!cols.defaultToHidden && !column.hidden))
1412 column.visible = true;
1414 if (column.sortable || (!cols.defaultToNoSort && !column.nonsortable))
1415 column.sortable = true;
1417 if (column.multisortable ||
1418 (!cols.defaultToNoMultiSort && !column.nonmultisortable))
1419 column.multisortable = true;
1421 if (cols.defaultDateFormat && ! column.dateformat) {
1422 column.dateformat = cols.defaultDateFormat;
1425 cols.columns.push(column);
1427 // Track which columns are visible by default in case we
1428 // need to reset column visibility
1430 cols.stockVisible.push(column.name);
1432 if (fromIDL) return; // directly from egIDL. nothing left to do.
1434 // lookup the matching IDL field
1435 if (!idl_info && cols.idlClass)
1436 idl_info = cols.idlFieldFromPath(column.path);
1439 // column is not represented within the IDL
1440 column.adhoc = true;
1444 column.datatype = idl_info.idl_field.datatype;
1446 if (!column.label) {
1447 column.label = idl_info.idl_field.label || column.name;
1450 if (fromExpand && idl_info.idl_class) {
1451 column.idlclass = '';
1452 if (idl_info.field_parent_label && idl_info.idl_parent.label != idl_info.idl_class.label) {
1453 column.idlclass = (idl_info.field_parent_label || idl_info.idl_parent.label || idl_info.idl_parent.name);
1455 column.idlclass += idl_info.idl_class.label || idl_info.idl_class.name;
1460 // finds the IDL field from the dotpath, using the columns
1461 // idlClass as the base.
1462 cols.idlFieldFromPath = function(dotpath) {
1463 var class_obj = egCore.idl.classes[cols.idlClass];
1464 var path_parts = dotpath.split(/\./);
1468 for (var path_idx in path_parts) {
1469 var part = path_parts[path_idx];
1470 idl_parent = idl_field;
1471 idl_field = class_obj.field_map[part];
1474 if (idl_field['class'] && (
1475 idl_field.datatype == 'link' ||
1476 idl_field.datatype == 'org_unit')) {
1477 class_obj = egCore.idl.classes[idl_field['class']];
1485 idl_parent: idl_parent,
1486 idl_field : idl_field,
1487 idl_class : class_obj
1493 instance : function(args) { return new ColumnsProvider(args) }
1499 * Generic data provider template class. This is basically an abstract
1500 * class factory service whose instances can be locally modified to
1501 * meet the needs of each individual grid.
1503 .factory('egGridDataProvider',
1504 ['$q','$timeout','$filter','egCore',
1505 function($q , $timeout , $filter , egCore) {
1507 function GridDataProvider(args) {
1508 var gridData = this;
1509 if (!args) args = {};
1512 gridData.get = args.get;
1513 gridData.query = args.query;
1514 gridData.idlClass = args.idlClass;
1515 gridData.columnsProvider = args.columnsProvider;
1517 // Delivers a stream of array data via promise.notify()
1518 // Useful for passing an array of data to egGrid.get()
1519 // If a count is provided, the array will be trimmed to
1520 // the range defined by count and offset
1521 gridData.arrayNotifier = function(arr, offset, count) {
1522 if (!arr || arr.length == 0) return $q.when();
1523 if (count) arr = arr.slice(offset, offset + count);
1524 var def = $q.defer();
1525 // promise notifications are only witnessed when delivered
1526 // after the caller has his hands on the promise object
1527 $timeout(function() {
1528 angular.forEach(arr, def.notify);
1534 // Calls the grid refresh function. Once instantiated, the
1535 // grid will replace this function with it's own refresh()
1536 gridData.refresh = function(noReset) { }
1538 if (!gridData.get) {
1539 // returns a promise whose notify() delivers items
1540 gridData.get = function(index, count) {
1541 console.error("egGridDataProvider.get() not implemented");
1545 // attempts a flat field lookup first. If the column is not
1546 // found on the top-level object, attempts a nested lookup
1547 // TODO: consider a caching layer to speed up template
1548 // rendering, particularly for nested objects?
1549 gridData.itemFieldValue = function(item, column) {
1551 if (column.name in item) {
1552 if (typeof item[column.name] == 'function') {
1553 val = item[column.name]();
1555 val = item[column.name];
1558 val = gridData.nestedItemFieldValue(item, column);
1564 // TODO: deprecate me
1565 gridData.flatItemFieldValue = function(item, column) {
1566 console.warn('gridData.flatItemFieldValue deprecated; '
1567 + 'leave provider.itemFieldValue unset');
1568 return item[column.name];
1571 // given an object and a dot-separated path to a field,
1572 // extract the value of the field. The path can refer
1573 // to function names or object attributes. If the final
1574 // value is an IDL field, run the value through its
1575 // corresponding output filter.
1576 gridData.nestedItemFieldValue = function(obj, column) {
1577 item = obj; // keep a copy around
1579 if (obj === null || obj === undefined || obj === '') return '';
1580 if (!column.path) return obj;
1583 var parts = column.path.split('.');
1585 angular.forEach(parts, function(step, idx) {
1586 // object is not fleshed to the expected extent
1587 if (typeof obj != 'object') {
1588 if (typeof obj != 'undefined' && column.flesher) {
1589 obj = column.flesher(obj, column, item);
1596 if (!obj) return '';
1598 var cls = obj.classname;
1599 if (cls && (class_obj = egCore.idl.classes[cls])) {
1600 idl_field = class_obj.field_map[step];
1601 obj = obj[step] ? obj[step]() : '';
1603 if (angular.isFunction(obj[step])) {
1611 // We found a nested IDL object which may or may not have
1612 // been configured as a top-level column. Grab the datatype.
1613 if (idl_field && !column.datatype)
1614 column.datatype = idl_field.datatype;
1616 if (obj === null || obj === undefined || obj === '') return '';
1622 instance : function(args) {
1623 return new GridDataProvider(args);
1630 // Factory service for egGridDataManager instances, which are
1631 // responsible for collecting flattened grid data.
1632 .factory('egGridFlatDataProvider',
1633 ['$q','egCore','egGridDataProvider',
1634 function($q , egCore , egGridDataProvider) {
1637 instance : function(args) {
1638 var provider = egGridDataProvider.instance(args);
1640 provider.get = function(offset, count) {
1642 // no query means no call
1643 if (!provider.query ||
1644 angular.equals(provider.query, {}))
1647 // find all of the currently visible columns
1648 var queryFields = {}
1649 angular.forEach(provider.columnsProvider.columns,
1651 // only query IDL-tracked columns
1652 if (!col.adhoc && (col.required || col.visible))
1653 queryFields[col.name] = col.path;
1657 return egCore.net.request(
1659 'open-ils.fielder.flattened_search',
1660 egCore.auth.token(), provider.idlClass,
1661 queryFields, provider.query,
1662 { sort : provider.sort,
1668 //provider.itemFieldValue = provider.flatItemFieldValue;
1675 .directive('egGridColumnDragSource', function() {
1678 require : '^egGrid',
1679 link : function(scope, element, attrs, egGridCtrl) {
1680 angular.element(element).attr('draggable', 'true');
1682 element.bind('dragstart', function(e) {
1683 egGridCtrl.dragColumn = attrs.column;
1684 egGridCtrl.dragType = attrs.dragType || 'move'; // or resize
1685 egGridCtrl.colResizeDir = 0;
1687 if (egGridCtrl.dragType == 'move') {
1688 // style the column getting moved
1689 angular.element(e.target).addClass(
1690 'eg-grid-column-move-handle-active');
1694 element.bind('dragend', function(e) {
1695 if (egGridCtrl.dragType == 'move') {
1696 angular.element(e.target).removeClass(
1697 'eg-grid-column-move-handle-active');
1704 .directive('egGridColumnDragDest', function() {
1707 require : '^egGrid',
1708 link : function(scope, element, attrs, egGridCtrl) {
1710 element.bind('dragover', function(e) { // required for drop
1711 e.stopPropagation();
1713 e.dataTransfer.dropEffect = 'move';
1715 if (egGridCtrl.colResizeDir == 0) return; // move
1717 var cols = egGridCtrl.columnsProvider;
1718 var srcCol = egGridCtrl.dragColumn;
1719 var srcColIdx = cols.indexOf(srcCol);
1721 if (egGridCtrl.colResizeDir == -1) {
1722 if (cols.indexOf(attrs.column) <= srcColIdx) {
1723 egGridCtrl.modifyColumnFlex(
1724 egGridCtrl.columnsProvider.findColumn(
1725 egGridCtrl.dragColumn), -1);
1726 if (cols.columns[srcColIdx+1]) {
1727 // source column shrinks by one, column to the
1728 // right grows by one.
1729 egGridCtrl.modifyColumnFlex(
1730 cols.columns[srcColIdx+1], 1);
1735 if (cols.indexOf(attrs.column) > srcColIdx) {
1736 egGridCtrl.modifyColumnFlex(
1737 egGridCtrl.columnsProvider.findColumn(
1738 egGridCtrl.dragColumn), 1);
1739 if (cols.columns[srcColIdx+1]) {
1740 // source column grows by one, column to the
1741 // right grows by one.
1742 egGridCtrl.modifyColumnFlex(
1743 cols.columns[srcColIdx+1], -1);
1751 element.bind('dragenter', function(e) {
1752 e.stopPropagation();
1754 if (egGridCtrl.dragType == 'move') {
1755 angular.element(e.target).addClass('eg-grid-col-hover');
1757 // resize grips are on the right side of each column.
1758 // dragenter will either occur on the source column
1759 // (dragging left) or the column to the right.
1760 if (egGridCtrl.colResizeDir == 0) {
1761 if (egGridCtrl.dragColumn == attrs.column) {
1762 egGridCtrl.colResizeDir = -1; // west
1764 egGridCtrl.colResizeDir = 1; // east
1770 element.bind('dragleave', function(e) {
1771 e.stopPropagation();
1773 if (egGridCtrl.dragType == 'move') {
1774 angular.element(e.target).removeClass('eg-grid-col-hover');
1778 element.bind('drop', function(e) {
1779 e.stopPropagation();
1781 egGridCtrl.colResizeDir = 0;
1782 if (egGridCtrl.dragType == 'move') {
1783 angular.element(e.target).removeClass('eg-grid-col-hover');
1784 egGridCtrl.onColumnDrop(attrs.column); // move the column
1791 .directive('egGridMenuItem', function() {
1794 require : '^egGrid',
1800 handler : '=', // onclick handler function
1801 divider : '=', // if true, show a divider only
1802 handlerData : '=', // if set, passed as second argument to handler
1803 disabled : '=', // function
1804 hidden : '=' // function
1806 link : function(scope, element, attrs, egGridCtrl) {
1807 egGridCtrl.addMenuItem({
1808 checkbox : scope.checkbox,
1809 checked : scope.checked ? true : false,
1810 label : scope.label,
1811 standalone : scope.standalone ? true : false,
1812 handler : scope.handler,
1813 divider : scope.divider,
1814 disabled : scope.disabled,
1815 hidden : scope.hidden,
1816 handlerData : scope.handlerData
1826 * Translates bare IDL object values into display values.
1827 * 1. Passes dates through the angular date filter
1828 * 2. Translates bools to Booleans so the browser can display translated
1829 * value. (Though we could manually translate instead..)
1830 * Others likely to follow...
1832 .filter('egGridValueFilter', ['$filter', function($filter) {
1833 return function(value, column) {
1834 switch(column.datatype) {
1837 // Browser will translate true/false for us
1839 case '1' : // legacy
1843 case '0' : // legacy
1846 // value may be null, '', etc.
1847 default : return '';
1850 // canned angular date filter FTW
1851 if (!column.dateformat)
1852 column.dateformat = 'shortDate';
1853 return $filter('date')(value, column.dateformat);
1855 return $filter('currency')(value);