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 disable handler function for a context action
520 $scope.actionDisable = function(action) {
521 if (!action.disabled) {
524 return action.disabled(action);
527 // fires the action handler function for a context action
528 $scope.actionLauncher = function(action) {
529 if (!action.handler) {
531 'No handler specified for "' + action.label + '"');
535 action.handler(grid.getSelectedItems());
537 console.error('Error executing handler for "'
538 + action.label + '" => ' + E + "\n" + E.stack);
541 if ($scope.action_context_showing) $scope.hideActionContextMenu();
546 $scope.hideActionContextMenu = function () {
547 $($scope.menu_dom).css({
549 width: $scope.action_context_width,
550 top: $scope.action_context_y,
551 left: $scope.action_context_x
553 $($scope.action_context_parent).append($scope.menu_dom);
554 $scope.action_context_oldy = $scope.action_context_oldx = 0;
555 $('body').unbind('click.remove_context_menu_'+$scope.action_context_index);
556 $scope.action_context_showing = false;
559 $scope.action_context_showing = false;
560 $scope.showActionContextMenu = function ($event) {
562 // Have to gather these here, instead of inside link()
563 if (!$scope.menu_dom) $scope.menu_dom = $($scope.grid_element).find('.grid-action-dropdown')[0];
564 if (!$scope.action_context_parent) $scope.action_context_parent = $($scope.menu_dom).parent();
566 if (!grid.getSelectedItems().length) // Nothing selected, fire the click event
567 $event.target.click();
569 if (!$scope.action_context_showing) {
570 $scope.action_context_width = $($scope.menu_dom).css('width');
571 $scope.action_context_y = $($scope.menu_dom).css('top');
572 $scope.action_context_x = $($scope.menu_dom).css('left');
573 $scope.action_context_showing = true;
574 $scope.action_context_index = Math.floor((Math.random() * 1000) + 1);
576 $('body').append($($scope.menu_dom));
577 $('body').bind('click.remove_context_menu_'+$scope.action_context_index, $scope.hideActionContextMenu);
580 $($scope.menu_dom).css({
582 width: $scope.action_context_width,
590 // returns the list of selected item objects
591 grid.getSelectedItems = function() {
592 return $scope.items.filter(
594 return Boolean($scope.selected[grid.indexValue(item)]);
599 grid.getItemByIndex = function(index) {
600 for (var i = 0; i < $scope.items.length; i++) {
601 var item = $scope.items[i];
602 if (grid.indexValue(item) == index)
607 // selects one row after deselecting all of the others
608 grid.selectOneItem = function(index) {
609 $scope.selected = {};
610 $scope.selected[index] = true;
613 // selects or deselects an item, without affecting the others.
614 // returns true if the item is selected; false if de-selected.
615 grid.toggleSelectOneItem = function(index) {
616 if ($scope.selected[index]) {
617 delete $scope.selected[index];
620 return $scope.selected[index] = true;
624 grid.selectAllItems = function() {
625 angular.forEach($scope.items, function(item) {
626 $scope.selected[grid.indexValue(item)] = true
630 $scope.$watch('selectAll', function(newVal) {
632 grid.selectAllItems();
634 $scope.selected = {};
638 // returns true if item1 appears in the list before item2;
639 // false otherwise. this is slightly more efficient that
640 // finding the position of each then comparing them.
641 // item1 / item2 may be an item or an item index
642 grid.itemComesBefore = function(itemOrIndex1, itemOrIndex2) {
643 var idx1 = grid.indexValue(itemOrIndex1);
644 var idx2 = grid.indexValue(itemOrIndex2);
646 // use for() for early exit
647 for (var i = 0; i < $scope.items.length; i++) {
648 var idx = grid.indexValue($scope.items[i]);
649 if (idx == idx1) return true;
650 if (idx == idx2) return false;
655 // 0-based position of item in the current data set
656 grid.indexOf = function(item) {
657 var idx = grid.indexValue(item);
658 for (var i = 0; i < $scope.items.length; i++) {
659 if (grid.indexValue($scope.items[i]) == idx)
665 grid.modifyColumnFlex = function(column, val) {
667 // prevent flex:0; use hiding instead
671 $scope.modifyColumnFlex = function(col, val) {
672 grid.modifyColumnFlex(col, val);
675 // handles click, control-click, and shift-click
676 $scope.handleRowClick = function($event, item) {
677 var index = grid.indexValue(item);
679 var origSelected = Object.keys($scope.selected);
681 if (!$scope.canMultiSelect) {
682 grid.selectOneItem(index);
683 grid.lastSelectedItemIndex = index;
687 if ($event.ctrlKey || $event.metaKey /* mac command */) {
689 if (grid.toggleSelectOneItem(index))
690 grid.lastSelectedItemIndex = index;
692 } else if ($event.shiftKey) {
695 if (!grid.lastSelectedItemIndex ||
696 index == grid.lastSelectedItemIndex) {
697 grid.selectOneItem(index);
698 grid.lastSelectedItemIndex = index;
702 var selecting = false;
703 var ascending = grid.itemComesBefore(
704 grid.lastSelectedItemIndex, item);
706 grid.indexOf(grid.lastSelectedItemIndex);
708 // update to new last-selected
709 grid.lastSelectedItemIndex = index;
711 // select each row between the last selected and
712 // currently selected items
714 startPos += ascending ? 1 : -1;
715 var curItem = $scope.items[startPos];
717 var curIdx = grid.indexValue(curItem);
718 $scope.selected[curIdx] = true;
719 if (curIdx == index) break; // all done
724 grid.selectOneItem(index);
725 grid.lastSelectedItemIndex = index;
729 // Builds a sort expression from column sort priorities.
730 // called on page load and any time the priorities are modified.
731 grid.compileSort = function() {
732 var sortList = grid.columnsProvider.columns.filter(
733 function(col) { return Number(col.sort) != 0 }
736 if (Math.abs(a.sort) < Math.abs(b.sort))
742 if (sortList.length) {
743 grid.dataProvider.sort = sortList.map(function(col) {
745 blob[col.name] = col.sort < 0 ? 'desc' : 'asc';
751 // builds a sort expression using a single column,
752 // toggling between ascending and descending sort.
753 $scope.quickSort = function(col_name) {
754 var sort = grid.dataProvider.sort;
755 if (sort && sort.length &&
756 sort[0] == col_name) {
758 blob[col_name] = 'desc';
759 grid.dataProvider.sort = [blob];
761 grid.dataProvider.sort = [col_name];
768 // show / hide the grid configuration row
769 $scope.toggleConfDisplay = function() {
770 if ($scope.showGridConf) {
771 $scope.showGridConf = false;
772 if (grid.columnsProvider.hasSortableColumn()) {
773 // only refresh the grid if the user has the
774 // ability to modify the sort priorities.
780 $scope.showGridConf = true;
783 $scope.gridColumnPickerIsOpen = false;
786 // called when a dragged column is dropped onto itself
787 // or any other column
788 grid.onColumnDrop = function(target) {
789 if (angular.isUndefined(target)) return;
790 if (target == grid.dragColumn) return;
791 var srcIdx, targetIdx, srcCol;
792 angular.forEach(grid.columnsProvider.columns,
794 if (col.name == grid.dragColumn) {
797 } else if (col.name == target) {
803 if (srcIdx < targetIdx) targetIdx--;
805 // move src column from old location to new location in
806 // the columns array, then force a page refresh
807 grid.columnsProvider.columns.splice(srcIdx, 1);
808 grid.columnsProvider.columns.splice(targetIdx, 0, srcCol);
812 // prepares a string for inclusion within a CSV document
813 // by escaping commas and quotes and removing newlines.
814 grid.csvDatum = function(str) {
817 str = str.replace(/\n/g, '');
818 if (str.match(/\,/) || str.match(/"/)) {
819 str = str.replace(/"/g, '""');
820 str = '"' + str + '"';
825 // sets the download file name and inserts the current CSV
826 // into a Blob URL for browser download.
827 $scope.generateCSVExportURL = function() {
828 $scope.gridColumnPickerIsOpen = false;
830 // let the file name describe the grid
831 $scope.csvExportFileName =
832 ($scope.mainLabel || grid.persistKey || 'eg_grid_data')
833 .replace(/\s+/g, '_') + '_' + $scope.page();
835 // toss the CSV into a Blob and update the export URL
836 var csv = grid.generateCSV();
837 var blob = new Blob([csv], {type : 'text/plain'});
838 $scope.csvExportURL =
839 ($window.URL || $window.webkitURL).createObjectURL(blob);
842 $scope.printCSV = function() {
843 $scope.gridColumnPickerIsOpen = false;
846 content : grid.generateCSV(),
847 content_type : 'text/plain'
851 // generates CSV for the currently visible grid contents
852 grid.generateCSV = function() {
854 var colCount = grid.columnsProvider.columns.length;
857 angular.forEach(grid.columnsProvider.columns,
859 if (!col.visible) return;
860 csvStr += grid.csvDatum(col.label);
865 csvStr = csvStr.replace(/,$/,'\n');
868 angular.forEach($scope.items, function(item) {
869 angular.forEach(grid.columnsProvider.columns,
871 if (!col.visible) return;
873 var val = grid.dataProvider.itemFieldValue(item, col);
874 // filtered value (dates, etc.)
875 val = $filter('egGridValueFilter')(val, col);
876 csvStr += grid.csvDatum(val);
880 csvStr = csvStr.replace(/,$/,'\n');
886 // Interpolate the value for column.linkpath within the context
887 // of the row item to generate the final link URL.
888 $scope.generateLinkPath = function(col, item) {
889 return egCore.strings.$replace(col.linkpath, {item : item});
892 // If a column provides its own HTML template, translate it,
893 // using the current item for the template scope.
894 // note: $sce is required to avoid security restrictions and
895 // is OK here, since the template comes directly from a
896 // local HTML template (not user input).
897 $scope.translateCellTemplate = function(col, item) {
898 var html = egCore.strings.$replace(col.template, {item : item});
899 return $sce.trustAsHtml(html);
902 $scope.collect = function() { grid.collect() }
904 // asks the dataProvider for a page of data
905 grid.collect = function() {
907 // avoid firing the collect if there is nothing to collect.
908 if (grid.selfManagedData && !grid.dataProvider.query) return;
910 if (grid.collecting) return; // avoid parallel collect()
911 grid.collecting = true;
913 console.debug('egGrid.collect() offset='
914 + grid.offset + '; limit=' + grid.limit);
916 // ensure all of our dropdowns are closed
917 // TODO: git rid of these and just use dropdown-toggle,
918 // which is more reliable.
919 $scope.gridColumnPickerIsOpen = false;
920 $scope.gridRowCountIsOpen = false;
921 $scope.gridPageSelectIsOpen = false;
924 $scope.selected = {};
925 grid.dataProvider.get(grid.offset, grid.limit).then(
927 if (grid.controls.allItemsRetrieved)
928 grid.controls.allItemsRetrieved();
933 $scope.items.push(item)
934 if (grid.controls.itemRetrieved)
935 grid.controls.itemRetrieved(item);
937 }).finally(function() {
938 console.debug('egGrid.collect() complete');
939 grid.collecting = false
949 * eg-grid-field : used for collecting custom field data from the templates.
950 * This directive does not direct display, it just passes data up to the
953 .directive('egGridField', function() {
958 name : '@', // required; unique name
959 path : '@', // optional; flesh path
960 ignore: '@', // optional; fields to ignore when path is a wildcard
961 label : '@', // optional; display label
962 flex : '@', // optional; default flex width
963 align : '@', // optional; default alignment, left/center/right
964 dateformat : '@', // optional: passed down to egGridValueFilter
966 // if a field is part of an IDL object, but we are unable to
967 // determine the class, because it's nested within a hash
968 // (i.e. we can't navigate directly to the object via the IDL),
969 // idlClass lets us specify the class. This is particularly
970 // useful for nested wildcard fields.
971 parentIdlClass : '@',
973 // optional: for non-IDL columns, specifying a datatype
974 // lets the caller control which display filter is used.
975 // datatype should match the standard IDL datatypes.
978 link : function(scope, element, attrs, egGridCtrl) {
980 // boolean fields are presented as value-less attributes
989 'required' // if set, always fetch data for this column
992 if (angular.isDefined(attrs[field]))
997 // any HTML content within the field is its custom template
998 var tmpl = element.html();
999 if (tmpl && !tmpl.match(/^\s*$/))
1000 scope.template = tmpl
1002 egGridCtrl.columnsProvider.add(scope);
1009 * eg-grid-action : used for specifying actions which may be applied
1010 * to items within the grid.
1012 .directive('egGridAction', function() {
1014 require : '^egGrid',
1018 group : '@', // Action group, ungrouped if not set
1019 label : '@', // Action label
1020 handler : '=', // Action function handler
1022 disabled : '=', // function
1025 link : function(scope, element, attrs, egGridCtrl) {
1026 egGridCtrl.addAction({
1028 group : scope.group,
1029 label : scope.label,
1030 divider : scope.divider,
1031 handler : scope.handler,
1032 disabled : scope.disabled,
1039 .factory('egGridColumnsProvider', ['egCore', function(egCore) {
1041 function ColumnsProvider(args) {
1044 cols.stockVisible = [];
1045 cols.idlClass = args.idlClass;
1046 cols.defaultToHidden = args.defaultToHidden;
1047 cols.defaultToNoSort = args.defaultToNoSort;
1048 cols.defaultToNoMultiSort = args.defaultToNoMultiSort;
1050 // resets column width, visibility, and sort behavior
1051 // Visibility resets to the visibility settings defined in the
1052 // template (i.e. the original egGridField values).
1053 cols.reset = function() {
1054 angular.forEach(cols.columns, function(col) {
1058 if (cols.stockVisible.indexOf(col.name) > -1) {
1061 col.visible = false;
1066 // returns true if any columns are sortable
1067 cols.hasSortableColumn = function() {
1068 return cols.columns.filter(
1070 return col.sortable || col.multisortable;
1075 cols.showAllColumns = function() {
1076 angular.forEach(cols.columns, function(column) {
1077 column.visible = true;
1081 cols.hideAllColumns = function() {
1082 angular.forEach(cols.columns, function(col) {
1087 cols.indexOf = function(name) {
1088 for (var i = 0; i < cols.columns.length; i++) {
1089 if (cols.columns[i].name == name)
1095 cols.findColumn = function(name) {
1096 return cols.columns[cols.indexOf(name)];
1099 cols.compileAutoColumns = function() {
1100 var idl_class = egCore.idl.classes[cols.idlClass];
1103 idl_class.fields.sort(
1104 function(a, b) { return a.name < b.name ? -1 : 1 }),
1106 if (field.virtual) return;
1107 if (field.datatype == 'link' || field.datatype == 'org_unit') {
1108 // if the field is a link and the linked class has a
1109 // "selector" field specified, use the selector field
1110 // as the display field for the columns.
1111 // flattener will take care of the fleshing.
1112 if (field['class']) {
1113 var selector_field = egCore.idl.classes[field['class']].fields
1114 .filter(function(f) { return Boolean(f.selector) })[0];
1115 if (selector_field) {
1116 field.path = field.name + '.' + selector_field.selector;
1120 cols.add(field, true);
1125 // if a column definition has a path with a wildcard, create
1126 // columns for all non-virtual fields at the specified
1127 // position in the path.
1128 cols.expandPath = function(colSpec) {
1130 var ignoreList = [];
1132 ignoreList = colSpec.ignore.split(' ');
1134 var dotpath = colSpec.path.replace(/\.?\*$/,'');
1138 if (colSpec.parentIdlClass) {
1139 class_obj = egCore.idl.classes[colSpec.parentIdlClass];
1141 class_obj = egCore.idl.classes[cols.idlClass];
1144 if (!class_obj) return;
1146 console.debug('egGrid: auto dotpath is: ' + dotpath);
1147 var path_parts = dotpath.split(/\./);
1149 // find the IDL class definition for the last element in the
1150 // path before the .*
1151 // an empty path_parts means expand the root class
1153 for (var path_idx in path_parts) {
1154 var part = path_parts[path_idx];
1155 idl_field = class_obj.field_map[part];
1157 // unless we're at the end of the list, this field should
1158 // link to another class.
1159 if (idl_field && idl_field['class'] && (
1160 idl_field.datatype == 'link' ||
1161 idl_field.datatype == 'org_unit')) {
1162 class_obj = egCore.idl.classes[idl_field['class']];
1164 if (path_idx < (path_parts.length - 1)) {
1165 // we ran out of classes to hop through before
1166 // we ran out of path components
1167 console.error("egGrid: invalid IDL path: " + dotpath);
1174 angular.forEach(class_obj.fields, function(field) {
1176 // Only show wildcard fields where we have data to show
1177 // Virtual and un-fleshed links will not have any data.
1178 if (field.virtual ||
1179 (field.datatype == 'link' || field.datatype == 'org_unit') ||
1180 ignoreList.indexOf(field.name) > -1
1184 var col = cols.cloneFromScope(colSpec);
1185 col.path = (dotpath ? dotpath + '.' + field.name : field.name);
1186 console.debug('egGrid: field: ' +field.name + '; parent field: ' + js2JSON(idl_field));
1187 cols.add(col, false, true,
1188 {idl_parent : idl_field, idl_field : field, idl_class : class_obj});
1191 cols.columns = cols.columns.sort(
1193 if (a.explicit) return -1;
1194 if (b.explicit) return 1;
1195 if (a.idlclass && b.idlclass) {
1196 return a.idlclass < b.idlclass ? -1 : 1;
1197 return a.idlclass > b.idlclass ? 1 : -1;
1199 if (a.path && b.path) {
1200 return a.path < b.path ? -1 : 1;
1201 return a.path > b.path ? 1 : -1;
1204 return a.label < b.label ? -1 : 1;
1211 "egGrid: wildcard path does not resolve to an object: "
1216 // angular.clone(scopeObject) is not permittable. Manually copy
1217 // the fields over that we need (so the scope object can go away).
1218 cols.cloneFromScope = function(colSpec) {
1220 name : colSpec.name,
1221 label : colSpec.label,
1222 path : colSpec.path,
1223 align : colSpec.align || 'left',
1224 flex : Number(colSpec.flex) || 2,
1225 sort : Number(colSpec.sort) || 0,
1226 required : colSpec.required,
1227 linkpath : colSpec.linkpath,
1228 template : colSpec.template,
1229 visible : colSpec.visible,
1230 hidden : colSpec.hidden,
1231 datatype : colSpec.datatype,
1232 sortable : colSpec.sortable,
1233 nonsortable : colSpec.nonsortable,
1234 multisortable : colSpec.multisortable,
1235 nonmultisortable : colSpec.nonmultisortable,
1236 dateformat : colSpec.dateformat,
1237 parentIdlClass : colSpec.parentIdlClass
1242 // Add a column to the columns collection.
1243 // Columns may come from a slim eg-columns-field or
1244 // directly from the IDL.
1245 cols.add = function(colSpec, fromIDL, fromExpand, idl_info) {
1247 // First added column with the specified path takes precedence.
1248 // This allows for specific definitions followed by wildcard
1249 // definitions. If a match is found, back out.
1250 if (cols.columns.filter(function(c) {
1251 return (c.path == colSpec.path) })[0]) {
1252 console.debug('skipping pre-existing column ' + colSpec.path);
1256 var column = fromExpand ? colSpec : cols.cloneFromScope(colSpec);
1258 if (column.path && column.path.match(/\*$/))
1259 return cols.expandPath(colSpec);
1261 if (!fromExpand) column.explicit = true;
1263 if (!column.name) column.name = column.path;
1264 if (!column.path) column.path = column.name;
1266 if (column.visible || (!cols.defaultToHidden && !column.hidden))
1267 column.visible = true;
1269 if (column.sortable || (!cols.defaultToNoSort && !column.nonsortable))
1270 column.sortable = true;
1272 if (column.multisortable ||
1273 (!cols.defaultToNoMultiSort && !column.nonmultisortable))
1274 column.multisortable = true;
1276 cols.columns.push(column);
1278 // Track which columns are visible by default in case we
1279 // need to reset column visibility
1281 cols.stockVisible.push(column.name);
1283 if (fromIDL) return; // directly from egIDL. nothing left to do.
1285 // lookup the matching IDL field
1286 if (!idl_info && cols.idlClass)
1287 idl_info = cols.idlFieldFromPath(column.path);
1290 // column is not represented within the IDL
1291 column.adhoc = true;
1295 column.datatype = idl_info.idl_field.datatype;
1297 if (!column.label) {
1298 column.label = idl_info.idl_field.label || column.name;
1301 if (fromExpand && idl_info.idl_class) {
1302 column.idlclass = '';
1303 if (idl_info.idl_parent) {
1304 column.idlclass = idl_info.idl_parent.label || idl_info.idl_parent.name;
1306 column.idlclass += idl_info.idl_class.label || idl_info.idl_class.name;
1311 // finds the IDL field from the dotpath, using the columns
1312 // idlClass as the base.
1313 cols.idlFieldFromPath = function(dotpath) {
1314 var class_obj = egCore.idl.classes[cols.idlClass];
1315 var path_parts = dotpath.split(/\./);
1319 for (var path_idx in path_parts) {
1320 var part = path_parts[path_idx];
1321 idl_parent = idl_field;
1322 idl_field = class_obj.field_map[part];
1324 if (idl_field && idl_field['class'] && (
1325 idl_field.datatype == 'link' ||
1326 idl_field.datatype == 'org_unit')) {
1327 class_obj = egCore.idl.classes[idl_field['class']];
1329 // else, path is not in the IDL, which is fine
1332 if (!idl_field) return null;
1335 idl_parent: idl_parent,
1336 idl_field : idl_field,
1337 idl_class : class_obj
1343 instance : function(args) { return new ColumnsProvider(args) }
1349 * Generic data provider template class. This is basically an abstract
1350 * class factory service whose instances can be locally modified to
1351 * meet the needs of each individual grid.
1353 .factory('egGridDataProvider',
1354 ['$q','$timeout','$filter','egCore',
1355 function($q , $timeout , $filter , egCore) {
1357 function GridDataProvider(args) {
1358 var gridData = this;
1359 if (!args) args = {};
1362 gridData.get = args.get;
1363 gridData.query = args.query;
1364 gridData.idlClass = args.idlClass;
1365 gridData.columnsProvider = args.columnsProvider;
1367 // Delivers a stream of array data via promise.notify()
1368 // Useful for passing an array of data to egGrid.get()
1369 // If a count is provided, the array will be trimmed to
1370 // the range defined by count and offset
1371 gridData.arrayNotifier = function(arr, offset, count) {
1372 if (!arr || arr.length == 0) return $q.when();
1373 if (count) arr = arr.slice(offset, offset + count);
1374 var def = $q.defer();
1375 // promise notifications are only witnessed when delivered
1376 // after the caller has his hands on the promise object
1377 $timeout(function() {
1378 angular.forEach(arr, def.notify);
1384 // Calls the grid refresh function. Once instantiated, the
1385 // grid will replace this function with it's own refresh()
1386 gridData.refresh = function(noReset) { }
1388 if (!gridData.get) {
1389 // returns a promise whose notify() delivers items
1390 gridData.get = function(index, count) {
1391 console.error("egGridDataProvider.get() not implemented");
1395 // attempts a flat field lookup first. If the column is not
1396 // found on the top-level object, attempts a nested lookup
1397 // TODO: consider a caching layer to speed up template
1398 // rendering, particularly for nested objects?
1399 gridData.itemFieldValue = function(item, column) {
1400 if (column.name in item) {
1401 if (typeof item[column.name] == 'function') {
1402 return item[column.name]();
1404 return item[column.name];
1407 return gridData.nestedItemFieldValue(item, column);
1411 // TODO: deprecate me
1412 gridData.flatItemFieldValue = function(item, column) {
1413 console.warn('gridData.flatItemFieldValue deprecated; '
1414 + 'leave provider.itemFieldValue unset');
1415 return item[column.name];
1418 // given an object and a dot-separated path to a field,
1419 // extract the value of the field. The path can refer
1420 // to function names or object attributes. If the final
1421 // value is an IDL field, run the value through its
1422 // corresponding output filter.
1423 gridData.nestedItemFieldValue = function(obj, column) {
1424 if (obj === null || obj === undefined || obj === '') return '';
1425 if (!column.path) return obj;
1428 var parts = column.path.split('.');
1430 angular.forEach(parts, function(step, idx) {
1431 // object is not fleshed to the expected extent
1432 if (!obj || typeof obj != 'object') {
1437 var cls = obj.classname;
1438 if (cls && (class_obj = egCore.idl.classes[cls])) {
1439 idl_field = class_obj.field_map[step];
1440 obj = obj[step] ? obj[step]() : '';
1442 if (angular.isFunction(obj[step])) {
1450 // We found a nested IDL object which may or may not have
1451 // been configured as a top-level column. Grab the datatype.
1452 if (idl_field && !column.datatype)
1453 column.datatype = idl_field.datatype;
1455 if (obj === null || obj === undefined || obj === '') return '';
1461 instance : function(args) {
1462 return new GridDataProvider(args);
1469 // Factory service for egGridDataManager instances, which are
1470 // responsible for collecting flattened grid data.
1471 .factory('egGridFlatDataProvider',
1472 ['$q','egCore','egGridDataProvider',
1473 function($q , egCore , egGridDataProvider) {
1476 instance : function(args) {
1477 var provider = egGridDataProvider.instance(args);
1479 provider.get = function(offset, count) {
1481 // no query means no call
1482 if (!provider.query ||
1483 angular.equals(provider.query, {}))
1486 // find all of the currently visible columns
1487 var queryFields = {}
1488 angular.forEach(provider.columnsProvider.columns,
1490 // only query IDL-tracked columns
1491 if (!col.adhoc && (col.required || col.visible))
1492 queryFields[col.name] = col.path;
1496 return egCore.net.request(
1498 'open-ils.fielder.flattened_search',
1499 egCore.auth.token(), provider.idlClass,
1500 queryFields, provider.query,
1501 { sort : provider.sort,
1507 //provider.itemFieldValue = provider.flatItemFieldValue;
1514 .directive('egGridColumnDragSource', function() {
1517 require : '^egGrid',
1518 link : function(scope, element, attrs, egGridCtrl) {
1519 angular.element(element).attr('draggable', 'true');
1521 element.bind('dragstart', function(e) {
1522 egGridCtrl.dragColumn = attrs.column;
1523 egGridCtrl.dragType = attrs.dragType || 'move'; // or resize
1524 egGridCtrl.colResizeDir = 0;
1526 if (egGridCtrl.dragType == 'move') {
1527 // style the column getting moved
1528 angular.element(e.target).addClass(
1529 'eg-grid-column-move-handle-active');
1533 element.bind('dragend', function(e) {
1534 if (egGridCtrl.dragType == 'move') {
1535 angular.element(e.target).removeClass(
1536 'eg-grid-column-move-handle-active');
1543 .directive('egGridColumnDragDest', function() {
1546 require : '^egGrid',
1547 link : function(scope, element, attrs, egGridCtrl) {
1549 element.bind('dragover', function(e) { // required for drop
1550 e.stopPropagation();
1552 e.dataTransfer.dropEffect = 'move';
1554 if (egGridCtrl.colResizeDir == 0) return; // move
1556 var cols = egGridCtrl.columnsProvider;
1557 var srcCol = egGridCtrl.dragColumn;
1558 var srcColIdx = cols.indexOf(srcCol);
1560 if (egGridCtrl.colResizeDir == -1) {
1561 if (cols.indexOf(attrs.column) <= srcColIdx) {
1562 egGridCtrl.modifyColumnFlex(
1563 egGridCtrl.columnsProvider.findColumn(
1564 egGridCtrl.dragColumn), -1);
1565 if (cols.columns[srcColIdx+1]) {
1566 // source column shrinks by one, column to the
1567 // right grows by one.
1568 egGridCtrl.modifyColumnFlex(
1569 cols.columns[srcColIdx+1], 1);
1574 if (cols.indexOf(attrs.column) > srcColIdx) {
1575 egGridCtrl.modifyColumnFlex(
1576 egGridCtrl.columnsProvider.findColumn(
1577 egGridCtrl.dragColumn), 1);
1578 if (cols.columns[srcColIdx+1]) {
1579 // source column grows by one, column to the
1580 // right grows by one.
1581 egGridCtrl.modifyColumnFlex(
1582 cols.columns[srcColIdx+1], -1);
1590 element.bind('dragenter', function(e) {
1591 e.stopPropagation();
1593 if (egGridCtrl.dragType == 'move') {
1594 angular.element(e.target).addClass('eg-grid-col-hover');
1596 // resize grips are on the right side of each column.
1597 // dragenter will either occur on the source column
1598 // (dragging left) or the column to the right.
1599 if (egGridCtrl.colResizeDir == 0) {
1600 if (egGridCtrl.dragColumn == attrs.column) {
1601 egGridCtrl.colResizeDir = -1; // west
1603 egGridCtrl.colResizeDir = 1; // east
1609 element.bind('dragleave', function(e) {
1610 e.stopPropagation();
1612 if (egGridCtrl.dragType == 'move') {
1613 angular.element(e.target).removeClass('eg-grid-col-hover');
1617 element.bind('drop', function(e) {
1618 e.stopPropagation();
1620 egGridCtrl.colResizeDir = 0;
1621 if (egGridCtrl.dragType == 'move') {
1622 angular.element(e.target).removeClass('eg-grid-col-hover');
1623 egGridCtrl.onColumnDrop(attrs.column); // move the column
1630 .directive('egGridMenuItem', function() {
1633 require : '^egGrid',
1639 handler : '=', // onclick handler function
1640 divider : '=', // if true, show a divider only
1641 handlerData : '=', // if set, passed as second argument to handler
1642 disabled : '=', // function
1643 hidden : '=' // function
1645 link : function(scope, element, attrs, egGridCtrl) {
1646 egGridCtrl.addMenuItem({
1647 checkbox : scope.checkbox,
1648 checked : scope.checked ? true : false,
1649 label : scope.label,
1650 standalone : scope.standalone ? true : false,
1651 handler : scope.handler,
1652 divider : scope.divider,
1653 disabled : scope.disabled,
1654 hidden : scope.hidden,
1655 handlerData : scope.handlerData
1665 * Translates bare IDL object values into display values.
1666 * 1. Passes dates through the angular date filter
1667 * 2. Translates bools to Booleans so the browser can display translated
1668 * value. (Though we could manually translate instead..)
1669 * Others likely to follow...
1671 .filter('egGridValueFilter', ['$filter', function($filter) {
1672 return function(value, column) {
1673 switch(column.datatype) {
1676 // Browser will translate true/false for us
1678 case '1' : // legacy
1682 case '0' : // legacy
1685 // value may be null, '', etc.
1686 default : return '';
1689 // canned angular date filter FTW
1690 if (!column.dateformat)
1691 column.dateformat = 'shortDate';
1692 return $filter('date')(value, column.dateformat);
1694 return $filter('currency')(value);