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: object containing function to conditionally apply
61 // optional: object that enables status icon field and contains
62 // function to handle what status icons should exist and why.
65 // optional primary grid label
68 // if true, use the IDL class label as the mainLabel
71 // optional context menu label
74 dateformat : '@', // optional: passed down to egGridValueFilter
75 datecontext: '@', // optional: passed down to egGridValueFilter to choose TZ
76 datefilter: '@', // optional: passed down to egGridValueFilter to choose specialized date filters
77 dateonlyinterval: '@', // optional: passed down to egGridValueFilter to choose a "better" format
79 // Hash of control functions.
81 // These functions are defined by the calling scope and
82 // invoked as-is by the grid w/ the specified parameters.
84 // collectStarted : function() {}
85 // itemRetrieved : function(item) {}
86 // allItemsRetrieved : function() {}
89 // If defined, the grid will watch the return value from
90 // the function defined at watchQuery on each digest and
91 // re-draw the grid when query changes occur.
93 // watchQuery : function() { /* return grid query */ }
96 // These functions are defined by the grid and thus
97 // replace any values defined for these attributes from the
100 // activateItem : function(item) {}
101 // allItems : function(allItems) {}
102 // selectedItems : function(selected) {}
103 // selectItems : function(ids) {}
104 // setQuery : function(queryStruct) {} // causes reload
105 // setSort : function(sortSturct) {} // causes reload
109 // TODO: avoid hard-coded url
110 templateUrl : '/eg/staff/share/t_autogrid',
112 link : function(scope, element, attrs) {
114 // Give the grid config loading steps time to fetch the
115 // workstation setting and apply columns before loading data.
116 var loadPromise = scope.configLoadPromise || $q.when();
117 loadPromise.then(function() {
119 // load auto fields after eg-grid-field's so they are not clobbered
120 scope.handleAutoFields();
123 scope.grid_element = element;
126 $(element).attr('id', attrs.persistKey);
130 .find('.eg-grid-content-body')
131 .bind('contextmenu', scope.showActionContextMenu);
136 '$scope','$q','egCore','egGridFlatDataProvider','$location',
137 'egGridColumnsProvider','$filter','$window','$sce','$timeout',
138 'egProgressDialog','$uibModal','egConfirmDialog','egStrings',
139 function($scope, $q , egCore, egGridFlatDataProvider , $location,
140 egGridColumnsProvider , $filter , $window , $sce , $timeout,
141 egProgressDialog, $uibModal , egConfirmDialog , egStrings) {
145 grid.init = function() {
148 $scope.showGridConf = false;
149 grid.totalCount = -1;
150 $scope.selected = {};
151 $scope.actionGroups = [{actions:[]}]; // Grouped actions for selected items
152 $scope.menuItems = []; // global actions
154 // returns true if any rows are selected.
155 $scope.hasSelected = function() {
156 return grid.getSelectedItems().length > 0 };
158 var features = ($scope.features) ?
159 $scope.features.split(',') : [];
160 delete $scope.features;
162 $scope.showIndex = (features.indexOf('-index') == -1);
164 $scope.allowAll = (features.indexOf('allowAll') > -1);
165 $scope.startSelected = $scope.selectAll = (features.indexOf('startSelected') > -1);
166 $scope.showActions = (features.indexOf('-actions') == -1);
167 $scope.showPagination = (features.indexOf('-pagination') == -1);
168 $scope.showPicker = (features.indexOf('-picker') == -1);
170 $scope.showMenu = (features.indexOf('-menu') == -1);
172 // remove some unneeded values from the scope to reduce bloat
174 grid.idlClass = $scope.idlClass;
175 delete $scope.idlClass;
177 grid.persistKey = $scope.persistKey;
178 delete $scope.persistKey;
180 var stored_limit = 0;
181 if ($scope.showPagination) {
182 // localStorage of grid limits is deprecated. Limits
183 // are now stored along with the columns configuration.
184 // Values found in localStorage will be migrated upon
186 if (grid.persistKey) {
187 var stored_limit = Number(
188 egCore.hatch.getLocalItem('eg.grid.' + grid.persistKey + '.limit')
192 stored_limit = 10000; // maybe support "Inf"?
195 grid.limit = Number(stored_limit) || Number($scope.pageSize) || 25;
197 grid.indexField = $scope.idField;
198 delete $scope.idField;
200 grid.dataProvider = $scope.itemsProvider;
202 if (!grid.indexField && grid.idlClass)
203 grid.indexField = egCore.idl.classes[grid.idlClass].pkey;
205 grid.columnsProvider = egGridColumnsProvider.instance({
206 idlClass : grid.idlClass,
207 clientSort : (features.indexOf('clientsort') > -1 && features.indexOf('-clientsort') == -1),
208 defaultToHidden : (features.indexOf('-display') > -1),
209 defaultToNoSort : (features.indexOf('-sort') > -1),
210 defaultToNoMultiSort : (features.indexOf('-multisort') > -1),
211 defaultDateFormat : $scope.dateformat,
212 defaultDateContext : $scope.datecontext,
213 defaultDateFilter : $scope.datefilter,
214 defaultDateOnlyInterval : $scope.dateonlyinterval
216 $scope.canMultiSelect = (features.indexOf('-multiselect') == -1);
218 $scope.handleAutoFields = function() {
219 if ($scope.autoFields) {
220 if (grid.autoLabel) {
222 egCore.idl.classes[grid.idlClass].label;
224 grid.columnsProvider.compileAutoColumns();
225 delete $scope.autoFields;
229 if (!grid.dataProvider) {
230 // no provider, um, provided.
231 // Use a flat data provider
233 grid.selfManagedData = true;
234 grid.dataProvider = egGridFlatDataProvider.instance({
235 indexField : grid.indexField,
236 idlClass : grid.idlClass,
237 columnsProvider : grid.columnsProvider,
242 // make grid ref available in get() to set totalCount, if known.
243 // this allows us disable the 'next' paging button correctly
244 grid.dataProvider.grid = grid;
246 grid.dataProvider.columnsProvider = grid.columnsProvider;
248 $scope.itemFieldValue = grid.dataProvider.itemFieldValue;
249 $scope.indexValue = function(item) {
250 return grid.indexValue(item)
253 grid.applyControlFunctions();
255 $scope.configLoadPromise = grid.loadConfig().then(function() {
256 // link columns to scope after loadConfig(), since it
257 // replaces the columns array.
258 $scope.columns = grid.columnsProvider.columns;
261 // NOTE: grid.collect() is first called from link(), not here.
264 // link our control functions into the gridControls
265 // scope object so the caller can access them.
266 grid.applyControlFunctions = function() {
268 // we use some of these controls internally, so sett
269 // them up even if the caller doesn't request them.
270 var controls = $scope.gridControls || {};
272 controls.columnMap = function() {
274 angular.forEach(grid.columnsProvider.columns, function (c) {
280 controls.columnsProvider = function() {
281 return grid.columnsProvider;
284 // link in the control functions
285 controls.selectedItems = function() {
286 return grid.getSelectedItems()
289 controls.selectItemsByValue = function(c,v) {
290 return grid.selectItemsByValue(c,v)
293 controls.allItems = function() {
297 controls.selectItems = function(ids) {
299 $scope.selected = {};
300 angular.forEach(ids, function(i) {
301 $scope.selected[''+i] = true;
305 // if the caller provided a functional setQuery,
306 // extract the value before replacing it
307 if (controls.setQuery) {
308 grid.dataProvider.query =
312 controls.setQuery = function(query) {
313 grid.dataProvider.query = query;
317 if (controls.watchQuery) {
318 // capture the initial query value
319 grid.dataProvider.query = controls.watchQuery();
322 $scope.gridWatchQuery = controls.watchQuery;
323 $scope.$watch('gridWatchQuery()', function(newv) {
324 controls.setQuery(newv);
328 // if the caller provided a functional setSort
329 // extract the value before replacing it
330 grid.dataProvider.sort =
331 controls.setSort ? controls.setSort() : [];
333 controls.setSort = function(sort) {
337 controls.refresh = function(noReset) {
338 if (!noReset) grid.offset = 0;
342 controls.prepend = function(limit) {
346 controls.setLimit = function(limit,forget) {
348 if (!forget && grid.persistKey) {
352 controls.getLimit = function() {
355 controls.setOffset = function(offset) {
356 grid.offset = offset;
358 controls.getOffset = function() {
362 controls.saveConfig = function () {
363 return $scope.saveConfig();
366 grid.dataProvider.refresh = controls.refresh;
367 grid.dataProvider.prepend = controls.prepend;
368 grid.controls = controls;
371 // If a menu item provides its own HTML template, translate it,
372 // using the menu item for the template scope.
373 // note: $sce is required to avoid security restrictions and
374 // is OK here, since the template comes directly from a
375 // local HTML template (not user input).
376 $scope.translateMenuItemTemplate = function(item) {
377 var html = egCore.strings.$replace(item.template, {item : item});
378 return $sce.trustAsHtml(html);
381 // add a new (global) grid menu item
382 grid.addMenuItem = function(item) {
383 $scope.menuItems.push(item);
384 var handler = item.handler;
385 item.handler = function() {
386 $scope.gridMenuIsOpen = false; // close menu
389 item.handlerData, grid.getSelectedItems());
394 // add a selected-items action
395 grid.addAction = function(act) {
397 $scope.actionGroups.forEach(function(g){
398 if (g.label === act.group) {
404 $scope.actionGroups.push({
411 // remove the stored column configuration preferenc, then recover
412 // the column visibility information from the initial page load.
413 $scope.resetColumns = function() {
414 $scope.gridColumnPickerIsOpen = false;
415 egCore.hatch.removeItem('eg.grid.' + grid.persistKey)
417 grid.columnsProvider.reset();
418 if (grid.selfManagedData) grid.collect();
422 $scope.showAllColumns = function() {
423 $scope.gridColumnPickerIsOpen = false;
424 grid.columnsProvider.showAllColumns();
425 if (grid.selfManagedData) grid.collect();
428 $scope.hideAllColumns = function() {
429 $scope.gridColumnPickerIsOpen = false;
430 grid.columnsProvider.hideAllColumns();
431 // note: no need to fetch new data if no columns are visible
434 $scope.toggleColumnVisibility = function(col) {
435 $scope.gridColumnPickerIsOpen = false;
436 col.visible = !col.visible;
438 // egGridFlatDataProvider only retrieves data to be
439 // displayed. When column visibility changes, it's
440 // necessary to fetch the newly visible column data.
441 if (grid.selfManagedData) grid.collect();
444 // save the columns configuration (position, sort, width) to
445 // eg.grid.<persist-key>
446 $scope.saveConfig = function() {
447 $scope.gridColumnPickerIsOpen = false;
449 if (!grid.persistKey) {
451 "Cannot save settings without a grid persist-key");
455 // only store information about visible columns.
456 var cols = grid.columnsProvider.columns.filter(
457 function(col) {return Boolean(col.visible) });
459 // now scrunch the data down to just the needed info
460 cols = cols.map(function(col) {
461 var c = {name : col.name}
462 // Apart from the name, only store non-default values.
463 // No need to store col.visible, since that's implicit
464 if (col.align != 'left') c.align = col.align;
465 if (col.flex != 2) c.flex = col.flex;
466 if (Number(col.sort)) c.sort = Number(c.sort);
476 egCore.hatch.setItem('eg.grid.' + grid.persistKey, conf)
478 // Save operation performed from the grid configuration UI.
479 // Hide the configuration UI and re-draw w/ sort applied
480 if ($scope.showGridConf)
481 $scope.toggleConfDisplay();
483 // Once a version-2 grid config is saved (with limit
484 // included) we can remove the local limit pref.
485 egCore.hatch.removeLocalItem(
486 'eg.grid.' + grid.persistKey + '.limit');
491 // load the columns configuration (position, sort, width) from
492 // eg.grid.<persist-key> and apply the loaded settings to the
493 // columns on our columnsProvider
494 grid.loadConfig = function() {
495 if (!grid.persistKey) return $q.when();
497 return egCore.hatch.getItem('eg.grid.' + grid.persistKey)
498 .then(function(conf) {
501 // load all column options before validating saved columns
502 $scope.handleAutoFields();
504 var columns = grid.columnsProvider.columns;
507 if (Array.isArray(conf)) {
509 'upgrading version 1 grid config to version 2');
517 grid.limit = Number(conf.limit);
520 angular.forEach(conf.columns, function(col) {
521 var grid_col = columns.filter(
522 function(c) {return c.name == col.name})[0];
525 // saved column does not match a column in the
526 // current grid. skip it.
530 grid_col.align = col.align || 'left';
531 grid_col.flex = col.flex || 2;
532 grid_col.sort = col.sort || 0;
533 // all saved columns are assumed to be true
534 grid_col.visible = true;
536 .filter(function (c) {
537 return c.name == grid_col.name;
540 new_cols.push(grid_col);
543 // columns which are not expressed within the saved
544 // configuration are marked as non-visible and
545 // appended to the end of the new list of columns.
546 angular.forEach(columns, function(col) {
547 var found = conf.columns.filter(
548 function(c) {return (c.name == col.name)})[0];
555 grid.columnsProvider.columns = new_cols;
561 $scope.onContextMenu = function($event) {
562 var col = angular.element($event.target).attr('column');
563 console.log('selected column ' + col);
566 $scope.page = function() {
567 return (grid.offset / grid.limit) + 1;
570 $scope.goToPage = function(page) {
572 if (angular.isNumber(page) && page > 0) {
573 grid.offset = (page - 1) * grid.limit;
578 $scope.offset = function(o) {
579 if (angular.isNumber(o))
584 $scope.limit = function(l) {
585 if (angular.isNumber(l)) {
587 if (grid.persistKey) {
594 $scope.onFirstPage = function() {
595 return grid.offset == 0;
598 $scope.hasNextPage = function() {
599 // we have less data than requested, there must
600 // not be any more pages
601 if (grid.count() < grid.limit) return false;
603 // if the total count is not known, assume that a full
604 // page of data implies more pages are available.
605 if (grid.totalCount == -1) return true;
607 // we have a full page of data, but is there more?
608 return grid.totalCount > (grid.offset + grid.count());
611 $scope.incrementPage = function() {
612 grid.offset += grid.limit;
616 $scope.decrementPage = function() {
617 if (grid.offset < grid.limit) {
620 grid.offset -= grid.limit;
625 // number of items loaded for the current page of results
626 grid.count = function() {
627 return $scope.items.length;
630 // returns the unique identifier value for the provided item
631 // for internal consistency, indexValue is always coerced
633 grid.indexValue = function(item) {
634 if (angular.isObject(item)) {
636 if (angular.isFunction(item[grid.indexField]))
637 return ''+item[grid.indexField]();
638 return ''+item[grid.indexField]; // flat data
641 // passed a non-object; assume it's an index
645 // fires the hide handler function for a context action
646 $scope.actionHide = function(action) {
647 if (typeof action.hide == 'undefined') {
650 if (angular.isFunction(action.hide))
651 return action.hide(action);
655 // fires the disable handler function for a context action
656 $scope.actionDisable = function(action) {
657 if (typeof action.disabled == 'undefined') {
660 if (angular.isFunction(action.disabled))
661 return action.disabled(action);
662 return action.disabled;
665 // fires the action handler function for a context action
666 $scope.actionLauncher = function(action) {
667 if (!action.handler) {
669 'No handler specified for "' + action.label + '"');
673 action.handler(grid.getSelectedItems());
675 console.error('Error executing handler for "'
676 + action.label + '" => ' + E + "\n" + E.stack);
679 if ($scope.action_context_showing) $scope.hideActionContextMenu();
684 $scope.hideActionContextMenu = function () {
685 $($scope.menu_dom).css({
687 width: $scope.action_context_width,
688 top: $scope.action_context_y,
689 left: $scope.action_context_x
691 $($scope.action_context_parent).append($scope.menu_dom);
692 $scope.action_context_oldy = $scope.action_context_oldx = 0;
693 $('body').unbind('click.remove_context_menu_'+$scope.action_context_index);
694 $scope.action_context_showing = false;
697 $scope.action_context_showing = false;
698 $scope.showActionContextMenu = function ($event) {
700 // Have to gather these here, instead of inside link()
701 if (!$scope.menu_dom) $scope.menu_dom = $($scope.grid_element).find('.grid-action-dropdown')[0];
702 if (!$scope.action_context_parent) $scope.action_context_parent = $($scope.menu_dom).parent();
704 // we need the the row that got right-clicked...
705 var e = $event.target; // the DOM element
706 var s = undefined; // the angular scope for that element
707 while(e){ // searching for the row
708 // abort & use the browser default context menu for links (lp1669856):
709 if(e.tagName.toLowerCase() === 'a' && e.href){ return true; }
710 s = angular.element(e).scope();
711 if(s.hasOwnProperty('item')){ break; }
714 // select the right-clicked row if it is not already selected (lp1776557):
715 if(!$scope.selected[grid.indexValue(s.item)]){ $event.target.click(); }
717 if (!$scope.action_context_showing) {
718 $scope.action_context_width = $($scope.menu_dom).css('width');
719 $scope.action_context_y = $($scope.menu_dom).css('top');
720 $scope.action_context_x = $($scope.menu_dom).css('left');
721 $scope.action_context_showing = true;
722 $scope.action_context_index = Math.floor((Math.random() * 1000) + 1);
724 $('body').append($($scope.menu_dom));
725 $('body').bind('click.remove_context_menu_'+$scope.action_context_index, $scope.hideActionContextMenu);
728 $($scope.menu_dom).css({
730 width: $scope.action_context_width,
738 // returns the list of selected item objects
739 grid.getSelectedItems = function() {
740 return $scope.items.filter(
742 return Boolean($scope.selected[grid.indexValue(item)]);
747 grid.getItemByIndex = function(index) {
748 for (var i = 0; i < $scope.items.length; i++) {
749 var item = $scope.items[i];
750 if (grid.indexValue(item) == index)
755 // selects one row after deselecting all of the others
756 grid.selectOneItem = function(index) {
757 $scope.selected = {};
758 $scope.selected[index] = true;
761 // selects items by a column value, first clearing selected list.
762 // we overwrite the object so that we can watch $scope.selected
763 grid.selectItemsByValue = function(column, value) {
764 $scope.selected = {};
765 angular.forEach($scope.items, function(item) {
767 if (angular.isFunction(item[column]))
768 col_value = item[column]();
770 col_value = item[column];
772 if (value == col_value) $scope.selected[grid.indexValue(item)] = true
776 // selects or deselects an item, without affecting the others.
777 // returns true if the item is selected; false if de-selected.
778 // we overwrite the object so that we can watch $scope.selected
779 grid.toggleSelectOneItem = function(index) {
780 if ($scope.selected[index]) {
781 delete $scope.selected[index];
782 $scope.selected = angular.copy($scope.selected);
785 $scope.selected[index] = true;
786 $scope.selected = angular.copy($scope.selected);
791 $scope.updateSelected = function () {
792 return $scope.selected = angular.copy($scope.selected);
795 grid.selectAllItems = function() {
796 angular.forEach($scope.items, function(item) {
797 $scope.selected[grid.indexValue(item)] = true
799 $scope.selected = angular.copy($scope.selected);
802 $scope.$watch('selectAll', function(newVal) {
804 grid.selectAllItems();
806 $scope.selected = {};
810 if ($scope.onSelect) {
811 $scope.$watch('selected', function(newVal) {
812 $scope.onSelect(grid.getSelectedItems());
813 if ($scope.afterSelect) $scope.afterSelect();
817 // returns true if item1 appears in the list before item2;
818 // false otherwise. this is slightly more efficient that
819 // finding the position of each then comparing them.
820 // item1 / item2 may be an item or an item index
821 grid.itemComesBefore = function(itemOrIndex1, itemOrIndex2) {
822 var idx1 = grid.indexValue(itemOrIndex1);
823 var idx2 = grid.indexValue(itemOrIndex2);
825 // use for() for early exit
826 for (var i = 0; i < $scope.items.length; i++) {
827 var idx = grid.indexValue($scope.items[i]);
828 if (idx == idx1) return true;
829 if (idx == idx2) return false;
834 // 0-based position of item in the current data set
835 grid.indexOf = function(item) {
836 var idx = grid.indexValue(item);
837 for (var i = 0; i < $scope.items.length; i++) {
838 if (grid.indexValue($scope.items[i]) == idx)
844 grid.modifyColumnFlex = function(column, val) {
846 // prevent flex:0; use hiding instead
850 $scope.modifyColumnFlex = function(col, val) {
851 $scope.lastModColumn = col;
852 grid.modifyColumnFlex(col, val);
855 $scope.isLastModifiedColumn = function(col) {
856 if ($scope.lastModColumn)
857 return $scope.lastModColumn === col;
861 grid.modifyColumnPos = function(col, diff) {
862 var srcIdx, targetIdx;
863 angular.forEach(grid.columnsProvider.columns,
864 function(c, i) { if (c.name == col.name) srcIdx = i });
866 targetIdx = srcIdx + diff;
869 } else if (targetIdx >= grid.columnsProvider.columns.length) {
870 // Target index follows the last visible column.
872 angular.forEach(grid.columnsProvider.columns,
873 function(column, idx) {
874 if (column.visible) lastVisible = idx;
878 // When moving a column (down) causes one or more
879 // visible columns to shuffle forward, our column
880 // moves into the slot of the last visible column.
881 // Otherwise, put it into the slot directly following
882 // the last visible column.
884 srcIdx <= lastVisible ? lastVisible : lastVisible + 1;
887 // Splice column out of old position, insert at new position.
888 grid.columnsProvider.columns.splice(srcIdx, 1);
889 grid.columnsProvider.columns.splice(targetIdx, 0, col);
892 $scope.modifyColumnPos = function(col, diff) {
893 $scope.lastModColumn = col;
894 return grid.modifyColumnPos(col, diff);
898 // handles click, control-click, and shift-click
899 $scope.handleRowClick = function($event, item) {
900 var index = grid.indexValue(item);
902 var origSelected = Object.keys($scope.selected);
904 if (!$scope.canMultiSelect) {
905 grid.selectOneItem(index);
906 grid.lastSelectedItemIndex = index;
910 if ($event.ctrlKey || $event.metaKey /* mac command */) {
912 if (grid.toggleSelectOneItem(index))
913 grid.lastSelectedItemIndex = index;
915 } else if ($event.shiftKey) {
918 if (!grid.lastSelectedItemIndex ||
919 index == grid.lastSelectedItemIndex) {
920 grid.selectOneItem(index);
921 grid.lastSelectedItemIndex = index;
925 var selecting = false;
926 var ascending = grid.itemComesBefore(
927 grid.lastSelectedItemIndex, item);
929 grid.indexOf(grid.lastSelectedItemIndex);
931 // update to new last-selected
932 grid.lastSelectedItemIndex = index;
934 // select each row between the last selected and
935 // currently selected items
937 startPos += ascending ? 1 : -1;
938 var curItem = $scope.items[startPos];
940 var curIdx = grid.indexValue(curItem);
941 $scope.selected[curIdx] = true;
942 if (curIdx == index) break; // all done
944 $scope.selected = angular.copy($scope.selected);
948 grid.selectOneItem(index);
949 grid.lastSelectedItemIndex = index;
953 // Builds a sort expression from column sort priorities.
954 // called on page load and any time the priorities are modified.
955 grid.compileSort = function() {
956 var sortList = grid.columnsProvider.columns.filter(
957 function(col) { return Number(col.sort) != 0 }
960 if (Math.abs(a.sort) < Math.abs(b.sort))
966 if (sortList.length) {
967 grid.dataProvider.sort = sortList.map(function(col) {
969 blob[col.name] = col.sort < 0 ? 'desc' : 'asc';
975 // builds a sort expression using a single column,
976 // toggling between ascending and descending sort.
977 $scope.quickSort = function(col_name) {
978 var sort = grid.dataProvider.sort;
979 if (sort && sort.length &&
980 sort[0] == col_name) {
982 blob[col_name] = 'desc';
983 grid.dataProvider.sort = [blob];
985 grid.dataProvider.sort = [col_name];
992 // show / hide the grid configuration row
993 $scope.toggleConfDisplay = function() {
994 if ($scope.showGridConf) {
995 $scope.showGridConf = false;
996 if (grid.columnsProvider.hasSortableColumn()) {
997 // only refresh the grid if the user has the
998 // ability to modify the sort priorities.
1004 $scope.showGridConf = true;
1007 delete $scope.lastModColumn;
1008 $scope.gridColumnPickerIsOpen = false;
1011 // called when a dragged column is dropped onto itself
1012 // or any other column
1013 grid.onColumnDrop = function(target) {
1014 if (angular.isUndefined(target)) return;
1015 if (target == grid.dragColumn) return;
1016 var srcIdx, targetIdx, srcCol;
1017 angular.forEach(grid.columnsProvider.columns,
1018 function(col, idx) {
1019 if (col.name == grid.dragColumn) {
1022 } else if (col.name == target) {
1028 if (srcIdx < targetIdx) targetIdx--;
1030 // move src column from old location to new location in
1031 // the columns array, then force a page refresh
1032 grid.columnsProvider.columns.splice(srcIdx, 1);
1033 grid.columnsProvider.columns.splice(targetIdx, 0, srcCol);
1037 // prepares a string for inclusion within a CSV document
1038 // by escaping commas and quotes and removing newlines.
1039 grid.csvDatum = function(str) {
1041 if (!str) return '';
1042 str = str.replace(/\n/g, '');
1043 if (str.match(/\,/) || str.match(/"/)) {
1044 str = str.replace(/"/g, '""');
1045 str = '"' + str + '"';
1050 /** Export the full data set as CSV.
1052 * 1. User clicks the 'download csv' link
1053 * 2. All grid data is retrieved asychronously
1054 * 3. Once all data is all present and CSV-ized, the download
1055 * attributes are linked to the href.
1056 * 4. The href .click() action is prgrammatically fired again,
1057 * telling the browser to download the data, now that the
1058 * data is available for download.
1059 * 5 Once downloaded, the href attributes are reset.
1061 grid.csvExportInProgress = false;
1062 $scope.generateCSVExportURL = function($event) {
1064 if (grid.csvExportInProgress) {
1065 // This is secondary href click handler. Give the
1066 // browser a moment to start the download, then reset
1067 // the CSV download attributes / state.
1070 $scope.csvExportURL = '';
1071 $scope.csvExportFileName = '';
1072 grid.csvExportInProgress = false;
1078 grid.csvExportInProgress = true;
1079 $scope.gridColumnPickerIsOpen = false;
1081 // let the file name describe the grid
1082 $scope.csvExportFileName =
1083 ($scope.mainLabel || grid.persistKey || 'eg_grid_data')
1084 .replace(/\s+/g, '_') + '_' + $scope.page();
1086 // toss the CSV into a Blob and update the export URL
1087 grid.generateCSV().then(function(csv) {
1088 var blob = new Blob([csv], {type : 'text/plain'});
1089 $scope.csvExportURL =
1090 ($window.URL || $window.webkitURL).createObjectURL(blob);
1092 // Fire the 2nd click event now that the browser has
1093 // information on how to download the CSV file.
1094 $timeout(function() {$event.target.click()});
1099 * TODO: does this serve any purpose given we can
1100 * print formatted HTML? If so, generateCSV() now
1101 * returns a promise, needs light refactoring...
1102 $scope.printCSV = function() {
1103 $scope.gridColumnPickerIsOpen = false;
1104 egCore.print.print({
1105 context : 'default',
1106 content : grid.generateCSV(),
1107 content_type : 'text/plain'
1112 // Given a row item and column definition, extract the
1113 // text content for printing. Templated columns must be
1114 // processed and parsed as HTML, then boiled down to their
1116 grid.getItemTextContent = function(item, col) {
1119 val = $scope.translateCellTemplate(col, item);
1121 var node = new DOMParser()
1122 .parseFromString(val, 'text/html');
1123 val = $(node).text();
1126 val = grid.dataProvider.itemFieldValue(item, col);
1127 if (val === null || val === undefined || val === '') return '';
1128 val = $filter('egGridValueFilter')(val, col, item);
1133 $scope.getHtmlTooltip = function(col, item) {
1134 return grid.getItemTextContent(item, col);
1138 * Fetches all grid data and transates each item into a simple
1139 * key-value pair of column name => text-value.
1140 * Included in the response for convenience is the list of
1141 * currently visible column definitions.
1142 * TODO: currently fetches a maximum of 10k rows. Does this
1143 * need to be configurable?
1145 grid.getAllItemsAsText = function() {
1146 var text_items = [];
1148 // we don't know the total number of rows we're about
1149 // to retrieve, but we can indicate the number retrieved
1150 // so far as each item arrives.
1151 egProgressDialog.open({value : 0});
1153 var visible_cols = grid.columnsProvider.columns.filter(
1154 function(c) { return c.visible });
1156 return grid.dataProvider.get(0, 10000).then(
1158 return {items : text_items, columns : visible_cols};
1162 egProgressDialog.increment();
1164 angular.forEach(visible_cols, function(col) {
1165 text_item[col.name] =
1166 grid.getItemTextContent(item, col);
1168 text_items.push(text_item);
1170 ).finally(egProgressDialog.close);
1173 // Fetch "all" of the grid data, translate it into print-friendly
1174 // text, and send it to the printer service.
1175 $scope.printHTML = function() {
1176 $scope.gridColumnPickerIsOpen = false;
1177 return grid.getAllItemsAsText().then(function(text_items) {
1178 return egCore.print.print({
1179 template : 'grid_html',
1185 $scope.showColumnDialog = function() {
1186 return $uibModal.open({
1187 templateUrl: './share/t_grid_columns',
1190 controller: ['$scope', '$uibModalInstance',
1191 function($dialogScope, $uibModalInstance) {
1192 $dialogScope.modifyColumnPos = $scope.modifyColumnPos;
1193 $dialogScope.disableMultiSort = $scope.disableMultiSort;
1194 $dialogScope.columns = $scope.columns;
1196 // Push visible columns to the top of the list
1197 $dialogScope.elevateVisible = function() {
1199 angular.forEach($dialogScope.columns, function(col) {
1200 if (col.visible) new_cols.push(col);
1202 angular.forEach($dialogScope.columns, function(col) {
1203 if (!col.visible) new_cols.push(col);
1206 // Update all references to the list of columns
1207 $dialogScope.columns =
1209 grid.columnsProvider.columns =
1213 $dialogScope.toggle = function(col) {
1214 col.visible = !Boolean(col.visible);
1216 $dialogScope.ok = $dialogScope.cancel = function() {
1217 delete $scope.lastModColumn;
1218 $uibModalInstance.close()
1225 // generates CSV for the currently visible grid contents
1226 grid.generateCSV = function() {
1227 return grid.getAllItemsAsText().then(function(text_items) {
1228 var columns = text_items.columns;
1229 var items = text_items.items;
1233 angular.forEach(columns, function(col) {
1234 csvStr += grid.csvDatum(col.label);
1238 csvStr = csvStr.replace(/,$/,'\n');
1241 angular.forEach(items, function(item) {
1242 angular.forEach(columns, function(col) {
1243 csvStr += grid.csvDatum(item[col.name]);
1246 csvStr = csvStr.replace(/,$/,'\n');
1253 // Interpolate the value for column.linkpath within the context
1254 // of the row item to generate the final link URL.
1255 $scope.generateLinkPath = function(col, item) {
1256 return egCore.strings.$replace(col.linkpath, {item : item});
1259 // If a column provides its own HTML template, translate it,
1260 // using the current item for the template scope.
1261 // note: $sce is required to avoid security restrictions and
1262 // is OK here, since the template comes directly from a
1263 // local HTML template (not user input).
1264 $scope.translateCellTemplate = function(col, item) {
1265 var html = egCore.strings.$replace(col.template, {item : item});
1266 return $sce.trustAsHtml(html);
1269 $scope.collect = function() { grid.collect() }
1272 $scope.confirmAllowAllAndCollect = function(){
1273 egConfirmDialog.open(egStrings.CONFIRM_LONG_RUNNING_ACTION_ALL_ROWS_TITLE,
1274 egStrings.CONFIRM_LONG_RUNNING_ACTION_MSG)
1278 $scope.limit(10000);
1283 // asks the dataProvider for a page of data
1284 grid.collect = function() {
1286 // avoid firing the collect if there is nothing to collect.
1287 if (grid.selfManagedData && !grid.dataProvider.query) return;
1289 if (grid.collecting) return; // avoid parallel collect()
1290 grid.collecting = true;
1292 console.debug('egGrid.collect() offset='
1293 + grid.offset + '; limit=' + grid.limit);
1295 // ensure all of our dropdowns are closed
1296 // TODO: git rid of these and just use dropdown-toggle,
1297 // which is more reliable.
1298 $scope.gridColumnPickerIsOpen = false;
1299 $scope.gridRowCountIsOpen = false;
1300 $scope.gridPageSelectIsOpen = false;
1303 $scope.selected = {};
1305 // Inform the caller we've asked the data provider
1306 // for data. This is useful for knowing when collection
1307 // has started (e.g. to display a progress dialg) when
1308 // using the stock (flattener) data provider, where the
1309 // user is not directly defining a get() handler.
1310 if (grid.controls.collectStarted)
1311 grid.controls.collectStarted(grid.offset, grid.limit);
1313 grid.dataProvider.get(grid.offset, grid.limit).then(
1315 if (grid.controls.allItemsRetrieved)
1316 grid.controls.allItemsRetrieved();
1321 $scope.items.push(item)
1322 if (grid.controls.itemRetrieved)
1323 grid.controls.itemRetrieved(item);
1324 if ($scope.selectAll)
1325 $scope.selected[grid.indexValue(item)] = true
1327 }).finally(function() {
1328 console.debug('egGrid.collect() complete');
1329 grid.collecting = false
1330 $scope.selected = angular.copy($scope.selected);
1334 grid.prepend = function(limit) {
1335 var ran_into_duplicate = false;
1336 var sort = grid.dataProvider.sort;
1337 if (sort && sort.length) {
1338 // If sorting is in effect, we have no way
1339 // of knowing that the new item should be
1340 // visible _if the sort order is retained_.
1341 // However, since the grids that do prepending in
1342 // the first place are ones where we always
1343 // want the new row to show up on top, we'll
1344 // remove the current sort options.
1345 grid.dataProvider.sort = [];
1347 if (grid.offset > 0) {
1348 // if we're prepending, we're forcing the
1349 // offset back to zero to display the top
1355 if (grid.collecting) return; // avoid parallel collect() or prepend()
1356 grid.collecting = true;
1357 console.debug('egGrid.prepend() starting');
1358 // Note that we can count on the most-recently added
1359 // item being at offset 0 in the data provider only
1360 // for arrayNotifier data sources that do not have
1361 // sort options currently set.
1362 grid.dataProvider.get(0, 1).then(
1367 var newIdx = grid.indexValue(item);
1368 angular.forEach($scope.items, function(existing) {
1369 if (grid.indexValue(existing) == newIdx) {
1370 console.debug('egGrid.prepend(): refusing to add duplicate item ' + newIdx);
1371 ran_into_duplicate = true;
1375 $scope.items.unshift(item);
1376 if (limit && $scope.items.length > limit) {
1377 // this accommodates the checkin grid that
1378 // allows the user to set a definite limit
1379 // without requiring that entire collect()
1380 $scope.items.length = limit;
1382 if ($scope.items.length > grid.limit) {
1383 $scope.items.length = grid.limit;
1385 if (grid.controls.itemRetrieved)
1386 grid.controls.itemRetrieved(item);
1387 if ($scope.selectAll)
1388 $scope.selected[grid.indexValue(item)] = true
1390 }).finally(function() {
1391 console.debug('egGrid.prepend() complete');
1392 grid.collecting = false;
1393 $scope.selected = angular.copy($scope.selected);
1394 if (ran_into_duplicate) {
1406 * eg-grid-field : used for collecting custom field data from the templates.
1407 * This directive does not direct display, it just passes data up to the
1410 .directive('egGridField', function() {
1412 require : '^egGrid',
1415 flesher: '=', // optional; function that can flesh a linked field, given the value
1416 comparator: '=', // optional; function that can sort the thing at the end of 'path'
1417 name : '@', // required; unique name
1418 path : '@', // optional; flesh path
1419 ignore: '@', // optional; fields to ignore when path is a wildcard
1420 label : '@', // optional; display label
1421 flex : '@', // optional; default flex width
1422 align : '@', // optional; default alignment, left/center/right
1423 dateformat : '@', // optional: passed down to egGridValueFilter
1424 datecontext: '@', // optional: passed down to egGridValueFilter to choose TZ
1425 datefilter: '@', // optional: passed down to egGridValueFilter to choose specialized date filters
1426 dateonlyinterval: '@', // optional: passed down to egGridValueFilter to choose a "better" format
1428 // if a field is part of an IDL object, but we are unable to
1429 // determine the class, because it's nested within a hash
1430 // (i.e. we can't navigate directly to the object via the IDL),
1431 // idlClass lets us specify the class. This is particularly
1432 // useful for nested wildcard fields.
1433 parentIdlClass : '@',
1435 // optional: for non-IDL columns, specifying a datatype
1436 // lets the caller control which display filter is used.
1437 // datatype should match the standard IDL datatypes.
1440 // optional hash of functions that can be imported into
1441 // the directive's scope; meant for cases where the "compiled"
1445 // optional: CSS class name that we want to have for this field.
1446 // Auto generated from path if nothing is passed in via eg-grid-field declaration
1449 link : function(scope, element, attrs, egGridCtrl) {
1451 // boolean fields are presented as value-less attributes
1461 'required' // if set, always fetch data for this column
1464 if (angular.isDefined(attrs[field]))
1465 scope[field] = true;
1469 scope.cssSelector = attrs['cssSelector'] ? attrs['cssSelector'] : "";
1471 // auto-generate CSS selector name for field if none declared in tt2 and there's a path
1472 if (scope.path && !scope.cssSelector){
1473 var cssClass = 'grid' + "." + scope.path;
1474 cssClass = cssClass.replace(/\./g,'-');
1475 element.addClass(cssClass);
1476 scope.cssSelector = cssClass;
1479 // any HTML content within the field is its custom template
1480 var tmpl = element.html();
1481 if (tmpl && !tmpl.match(/^\s*$/))
1482 scope.template = tmpl
1484 egGridCtrl.columnsProvider.add(scope);
1491 * eg-grid-action : used for specifying actions which may be applied
1492 * to items within the grid.
1494 .directive('egGridAction', function() {
1496 require : '^egGrid',
1500 group : '@', // Action group, ungrouped if not set
1501 label : '@', // Action label
1502 handler : '=', // Action function handler
1504 disabled : '=', // function
1507 link : function(scope, element, attrs, egGridCtrl) {
1508 egGridCtrl.addAction({
1510 group : scope.group,
1511 label : scope.label,
1512 divider : scope.divider,
1513 handler : scope.handler,
1514 disabled : scope.disabled,
1521 .factory('egGridColumnsProvider', ['egCore', function(egCore) {
1523 function ColumnsProvider(args) {
1526 cols.stockVisible = [];
1527 cols.idlClass = args.idlClass;
1528 cols.clientSort = args.clientSort;
1529 cols.defaultToHidden = args.defaultToHidden;
1530 cols.defaultToNoSort = args.defaultToNoSort;
1531 cols.defaultToNoMultiSort = args.defaultToNoMultiSort;
1532 cols.defaultDateFormat = args.defaultDateFormat;
1533 cols.defaultDateContext = args.defaultDateContext;
1535 // resets column width, visibility, and sort behavior
1536 // Visibility resets to the visibility settings defined in the
1537 // template (i.e. the original egGridField values).
1538 cols.reset = function() {
1539 angular.forEach(cols.columns, function(col) {
1543 if (cols.stockVisible.indexOf(col.name) > -1) {
1546 col.visible = false;
1551 // returns true if any columns are sortable
1552 cols.hasSortableColumn = function() {
1553 return cols.columns.filter(
1555 return col.sortable || col.multisortable;
1560 cols.showAllColumns = function() {
1561 angular.forEach(cols.columns, function(column) {
1562 column.visible = true;
1566 cols.hideAllColumns = function() {
1567 angular.forEach(cols.columns, function(col) {
1572 cols.indexOf = function(name) {
1573 for (var i = 0; i < cols.columns.length; i++) {
1574 if (cols.columns[i].name == name)
1580 cols.findColumn = function(name) {
1581 return cols.columns[cols.indexOf(name)];
1584 cols.compileAutoColumns = function() {
1585 var idl_class = egCore.idl.classes[cols.idlClass];
1590 if (field.virtual) return;
1591 // Columns declared in the markup take precedence
1592 // of matching auto-columns.
1593 if (cols.findColumn(field.name)) return;
1594 if (field.datatype == 'link' || field.datatype == 'org_unit') {
1595 // if the field is a link and the linked class has a
1596 // "selector" field specified, use the selector field
1597 // as the display field for the columns.
1598 // flattener will take care of the fleshing.
1599 if (field['class']) {
1600 var selector_field = egCore.idl.classes[field['class']].fields
1601 .filter(function(f) { return Boolean(f.selector) })[0];
1602 if (selector_field) {
1603 field.path = field.name + '.' + selector_field.selector;
1607 cols.add(field, true);
1612 // if a column definition has a path with a wildcard, create
1613 // columns for all non-virtual fields at the specified
1614 // position in the path.
1615 cols.expandPath = function(colSpec) {
1617 var ignoreList = [];
1619 ignoreList = colSpec.ignore.split(' ');
1621 var dotpath = colSpec.path.replace(/\.?\*$/,'');
1625 if (colSpec.parentIdlClass) {
1626 class_obj = egCore.idl.classes[colSpec.parentIdlClass];
1628 class_obj = egCore.idl.classes[cols.idlClass];
1630 var idl_parent = class_obj;
1631 var old_field_label = '';
1633 if (!class_obj) return;
1635 //console.debug('egGrid: auto dotpath is: ' + dotpath);
1636 var path_parts = dotpath.split(/\./);
1638 // find the IDL class definition for the last element in the
1639 // path before the .*
1640 // an empty path_parts means expand the root class
1643 for (var path_idx in path_parts) {
1644 old_field = idl_field;
1646 var part = path_parts[path_idx];
1647 idl_field = class_obj.field_map[part];
1649 // unless we're at the end of the list, this field should
1650 // link to another class.
1651 if (idl_field && idl_field['class'] && (
1652 idl_field.datatype == 'link' ||
1653 idl_field.datatype == 'org_unit')) {
1654 if (old_field_label) old_field_label += ' : ';
1655 old_field_label += idl_field.label;
1656 class_obj = egCore.idl.classes[idl_field['class']];
1657 if (old_field) idl_parent = old_field;
1659 if (path_idx < (path_parts.length - 1)) {
1660 // we ran out of classes to hop through before
1661 // we ran out of path components
1662 console.error("egGrid: invalid IDL path: " + dotpath);
1669 angular.forEach(class_obj.fields, function(field) {
1671 // Only show wildcard fields where we have data to show
1672 // Virtual and un-fleshed links will not have any data.
1673 if (field.virtual ||
1674 (field.datatype == 'link' || field.datatype == 'org_unit') ||
1675 ignoreList.indexOf(field.name) > -1
1679 var col = cols.cloneFromScope(colSpec);
1680 col.path = (dotpath ? dotpath + '.' + field.name : field.name);
1682 // log line below is very chatty. disable until needed.
1683 // console.debug('egGrid: field: ' +field.name + '; parent field: ' + js2JSON(idl_parent));
1684 cols.add(col, false, true,
1685 {idl_parent : idl_parent, idl_field : field, idl_class : class_obj, field_parent_label : old_field_label });
1688 cols.columns = cols.columns.sort(
1690 if (a.explicit) return -1;
1691 if (b.explicit) return 1;
1693 if (a.idlclass && b.idlclass) {
1694 if (a.idlclass < b.idlclass) return -1;
1695 if (b.idlclass < a.idlclass) return 1;
1698 if (a.path && b.path && a.path.lastIndexOf('.') && b.path.lastIndexOf('.')) {
1699 if (a.path.substring(0, a.path.lastIndexOf('.')) < b.path.substring(0, b.path.lastIndexOf('.'))) return -1;
1700 if (b.path.substring(0, b.path.lastIndexOf('.')) < a.path.substring(0, a.path.lastIndexOf('.'))) return 1;
1703 if (a.label && b.label) {
1704 if (a.label < b.label) return -1;
1705 if (b.label < a.label) return 1;
1708 return a.name < b.name ? -1 : 1;
1715 "egGrid: wildcard path does not resolve to an object: "
1720 // angular.clone(scopeObject) is not permittable. Manually copy
1721 // the fields over that we need (so the scope object can go away).
1722 cols.cloneFromScope = function(colSpec) {
1724 flesher : colSpec.flesher,
1725 comparator : colSpec.comparator,
1726 name : colSpec.name,
1727 label : colSpec.label,
1728 path : colSpec.path,
1729 align : colSpec.align || 'left',
1730 flex : Number(colSpec.flex) || 2,
1731 sort : Number(colSpec.sort) || 0,
1732 required : colSpec.required,
1733 linkpath : colSpec.linkpath,
1734 template : colSpec.template,
1735 visible : colSpec.visible,
1736 compiled : colSpec.compiled,
1737 handlers : colSpec.handlers,
1738 hidden : colSpec.hidden,
1739 datatype : colSpec.datatype,
1740 sortable : colSpec.sortable,
1741 nonsortable : colSpec.nonsortable,
1742 multisortable : colSpec.multisortable,
1743 nonmultisortable : colSpec.nonmultisortable,
1744 dateformat : colSpec.dateformat,
1745 datecontext : colSpec.datecontext,
1746 datefilter : colSpec.datefilter,
1747 dateonlyinterval : colSpec.dateonlyinterval,
1748 parentIdlClass : colSpec.parentIdlClass,
1749 cssSelector : colSpec.cssSelector
1754 // Add a column to the columns collection.
1755 // Columns may come from a slim eg-columns-field or
1756 // directly from the IDL.
1757 cols.add = function(colSpec, fromIDL, fromExpand, idl_info) {
1759 // First added column with the specified path takes precedence.
1760 // This allows for specific definitions followed by wildcard
1761 // definitions. If a match is found, back out.
1762 if (cols.columns.filter(function(c) {
1763 return (c.path == colSpec.path) })[0]) {
1764 console.debug('skipping pre-existing column ' + colSpec.path);
1768 var column = fromExpand ? colSpec : cols.cloneFromScope(colSpec);
1770 if (column.path && column.path.match(/\*$/))
1771 return cols.expandPath(colSpec);
1773 if (!fromExpand) column.explicit = true;
1775 if (!column.name) column.name = column.path;
1776 if (!column.path) column.path = column.name;
1778 if (column.visible || (!cols.defaultToHidden && !column.hidden))
1779 column.visible = true;
1781 if (column.sortable || (!cols.defaultToNoSort && !column.nonsortable))
1782 column.sortable = true;
1784 if (column.multisortable ||
1785 (!cols.defaultToNoMultiSort && !column.nonmultisortable))
1786 column.multisortable = true;
1788 if (cols.defaultDateFormat && ! column.dateformat) {
1789 column.dateformat = cols.defaultDateFormat;
1792 if (cols.defaultDateOnlyInterval && ! column.dateonlyinterval) {
1793 column.dateonlyinterval = cols.defaultDateOnlyInterval;
1796 if (cols.defaultDateContext && ! column.datecontext) {
1797 column.datecontext = cols.defaultDateContext;
1800 if (cols.defaultDateFilter && ! column.datefilter) {
1801 column.datefilter = cols.defaultDateFilter;
1804 cols.columns.push(column);
1806 // Track which columns are visible by default in case we
1807 // need to reset column visibility
1809 cols.stockVisible.push(column.name);
1811 if (fromIDL) return; // directly from egIDL. nothing left to do.
1813 // lookup the matching IDL field
1814 if (!idl_info && cols.idlClass)
1815 idl_info = cols.idlFieldFromPath(column.path);
1818 // column is not represented within the IDL
1819 column.adhoc = true;
1823 column.datatype = idl_info.idl_field.datatype;
1825 if (!column.label) {
1826 column.label = idl_info.idl_field.label || column.name;
1829 if (fromExpand && idl_info.idl_class) {
1830 column.idlclass = '';
1831 if (idl_info.field_parent_label && idl_info.idl_parent.label != idl_info.idl_class.label) {
1832 column.idlclass = (idl_info.field_parent_label || idl_info.idl_parent.label || idl_info.idl_parent.name);
1834 column.idlclass += idl_info.idl_class.label || idl_info.idl_class.name;
1839 // finds the IDL field from the dotpath, using the columns
1840 // idlClass as the base.
1841 cols.idlFieldFromPath = function(dotpath) {
1842 var class_obj = egCore.idl.classes[cols.idlClass];
1843 if (!dotpath) return null;
1845 var path_parts = dotpath.split(/\./);
1849 for (var path_idx in path_parts) {
1850 var part = path_parts[path_idx];
1851 idl_parent = idl_field;
1852 idl_field = class_obj.field_map[part];
1855 if (idl_field['class'] && (
1856 idl_field.datatype == 'link' ||
1857 idl_field.datatype == 'org_unit')) {
1858 class_obj = egCore.idl.classes[idl_field['class']];
1866 idl_parent: idl_parent,
1867 idl_field : idl_field,
1868 idl_class : class_obj
1874 instance : function(args) { return new ColumnsProvider(args) }
1880 * Generic data provider template class. This is basically an abstract
1881 * class factory service whose instances can be locally modified to
1882 * meet the needs of each individual grid.
1884 .factory('egGridDataProvider',
1885 ['$q','$timeout','$filter','egCore',
1886 function($q , $timeout , $filter , egCore) {
1888 function GridDataProvider(args) {
1889 var gridData = this;
1890 if (!args) args = {};
1893 gridData.get = args.get;
1894 gridData.query = args.query;
1895 gridData.idlClass = args.idlClass;
1896 gridData.columnsProvider = args.columnsProvider;
1898 // Delivers a stream of array data via promise.notify()
1899 // Useful for passing an array of data to egGrid.get()
1900 // If a count is provided, the array will be trimmed to
1901 // the range defined by count and offset
1902 gridData.arrayNotifier = function(arr, offset, count) {
1903 if (!arr || arr.length == 0) return $q.when();
1905 if (gridData.columnsProvider.clientSort
1907 && gridData.sort.length > 0
1909 var sorter_cache = [];
1910 arr.sort(function(a,b) {
1911 for (var si = 0; si < gridData.sort.length; si++) {
1912 if (!sorter_cache[si]) { // Build sort structure on first comparison, reuse thereafter
1913 var field = gridData.sort[si];
1916 if (angular.isObject(field)) {
1917 dir = Object.values(field)[0];
1918 field = Object.keys(field)[0];
1921 var path = gridData.columnsProvider.findColumn(field).path || field;
1922 var comparator = gridData.columnsProvider.findColumn(field).comparator ||
1923 function (x,y) { if (x < y) return -1; if (x > y) return 1; return 0 };
1925 sorter_cache[si] = {
1928 comparator : comparator
1932 var sc = sorter_cache[si];
1936 if (a._isfieldmapper || angular.isFunction(a[sc.field])) {
1937 try {af = a[sc.field](); bf = b[sc.field]() } catch (e) {};
1939 af = a[sc.field]; bf = b[sc.field];
1941 if (af === undefined && sc.field.indexOf('.') > -1) { // assume an object, not flat path
1942 var parts = sc.field.split('.');
1945 angular.forEach(parts, function (p) {
1947 if (af._isfieldmapper || angular.isFunction(af[p])) af = af[p]();
1951 if (bf._isfieldmapper || angular.isFunction(bf[p])) bf = bf[p]();
1957 if (af === undefined) af = null;
1958 if (bf === undefined) bf = null;
1960 if (af === null && bf !== null) return 1;
1961 if (bf === null && af !== null) return -1;
1963 if (!(bf === null && af === null)) {
1964 var partial = sc.comparator(af,bf);
1966 if (sc.dir == 'desc') {
1967 if (partial > 0) return -1;
1979 if (count) arr = arr.slice(offset, offset + count);
1980 var def = $q.defer();
1981 // promise notifications are only witnessed when delivered
1982 // after the caller has his hands on the promise object
1983 $timeout(function() {
1984 angular.forEach(arr, def.notify);
1990 // Calls the grid refresh function. Once instantiated, the
1991 // grid will replace this function with it's own refresh()
1992 gridData.refresh = function(noReset) { }
1993 gridData.prepend = function(limit) { }
1995 if (!gridData.get) {
1996 // returns a promise whose notify() delivers items
1997 gridData.get = function(index, count) {
1998 console.error("egGridDataProvider.get() not implemented");
2002 // attempts a flat field lookup first. If the column is not
2003 // found on the top-level object, attempts a nested lookup
2004 // TODO: consider a caching layer to speed up template
2005 // rendering, particularly for nested objects?
2006 gridData.itemFieldValue = function(item, column) {
2008 if (column.name in item) {
2009 if (typeof item[column.name] == 'function') {
2010 val = item[column.name]();
2012 val = item[column.name];
2015 val = gridData.nestedItemFieldValue(item, column);
2021 // TODO: deprecate me
2022 gridData.flatItemFieldValue = function(item, column) {
2023 console.warn('gridData.flatItemFieldValue deprecated; '
2024 + 'leave provider.itemFieldValue unset');
2025 return item[column.name];
2028 // given an object and a dot-separated path to a field,
2029 // extract the value of the field. The path can refer
2030 // to function names or object attributes. If the final
2031 // value is an IDL field, run the value through its
2032 // corresponding output filter.
2033 gridData.nestedItemFieldValue = function(obj, column) {
2034 item = obj; // keep a copy around
2036 if (obj === null || obj === undefined || obj === '') return '';
2037 if (!column.path) return obj;
2040 var parts = column.path.split('.');
2042 angular.forEach(parts, function(step, idx) {
2043 // object is not fleshed to the expected extent
2044 if (typeof obj != 'object') {
2045 if (typeof obj != 'undefined' && column.flesher) {
2046 obj = column.flesher(obj, column, item);
2053 if (!obj) return '';
2055 var cls = obj.classname;
2056 if (cls && (class_obj = egCore.idl.classes[cls])) {
2057 idl_field = class_obj.field_map[step];
2058 obj = obj[step] ? obj[step]() : '';
2060 if (angular.isFunction(obj[step])) {
2068 // We found a nested IDL object which may or may not have
2069 // been configured as a top-level column. Grab the datatype.
2070 if (idl_field && !column.datatype)
2071 column.datatype = idl_field.datatype;
2073 if (obj === null || obj === undefined || obj === '') return '';
2079 instance : function(args) {
2080 return new GridDataProvider(args);
2087 // Factory service for egGridDataManager instances, which are
2088 // responsible for collecting flattened grid data.
2089 .factory('egGridFlatDataProvider',
2090 ['$q','egCore','egGridDataProvider',
2091 function($q , egCore , egGridDataProvider) {
2094 instance : function(args) {
2095 var provider = egGridDataProvider.instance(args);
2097 provider.get = function(offset, count) {
2099 // no query means no call
2100 if (!provider.query ||
2101 angular.equals(provider.query, {}))
2104 // find all of the currently visible columns
2105 var queryFields = {}
2106 angular.forEach(provider.columnsProvider.columns,
2108 // only query IDL-tracked columns
2109 if (!col.adhoc && col.name && col.path && (col.required || col.visible))
2110 queryFields[col.name] = col.path;
2114 return egCore.net.request(
2116 'open-ils.fielder.flattened_search',
2117 egCore.auth.token(), provider.idlClass,
2118 queryFields, provider.query,
2119 { sort : provider.sort,
2125 //provider.itemFieldValue = provider.flatItemFieldValue;
2132 .directive('egGridColumnDragSource', function() {
2135 require : '^egGrid',
2136 link : function(scope, element, attrs, egGridCtrl) {
2137 angular.element(element).attr('draggable', 'true');
2139 element.bind('dragstart', function(e) {
2140 egGridCtrl.dragColumn = attrs.column;
2141 egGridCtrl.dragType = attrs.dragType || 'move'; // or resize
2142 egGridCtrl.colResizeDir = 0;
2144 if (egGridCtrl.dragType == 'move') {
2145 // style the column getting moved
2146 angular.element(e.target).addClass(
2147 'eg-grid-column-move-handle-active');
2151 element.bind('dragend', function(e) {
2152 if (egGridCtrl.dragType == 'move') {
2153 angular.element(e.target).removeClass(
2154 'eg-grid-column-move-handle-active');
2161 .directive('egGridColumnDragDest', function() {
2164 require : '^egGrid',
2165 link : function(scope, element, attrs, egGridCtrl) {
2167 element.bind('dragover', function(e) { // required for drop
2168 e.stopPropagation();
2170 e.dataTransfer.dropEffect = 'move';
2172 if (egGridCtrl.colResizeDir == 0) return; // move
2174 var cols = egGridCtrl.columnsProvider;
2175 var srcCol = egGridCtrl.dragColumn;
2176 var srcColIdx = cols.indexOf(srcCol);
2178 if (egGridCtrl.colResizeDir == -1) {
2179 if (cols.indexOf(attrs.column) <= srcColIdx) {
2180 egGridCtrl.modifyColumnFlex(
2181 egGridCtrl.columnsProvider.findColumn(
2182 egGridCtrl.dragColumn), -1);
2183 if (cols.columns[srcColIdx+1]) {
2184 // source column shrinks by one, column to the
2185 // right grows by one.
2186 egGridCtrl.modifyColumnFlex(
2187 cols.columns[srcColIdx+1], 1);
2192 if (cols.indexOf(attrs.column) > srcColIdx) {
2193 egGridCtrl.modifyColumnFlex(
2194 egGridCtrl.columnsProvider.findColumn(
2195 egGridCtrl.dragColumn), 1);
2196 if (cols.columns[srcColIdx+1]) {
2197 // source column grows by one, column to the
2198 // right grows by one.
2199 egGridCtrl.modifyColumnFlex(
2200 cols.columns[srcColIdx+1], -1);
2208 element.bind('dragenter', function(e) {
2209 e.stopPropagation();
2211 if (egGridCtrl.dragType == 'move') {
2212 angular.element(e.target).addClass('eg-grid-col-hover');
2214 // resize grips are on the right side of each column.
2215 // dragenter will either occur on the source column
2216 // (dragging left) or the column to the right.
2217 if (egGridCtrl.colResizeDir == 0) {
2218 if (egGridCtrl.dragColumn == attrs.column) {
2219 egGridCtrl.colResizeDir = -1; // west
2221 egGridCtrl.colResizeDir = 1; // east
2227 element.bind('dragleave', function(e) {
2228 e.stopPropagation();
2230 if (egGridCtrl.dragType == 'move') {
2231 angular.element(e.target).removeClass('eg-grid-col-hover');
2235 element.bind('drop', function(e) {
2236 e.stopPropagation();
2238 egGridCtrl.colResizeDir = 0;
2239 if (egGridCtrl.dragType == 'move') {
2240 angular.element(e.target).removeClass('eg-grid-col-hover');
2241 egGridCtrl.onColumnDrop(attrs.column); // move the column
2248 .directive('egGridMenuItem', function() {
2251 require : '^egGrid',
2257 handler : '=', // onclick handler function
2258 divider : '=', // if true, show a divider only
2259 handlerData : '=', // if set, passed as second argument to handler
2260 disabled : '=', // function
2261 hidden : '=' // function
2263 link : function(scope, element, attrs, egGridCtrl) {
2264 egGridCtrl.addMenuItem({
2265 checkbox : scope.checkbox,
2266 checked : scope.checked ? true : false,
2267 label : scope.label,
2268 standalone : scope.standalone ? true : false,
2269 handler : scope.handler,
2270 divider : scope.divider,
2271 disabled : scope.disabled,
2272 hidden : scope.hidden,
2273 handlerData : scope.handlerData
2280 /* https://stackoverflow.com/questions/17343696/adding-an-ng-click-event-inside-a-filter/17344875#17344875 */
2281 .directive('compile', ['$compile', function ($compile) {
2282 return function(scope, element, attrs) {
2283 // pass through column defs from grid cell's scope
2284 scope.col = scope.$parent.col;
2287 // watch the 'compile' expression for changes
2288 return scope.$eval(attrs.compile);
2291 // when the 'compile' expression changes
2292 // assign it into the current DOM
2293 element.html(value);
2295 // compile the new DOM and link it to the current
2297 // NOTE: we only compile .childNodes so that
2298 // we don't get into infinite loop compiling ourselves
2299 $compile(element.contents())(scope);
2308 * Translates bare IDL object values into display values.
2309 * 1. Passes dates through the angular date filter
2310 * 2. Converts bools to translated Yes/No strings
2311 * Others likely to follow...
2313 .filter('egGridValueFilter', ['$filter','egCore', 'egStrings', function($filter,egCore,egStrings) {
2314 function traversePath(obj,path) {
2315 var list = path.split('.');
2316 for (var part in path) {
2317 if (obj[path]) obj = obj[path]
2323 var GVF = function(value, column, item) {
2324 switch(column.datatype) {
2327 // Browser will translate true/false for us
2329 case '1' : // legacy
2331 return egStrings.YES;
2333 case '0' : // legacy
2335 return egStrings.NO;
2336 // value may be null, '', etc.
2337 default : return '';
2340 var interval = angular.isFunction(item[column.dateonlyinterval])
2341 ? item[column.dateonlyinterval]()
2342 : item[column.dateonlyinterval];
2344 if (column.dateonlyinterval && !interval) // try it as a dotted path
2345 interval = traversePath(item, column.dateonlyinterval);
2347 var context = angular.isFunction(item[column.datecontext])
2348 ? item[column.datecontext]()
2349 : item[column.datecontext];
2351 if (column.datecontext && !context) // try it as a dotted path
2352 context = traversePath(item, column.datecontext);
2354 var date_filter = column.datefilter || 'egOrgDateInContext';
2356 return $filter(date_filter)(value, column.dateformat, context, interval);
2358 return $filter('currency')(value);
2364 GVF.$stateful = true;