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.setLimit = function(limit,forget) {
344 if (!forget && grid.persistKey) {
348 controls.getLimit = function() {
351 controls.setOffset = function(offset) {
352 grid.offset = offset;
354 controls.getOffset = function() {
358 controls.saveConfig = function () {
359 return $scope.saveConfig();
362 grid.dataProvider.refresh = controls.refresh;
363 grid.controls = controls;
366 // If a menu item provides its own HTML template, translate it,
367 // using the menu item for the template scope.
368 // note: $sce is required to avoid security restrictions and
369 // is OK here, since the template comes directly from a
370 // local HTML template (not user input).
371 $scope.translateMenuItemTemplate = function(item) {
372 var html = egCore.strings.$replace(item.template, {item : item});
373 return $sce.trustAsHtml(html);
376 // add a new (global) grid menu item
377 grid.addMenuItem = function(item) {
378 $scope.menuItems.push(item);
379 var handler = item.handler;
380 item.handler = function() {
381 $scope.gridMenuIsOpen = false; // close menu
384 item.handlerData, grid.getSelectedItems());
389 // add a selected-items action
390 grid.addAction = function(act) {
392 $scope.actionGroups.forEach(function(g){
393 if (g.label === act.group) {
399 $scope.actionGroups.push({
406 // remove the stored column configuration preferenc, then recover
407 // the column visibility information from the initial page load.
408 $scope.resetColumns = function() {
409 $scope.gridColumnPickerIsOpen = false;
410 egCore.hatch.removeItem('eg.grid.' + grid.persistKey)
412 grid.columnsProvider.reset();
413 if (grid.selfManagedData) grid.collect();
417 $scope.showAllColumns = function() {
418 $scope.gridColumnPickerIsOpen = false;
419 grid.columnsProvider.showAllColumns();
420 if (grid.selfManagedData) grid.collect();
423 $scope.hideAllColumns = function() {
424 $scope.gridColumnPickerIsOpen = false;
425 grid.columnsProvider.hideAllColumns();
426 // note: no need to fetch new data if no columns are visible
429 $scope.toggleColumnVisibility = function(col) {
430 $scope.gridColumnPickerIsOpen = false;
431 col.visible = !col.visible;
433 // egGridFlatDataProvider only retrieves data to be
434 // displayed. When column visibility changes, it's
435 // necessary to fetch the newly visible column data.
436 if (grid.selfManagedData) grid.collect();
439 // save the columns configuration (position, sort, width) to
440 // eg.grid.<persist-key>
441 $scope.saveConfig = function() {
442 $scope.gridColumnPickerIsOpen = false;
444 if (!grid.persistKey) {
446 "Cannot save settings without a grid persist-key");
450 // only store information about visible columns.
451 var cols = grid.columnsProvider.columns.filter(
452 function(col) {return Boolean(col.visible) });
454 // now scrunch the data down to just the needed info
455 cols = cols.map(function(col) {
456 var c = {name : col.name}
457 // Apart from the name, only store non-default values.
458 // No need to store col.visible, since that's implicit
459 if (col.align != 'left') c.align = col.align;
460 if (col.flex != 2) c.flex = col.flex;
461 if (Number(col.sort)) c.sort = Number(c.sort);
471 egCore.hatch.setItem('eg.grid.' + grid.persistKey, conf)
473 // Save operation performed from the grid configuration UI.
474 // Hide the configuration UI and re-draw w/ sort applied
475 if ($scope.showGridConf)
476 $scope.toggleConfDisplay();
478 // Once a version-2 grid config is saved (with limit
479 // included) we can remove the local limit pref.
480 egCore.hatch.removeLocalItem(
481 'eg.grid.' + grid.persistKey + '.limit');
486 // load the columns configuration (position, sort, width) from
487 // eg.grid.<persist-key> and apply the loaded settings to the
488 // columns on our columnsProvider
489 grid.loadConfig = function() {
490 if (!grid.persistKey) return $q.when();
492 return egCore.hatch.getItem('eg.grid.' + grid.persistKey)
493 .then(function(conf) {
496 var columns = grid.columnsProvider.columns;
499 if (Array.isArray(conf)) {
501 'upgrading version 1 grid config to version 2');
509 grid.limit = Number(conf.limit);
512 angular.forEach(conf.columns, function(col) {
513 var grid_col = columns.filter(
514 function(c) {return c.name == col.name})[0];
517 // saved column does not match a column in the
518 // current grid. skip it.
522 grid_col.align = col.align || 'left';
523 grid_col.flex = col.flex || 2;
524 grid_col.sort = col.sort || 0;
525 // all saved columns are assumed to be true
526 grid_col.visible = true;
528 .filter(function (c) {
529 return c.name == grid_col.name;
532 new_cols.push(grid_col);
535 // columns which are not expressed within the saved
536 // configuration are marked as non-visible and
537 // appended to the end of the new list of columns.
538 angular.forEach(columns, function(col) {
539 var found = conf.columns.filter(
540 function(c) {return (c.name == col.name)})[0];
547 grid.columnsProvider.columns = new_cols;
553 $scope.onContextMenu = function($event) {
554 var col = angular.element($event.target).attr('column');
555 console.log('selected column ' + col);
558 $scope.page = function() {
559 return (grid.offset / grid.limit) + 1;
562 $scope.goToPage = function(page) {
564 if (angular.isNumber(page) && page > 0) {
565 grid.offset = (page - 1) * grid.limit;
570 $scope.offset = function(o) {
571 if (angular.isNumber(o))
576 $scope.limit = function(l) {
577 if (angular.isNumber(l)) {
579 if (grid.persistKey) {
586 $scope.onFirstPage = function() {
587 return grid.offset == 0;
590 $scope.hasNextPage = function() {
591 // we have less data than requested, there must
592 // not be any more pages
593 if (grid.count() < grid.limit) return false;
595 // if the total count is not known, assume that a full
596 // page of data implies more pages are available.
597 if (grid.totalCount == -1) return true;
599 // we have a full page of data, but is there more?
600 return grid.totalCount > (grid.offset + grid.count());
603 $scope.incrementPage = function() {
604 grid.offset += grid.limit;
608 $scope.decrementPage = function() {
609 if (grid.offset < grid.limit) {
612 grid.offset -= grid.limit;
617 // number of items loaded for the current page of results
618 grid.count = function() {
619 return $scope.items.length;
622 // returns the unique identifier value for the provided item
623 // for internal consistency, indexValue is always coerced
625 grid.indexValue = function(item) {
626 if (angular.isObject(item)) {
628 if (angular.isFunction(item[grid.indexField]))
629 return ''+item[grid.indexField]();
630 return ''+item[grid.indexField]; // flat data
633 // passed a non-object; assume it's an index
637 // fires the hide handler function for a context action
638 $scope.actionHide = function(action) {
639 if (typeof action.hide == 'undefined') {
642 if (angular.isFunction(action.hide))
643 return action.hide(action);
647 // fires the disable handler function for a context action
648 $scope.actionDisable = function(action) {
649 if (typeof action.disabled == 'undefined') {
652 if (angular.isFunction(action.disabled))
653 return action.disabled(action);
654 return action.disabled;
657 // fires the action handler function for a context action
658 $scope.actionLauncher = function(action) {
659 if (!action.handler) {
661 'No handler specified for "' + action.label + '"');
665 action.handler(grid.getSelectedItems());
667 console.error('Error executing handler for "'
668 + action.label + '" => ' + E + "\n" + E.stack);
671 if ($scope.action_context_showing) $scope.hideActionContextMenu();
676 $scope.hideActionContextMenu = function () {
677 $($scope.menu_dom).css({
679 width: $scope.action_context_width,
680 top: $scope.action_context_y,
681 left: $scope.action_context_x
683 $($scope.action_context_parent).append($scope.menu_dom);
684 $scope.action_context_oldy = $scope.action_context_oldx = 0;
685 $('body').unbind('click.remove_context_menu_'+$scope.action_context_index);
686 $scope.action_context_showing = false;
689 $scope.action_context_showing = false;
690 $scope.showActionContextMenu = function ($event) {
692 // Have to gather these here, instead of inside link()
693 if (!$scope.menu_dom) $scope.menu_dom = $($scope.grid_element).find('.grid-action-dropdown')[0];
694 if (!$scope.action_context_parent) $scope.action_context_parent = $($scope.menu_dom).parent();
696 // we need the the row that got right-clicked...
697 var e = $event.target; // the DOM element
698 var s = undefined; // the angular scope for that element
699 while(e){ // searching for the row
700 // abort & use the browser default context menu for links (lp1669856):
701 if(e.tagName.toLowerCase() === 'a' && e.href){ return true; }
702 s = angular.element(e).scope();
703 if(s.hasOwnProperty('item')){ break; }
706 // select the right-clicked row if it is not already selected (lp1776557):
707 if(!$scope.selected[grid.indexValue(s.item)]){ $event.target.click(); }
709 if (!$scope.action_context_showing) {
710 $scope.action_context_width = $($scope.menu_dom).css('width');
711 $scope.action_context_y = $($scope.menu_dom).css('top');
712 $scope.action_context_x = $($scope.menu_dom).css('left');
713 $scope.action_context_showing = true;
714 $scope.action_context_index = Math.floor((Math.random() * 1000) + 1);
716 $('body').append($($scope.menu_dom));
717 $('body').bind('click.remove_context_menu_'+$scope.action_context_index, $scope.hideActionContextMenu);
720 $($scope.menu_dom).css({
722 width: $scope.action_context_width,
730 // returns the list of selected item objects
731 grid.getSelectedItems = function() {
732 return $scope.items.filter(
734 return Boolean($scope.selected[grid.indexValue(item)]);
739 grid.getItemByIndex = function(index) {
740 for (var i = 0; i < $scope.items.length; i++) {
741 var item = $scope.items[i];
742 if (grid.indexValue(item) == index)
747 // selects one row after deselecting all of the others
748 grid.selectOneItem = function(index) {
749 $scope.selected = {};
750 $scope.selected[index] = true;
753 // selects items by a column value, first clearing selected list.
754 // we overwrite the object so that we can watch $scope.selected
755 grid.selectItemsByValue = function(column, value) {
756 $scope.selected = {};
757 angular.forEach($scope.items, function(item) {
759 if (angular.isFunction(item[column]))
760 col_value = item[column]();
762 col_value = item[column];
764 if (value == col_value) $scope.selected[grid.indexValue(item)] = true
768 // selects or deselects an item, without affecting the others.
769 // returns true if the item is selected; false if de-selected.
770 // we overwrite the object so that we can watch $scope.selected
771 grid.toggleSelectOneItem = function(index) {
772 if ($scope.selected[index]) {
773 delete $scope.selected[index];
774 $scope.selected = angular.copy($scope.selected);
777 $scope.selected[index] = true;
778 $scope.selected = angular.copy($scope.selected);
783 $scope.updateSelected = function () {
784 return $scope.selected = angular.copy($scope.selected);
787 grid.selectAllItems = function() {
788 angular.forEach($scope.items, function(item) {
789 $scope.selected[grid.indexValue(item)] = true
791 $scope.selected = angular.copy($scope.selected);
794 $scope.$watch('selectAll', function(newVal) {
796 grid.selectAllItems();
798 $scope.selected = {};
802 if ($scope.onSelect) {
803 $scope.$watch('selected', function(newVal) {
804 $scope.onSelect(grid.getSelectedItems());
805 if ($scope.afterSelect) $scope.afterSelect();
809 // returns true if item1 appears in the list before item2;
810 // false otherwise. this is slightly more efficient that
811 // finding the position of each then comparing them.
812 // item1 / item2 may be an item or an item index
813 grid.itemComesBefore = function(itemOrIndex1, itemOrIndex2) {
814 var idx1 = grid.indexValue(itemOrIndex1);
815 var idx2 = grid.indexValue(itemOrIndex2);
817 // use for() for early exit
818 for (var i = 0; i < $scope.items.length; i++) {
819 var idx = grid.indexValue($scope.items[i]);
820 if (idx == idx1) return true;
821 if (idx == idx2) return false;
826 // 0-based position of item in the current data set
827 grid.indexOf = function(item) {
828 var idx = grid.indexValue(item);
829 for (var i = 0; i < $scope.items.length; i++) {
830 if (grid.indexValue($scope.items[i]) == idx)
836 grid.modifyColumnFlex = function(column, val) {
838 // prevent flex:0; use hiding instead
842 $scope.modifyColumnFlex = function(col, val) {
843 $scope.lastModColumn = col;
844 grid.modifyColumnFlex(col, val);
847 $scope.isLastModifiedColumn = function(col) {
848 if ($scope.lastModColumn)
849 return $scope.lastModColumn === col;
853 grid.modifyColumnPos = function(col, diff) {
854 var srcIdx, targetIdx;
855 angular.forEach(grid.columnsProvider.columns,
856 function(c, i) { if (c.name == col.name) srcIdx = i });
858 targetIdx = srcIdx + diff;
861 } else if (targetIdx >= grid.columnsProvider.columns.length) {
862 // Target index follows the last visible column.
864 angular.forEach(grid.columnsProvider.columns,
865 function(column, idx) {
866 if (column.visible) lastVisible = idx;
870 // When moving a column (down) causes one or more
871 // visible columns to shuffle forward, our column
872 // moves into the slot of the last visible column.
873 // Otherwise, put it into the slot directly following
874 // the last visible column.
876 srcIdx <= lastVisible ? lastVisible : lastVisible + 1;
879 // Splice column out of old position, insert at new position.
880 grid.columnsProvider.columns.splice(srcIdx, 1);
881 grid.columnsProvider.columns.splice(targetIdx, 0, col);
884 $scope.modifyColumnPos = function(col, diff) {
885 $scope.lastModColumn = col;
886 return grid.modifyColumnPos(col, diff);
890 // handles click, control-click, and shift-click
891 $scope.handleRowClick = function($event, item) {
892 var index = grid.indexValue(item);
894 var origSelected = Object.keys($scope.selected);
896 if (!$scope.canMultiSelect) {
897 grid.selectOneItem(index);
898 grid.lastSelectedItemIndex = index;
902 if ($event.ctrlKey || $event.metaKey /* mac command */) {
904 if (grid.toggleSelectOneItem(index))
905 grid.lastSelectedItemIndex = index;
907 } else if ($event.shiftKey) {
910 if (!grid.lastSelectedItemIndex ||
911 index == grid.lastSelectedItemIndex) {
912 grid.selectOneItem(index);
913 grid.lastSelectedItemIndex = index;
917 var selecting = false;
918 var ascending = grid.itemComesBefore(
919 grid.lastSelectedItemIndex, item);
921 grid.indexOf(grid.lastSelectedItemIndex);
923 // update to new last-selected
924 grid.lastSelectedItemIndex = index;
926 // select each row between the last selected and
927 // currently selected items
929 startPos += ascending ? 1 : -1;
930 var curItem = $scope.items[startPos];
932 var curIdx = grid.indexValue(curItem);
933 $scope.selected[curIdx] = true;
934 if (curIdx == index) break; // all done
936 $scope.selected = angular.copy($scope.selected);
940 grid.selectOneItem(index);
941 grid.lastSelectedItemIndex = index;
945 // Builds a sort expression from column sort priorities.
946 // called on page load and any time the priorities are modified.
947 grid.compileSort = function() {
948 var sortList = grid.columnsProvider.columns.filter(
949 function(col) { return Number(col.sort) != 0 }
952 if (Math.abs(a.sort) < Math.abs(b.sort))
958 if (sortList.length) {
959 grid.dataProvider.sort = sortList.map(function(col) {
961 blob[col.name] = col.sort < 0 ? 'desc' : 'asc';
967 // builds a sort expression using a single column,
968 // toggling between ascending and descending sort.
969 $scope.quickSort = function(col_name) {
970 var sort = grid.dataProvider.sort;
971 if (sort && sort.length &&
972 sort[0] == col_name) {
974 blob[col_name] = 'desc';
975 grid.dataProvider.sort = [blob];
977 grid.dataProvider.sort = [col_name];
984 // show / hide the grid configuration row
985 $scope.toggleConfDisplay = function() {
986 if ($scope.showGridConf) {
987 $scope.showGridConf = false;
988 if (grid.columnsProvider.hasSortableColumn()) {
989 // only refresh the grid if the user has the
990 // ability to modify the sort priorities.
996 $scope.showGridConf = true;
999 delete $scope.lastModColumn;
1000 $scope.gridColumnPickerIsOpen = false;
1003 // called when a dragged column is dropped onto itself
1004 // or any other column
1005 grid.onColumnDrop = function(target) {
1006 if (angular.isUndefined(target)) return;
1007 if (target == grid.dragColumn) return;
1008 var srcIdx, targetIdx, srcCol;
1009 angular.forEach(grid.columnsProvider.columns,
1010 function(col, idx) {
1011 if (col.name == grid.dragColumn) {
1014 } else if (col.name == target) {
1020 if (srcIdx < targetIdx) targetIdx--;
1022 // move src column from old location to new location in
1023 // the columns array, then force a page refresh
1024 grid.columnsProvider.columns.splice(srcIdx, 1);
1025 grid.columnsProvider.columns.splice(targetIdx, 0, srcCol);
1029 // prepares a string for inclusion within a CSV document
1030 // by escaping commas and quotes and removing newlines.
1031 grid.csvDatum = function(str) {
1033 if (!str) return '';
1034 str = str.replace(/\n/g, '');
1035 if (str.match(/\,/) || str.match(/"/)) {
1036 str = str.replace(/"/g, '""');
1037 str = '"' + str + '"';
1042 /** Export the full data set as CSV.
1044 * 1. User clicks the 'download csv' link
1045 * 2. All grid data is retrieved asychronously
1046 * 3. Once all data is all present and CSV-ized, the download
1047 * attributes are linked to the href.
1048 * 4. The href .click() action is prgrammatically fired again,
1049 * telling the browser to download the data, now that the
1050 * data is available for download.
1051 * 5 Once downloaded, the href attributes are reset.
1053 grid.csvExportInProgress = false;
1054 $scope.generateCSVExportURL = function($event) {
1056 if (grid.csvExportInProgress) {
1057 // This is secondary href click handler. Give the
1058 // browser a moment to start the download, then reset
1059 // the CSV download attributes / state.
1062 $scope.csvExportURL = '';
1063 $scope.csvExportFileName = '';
1064 grid.csvExportInProgress = false;
1070 grid.csvExportInProgress = true;
1071 $scope.gridColumnPickerIsOpen = false;
1073 // let the file name describe the grid
1074 $scope.csvExportFileName =
1075 ($scope.mainLabel || grid.persistKey || 'eg_grid_data')
1076 .replace(/\s+/g, '_') + '_' + $scope.page();
1078 // toss the CSV into a Blob and update the export URL
1079 grid.generateCSV().then(function(csv) {
1080 var blob = new Blob([csv], {type : 'text/plain'});
1081 $scope.csvExportURL =
1082 ($window.URL || $window.webkitURL).createObjectURL(blob);
1084 // Fire the 2nd click event now that the browser has
1085 // information on how to download the CSV file.
1086 $timeout(function() {$event.target.click()});
1091 * TODO: does this serve any purpose given we can
1092 * print formatted HTML? If so, generateCSV() now
1093 * returns a promise, needs light refactoring...
1094 $scope.printCSV = function() {
1095 $scope.gridColumnPickerIsOpen = false;
1096 egCore.print.print({
1097 context : 'default',
1098 content : grid.generateCSV(),
1099 content_type : 'text/plain'
1104 // Given a row item and column definition, extract the
1105 // text content for printing. Templated columns must be
1106 // processed and parsed as HTML, then boiled down to their
1108 grid.getItemTextContent = function(item, col) {
1111 val = $scope.translateCellTemplate(col, item);
1113 var node = new DOMParser()
1114 .parseFromString(val, 'text/html');
1115 val = $(node).text();
1118 val = grid.dataProvider.itemFieldValue(item, col);
1119 val = $filter('egGridValueFilter')(val, col, item);
1124 $scope.getHtmlTooltip = function(col, item) {
1125 return grid.getItemTextContent(item, col);
1129 * Fetches all grid data and transates each item into a simple
1130 * key-value pair of column name => text-value.
1131 * Included in the response for convenience is the list of
1132 * currently visible column definitions.
1133 * TODO: currently fetches a maximum of 10k rows. Does this
1134 * need to be configurable?
1136 grid.getAllItemsAsText = function() {
1137 var text_items = [];
1139 // we don't know the total number of rows we're about
1140 // to retrieve, but we can indicate the number retrieved
1141 // so far as each item arrives.
1142 egProgressDialog.open({value : 0});
1144 var visible_cols = grid.columnsProvider.columns.filter(
1145 function(c) { return c.visible });
1147 return grid.dataProvider.get(0, 10000).then(
1149 return {items : text_items, columns : visible_cols};
1153 egProgressDialog.increment();
1155 angular.forEach(visible_cols, function(col) {
1156 text_item[col.name] =
1157 grid.getItemTextContent(item, col);
1159 text_items.push(text_item);
1161 ).finally(egProgressDialog.close);
1164 // Fetch "all" of the grid data, translate it into print-friendly
1165 // text, and send it to the printer service.
1166 $scope.printHTML = function() {
1167 $scope.gridColumnPickerIsOpen = false;
1168 return grid.getAllItemsAsText().then(function(text_items) {
1169 return egCore.print.print({
1170 template : 'grid_html',
1176 $scope.showColumnDialog = function() {
1177 return $uibModal.open({
1178 templateUrl: './share/t_grid_columns',
1181 controller: ['$scope', '$uibModalInstance',
1182 function($dialogScope, $uibModalInstance) {
1183 $dialogScope.modifyColumnPos = $scope.modifyColumnPos;
1184 $dialogScope.disableMultiSort = $scope.disableMultiSort;
1185 $dialogScope.columns = $scope.columns;
1187 // Push visible columns to the top of the list
1188 $dialogScope.elevateVisible = function() {
1190 angular.forEach($dialogScope.columns, function(col) {
1191 if (col.visible) new_cols.push(col);
1193 angular.forEach($dialogScope.columns, function(col) {
1194 if (!col.visible) new_cols.push(col);
1197 // Update all references to the list of columns
1198 $dialogScope.columns =
1200 grid.columnsProvider.columns =
1204 $dialogScope.toggle = function(col) {
1205 col.visible = !Boolean(col.visible);
1207 $dialogScope.ok = $dialogScope.cancel = function() {
1208 delete $scope.lastModColumn;
1209 $uibModalInstance.close()
1216 // generates CSV for the currently visible grid contents
1217 grid.generateCSV = function() {
1218 return grid.getAllItemsAsText().then(function(text_items) {
1219 var columns = text_items.columns;
1220 var items = text_items.items;
1224 angular.forEach(columns, function(col) {
1225 csvStr += grid.csvDatum(col.label);
1229 csvStr = csvStr.replace(/,$/,'\n');
1232 angular.forEach(items, function(item) {
1233 angular.forEach(columns, function(col) {
1234 csvStr += grid.csvDatum(item[col.name]);
1237 csvStr = csvStr.replace(/,$/,'\n');
1244 // Interpolate the value for column.linkpath within the context
1245 // of the row item to generate the final link URL.
1246 $scope.generateLinkPath = function(col, item) {
1247 return egCore.strings.$replace(col.linkpath, {item : item});
1250 // If a column provides its own HTML template, translate it,
1251 // using the current item for the template scope.
1252 // note: $sce is required to avoid security restrictions and
1253 // is OK here, since the template comes directly from a
1254 // local HTML template (not user input).
1255 $scope.translateCellTemplate = function(col, item) {
1256 var html = egCore.strings.$replace(col.template, {item : item});
1257 return $sce.trustAsHtml(html);
1260 $scope.collect = function() { grid.collect() }
1263 $scope.confirmAllowAllAndCollect = function(){
1264 egConfirmDialog.open(egStrings.CONFIRM_LONG_RUNNING_ACTION_ALL_ROWS_TITLE,
1265 egStrings.CONFIRM_LONG_RUNNING_ACTION_MSG)
1269 $scope.limit(10000);
1274 // asks the dataProvider for a page of data
1275 grid.collect = function() {
1277 // avoid firing the collect if there is nothing to collect.
1278 if (grid.selfManagedData && !grid.dataProvider.query) return;
1280 if (grid.collecting) return; // avoid parallel collect()
1281 grid.collecting = true;
1283 console.debug('egGrid.collect() offset='
1284 + grid.offset + '; limit=' + grid.limit);
1286 // ensure all of our dropdowns are closed
1287 // TODO: git rid of these and just use dropdown-toggle,
1288 // which is more reliable.
1289 $scope.gridColumnPickerIsOpen = false;
1290 $scope.gridRowCountIsOpen = false;
1291 $scope.gridPageSelectIsOpen = false;
1294 $scope.selected = {};
1296 // Inform the caller we've asked the data provider
1297 // for data. This is useful for knowing when collection
1298 // has started (e.g. to display a progress dialg) when
1299 // using the stock (flattener) data provider, where the
1300 // user is not directly defining a get() handler.
1301 if (grid.controls.collectStarted)
1302 grid.controls.collectStarted(grid.offset, grid.limit);
1304 grid.dataProvider.get(grid.offset, grid.limit).then(
1306 if (grid.controls.allItemsRetrieved)
1307 grid.controls.allItemsRetrieved();
1312 $scope.items.push(item)
1313 if (grid.controls.itemRetrieved)
1314 grid.controls.itemRetrieved(item);
1315 if ($scope.selectAll)
1316 $scope.selected[grid.indexValue(item)] = true
1318 }).finally(function() {
1319 console.debug('egGrid.collect() complete');
1320 grid.collecting = false
1321 $scope.selected = angular.copy($scope.selected);
1331 * eg-grid-field : used for collecting custom field data from the templates.
1332 * This directive does not direct display, it just passes data up to the
1335 .directive('egGridField', function() {
1337 require : '^egGrid',
1340 flesher: '=', // optional; function that can flesh a linked field, given the value
1341 comparator: '=', // optional; function that can sort the thing at the end of 'path'
1342 name : '@', // required; unique name
1343 path : '@', // optional; flesh path
1344 ignore: '@', // optional; fields to ignore when path is a wildcard
1345 label : '@', // optional; display label
1346 flex : '@', // optional; default flex width
1347 align : '@', // optional; default alignment, left/center/right
1348 dateformat : '@', // optional: passed down to egGridValueFilter
1349 datecontext: '@', // optional: passed down to egGridValueFilter to choose TZ
1350 datefilter: '@', // optional: passed down to egGridValueFilter to choose specialized date filters
1351 dateonlyinterval: '@', // optional: passed down to egGridValueFilter to choose a "better" format
1353 // if a field is part of an IDL object, but we are unable to
1354 // determine the class, because it's nested within a hash
1355 // (i.e. we can't navigate directly to the object via the IDL),
1356 // idlClass lets us specify the class. This is particularly
1357 // useful for nested wildcard fields.
1358 parentIdlClass : '@',
1360 // optional: for non-IDL columns, specifying a datatype
1361 // lets the caller control which display filter is used.
1362 // datatype should match the standard IDL datatypes.
1365 // optional hash of functions that can be imported into
1366 // the directive's scope; meant for cases where the "compiled"
1370 // optional: CSS class name that we want to have for this field.
1371 // Auto generated from path if nothing is passed in via eg-grid-field declaration
1374 link : function(scope, element, attrs, egGridCtrl) {
1376 // boolean fields are presented as value-less attributes
1386 'required' // if set, always fetch data for this column
1389 if (angular.isDefined(attrs[field]))
1390 scope[field] = true;
1394 scope.cssSelector = attrs['cssSelector'] ? attrs['cssSelector'] : "";
1396 // auto-generate CSS selector name for field if none declared in tt2 and there's a path
1397 if (scope.path && !scope.cssSelector){
1398 var cssClass = 'grid' + "." + scope.path;
1399 cssClass = cssClass.replace(/\./g,'-');
1400 element.addClass(cssClass);
1401 scope.cssSelector = cssClass;
1404 // any HTML content within the field is its custom template
1405 var tmpl = element.html();
1406 if (tmpl && !tmpl.match(/^\s*$/))
1407 scope.template = tmpl
1409 egGridCtrl.columnsProvider.add(scope);
1416 * eg-grid-action : used for specifying actions which may be applied
1417 * to items within the grid.
1419 .directive('egGridAction', function() {
1421 require : '^egGrid',
1425 group : '@', // Action group, ungrouped if not set
1426 label : '@', // Action label
1427 handler : '=', // Action function handler
1429 disabled : '=', // function
1432 link : function(scope, element, attrs, egGridCtrl) {
1433 egGridCtrl.addAction({
1435 group : scope.group,
1436 label : scope.label,
1437 divider : scope.divider,
1438 handler : scope.handler,
1439 disabled : scope.disabled,
1446 .factory('egGridColumnsProvider', ['egCore', function(egCore) {
1448 function ColumnsProvider(args) {
1451 cols.stockVisible = [];
1452 cols.idlClass = args.idlClass;
1453 cols.clientSort = args.clientSort;
1454 cols.defaultToHidden = args.defaultToHidden;
1455 cols.defaultToNoSort = args.defaultToNoSort;
1456 cols.defaultToNoMultiSort = args.defaultToNoMultiSort;
1457 cols.defaultDateFormat = args.defaultDateFormat;
1458 cols.defaultDateContext = args.defaultDateContext;
1460 // resets column width, visibility, and sort behavior
1461 // Visibility resets to the visibility settings defined in the
1462 // template (i.e. the original egGridField values).
1463 cols.reset = function() {
1464 angular.forEach(cols.columns, function(col) {
1468 if (cols.stockVisible.indexOf(col.name) > -1) {
1471 col.visible = false;
1476 // returns true if any columns are sortable
1477 cols.hasSortableColumn = function() {
1478 return cols.columns.filter(
1480 return col.sortable || col.multisortable;
1485 cols.showAllColumns = function() {
1486 angular.forEach(cols.columns, function(column) {
1487 column.visible = true;
1491 cols.hideAllColumns = function() {
1492 angular.forEach(cols.columns, function(col) {
1497 cols.indexOf = function(name) {
1498 for (var i = 0; i < cols.columns.length; i++) {
1499 if (cols.columns[i].name == name)
1505 cols.findColumn = function(name) {
1506 return cols.columns[cols.indexOf(name)];
1509 cols.compileAutoColumns = function() {
1510 var idl_class = egCore.idl.classes[cols.idlClass];
1515 if (field.virtual) return;
1516 if (field.datatype == 'link' || field.datatype == 'org_unit') {
1517 // if the field is a link and the linked class has a
1518 // "selector" field specified, use the selector field
1519 // as the display field for the columns.
1520 // flattener will take care of the fleshing.
1521 if (field['class']) {
1522 var selector_field = egCore.idl.classes[field['class']].fields
1523 .filter(function(f) { return Boolean(f.selector) })[0];
1524 if (selector_field) {
1525 field.path = field.name + '.' + selector_field.selector;
1529 cols.add(field, true);
1534 // if a column definition has a path with a wildcard, create
1535 // columns for all non-virtual fields at the specified
1536 // position in the path.
1537 cols.expandPath = function(colSpec) {
1539 var ignoreList = [];
1541 ignoreList = colSpec.ignore.split(' ');
1543 var dotpath = colSpec.path.replace(/\.?\*$/,'');
1547 if (colSpec.parentIdlClass) {
1548 class_obj = egCore.idl.classes[colSpec.parentIdlClass];
1550 class_obj = egCore.idl.classes[cols.idlClass];
1552 var idl_parent = class_obj;
1553 var old_field_label = '';
1555 if (!class_obj) return;
1557 //console.debug('egGrid: auto dotpath is: ' + dotpath);
1558 var path_parts = dotpath.split(/\./);
1560 // find the IDL class definition for the last element in the
1561 // path before the .*
1562 // an empty path_parts means expand the root class
1565 for (var path_idx in path_parts) {
1566 old_field = idl_field;
1568 var part = path_parts[path_idx];
1569 idl_field = class_obj.field_map[part];
1571 // unless we're at the end of the list, this field should
1572 // link to another class.
1573 if (idl_field && idl_field['class'] && (
1574 idl_field.datatype == 'link' ||
1575 idl_field.datatype == 'org_unit')) {
1576 if (old_field_label) old_field_label += ' : ';
1577 old_field_label += idl_field.label;
1578 class_obj = egCore.idl.classes[idl_field['class']];
1579 if (old_field) idl_parent = old_field;
1581 if (path_idx < (path_parts.length - 1)) {
1582 // we ran out of classes to hop through before
1583 // we ran out of path components
1584 console.error("egGrid: invalid IDL path: " + dotpath);
1591 angular.forEach(class_obj.fields, function(field) {
1593 // Only show wildcard fields where we have data to show
1594 // Virtual and un-fleshed links will not have any data.
1595 if (field.virtual ||
1596 (field.datatype == 'link' || field.datatype == 'org_unit') ||
1597 ignoreList.indexOf(field.name) > -1
1601 var col = cols.cloneFromScope(colSpec);
1602 col.path = (dotpath ? dotpath + '.' + field.name : field.name);
1604 // log line below is very chatty. disable until needed.
1605 // console.debug('egGrid: field: ' +field.name + '; parent field: ' + js2JSON(idl_parent));
1606 cols.add(col, false, true,
1607 {idl_parent : idl_parent, idl_field : field, idl_class : class_obj, field_parent_label : old_field_label });
1610 cols.columns = cols.columns.sort(
1612 if (a.explicit) return -1;
1613 if (b.explicit) return 1;
1615 if (a.idlclass && b.idlclass) {
1616 if (a.idlclass < b.idlclass) return -1;
1617 if (b.idlclass < a.idlclass) return 1;
1620 if (a.path && b.path && a.path.lastIndexOf('.') && b.path.lastIndexOf('.')) {
1621 if (a.path.substring(0, a.path.lastIndexOf('.')) < b.path.substring(0, b.path.lastIndexOf('.'))) return -1;
1622 if (b.path.substring(0, b.path.lastIndexOf('.')) < a.path.substring(0, a.path.lastIndexOf('.'))) return 1;
1625 if (a.label && b.label) {
1626 if (a.label < b.label) return -1;
1627 if (b.label < a.label) return 1;
1630 return a.name < b.name ? -1 : 1;
1637 "egGrid: wildcard path does not resolve to an object: "
1642 // angular.clone(scopeObject) is not permittable. Manually copy
1643 // the fields over that we need (so the scope object can go away).
1644 cols.cloneFromScope = function(colSpec) {
1646 flesher : colSpec.flesher,
1647 comparator : colSpec.comparator,
1648 name : colSpec.name,
1649 label : colSpec.label,
1650 path : colSpec.path,
1651 align : colSpec.align || 'left',
1652 flex : Number(colSpec.flex) || 2,
1653 sort : Number(colSpec.sort) || 0,
1654 required : colSpec.required,
1655 linkpath : colSpec.linkpath,
1656 template : colSpec.template,
1657 visible : colSpec.visible,
1658 compiled : colSpec.compiled,
1659 handlers : colSpec.handlers,
1660 hidden : colSpec.hidden,
1661 datatype : colSpec.datatype,
1662 sortable : colSpec.sortable,
1663 nonsortable : colSpec.nonsortable,
1664 multisortable : colSpec.multisortable,
1665 nonmultisortable : colSpec.nonmultisortable,
1666 dateformat : colSpec.dateformat,
1667 datecontext : colSpec.datecontext,
1668 datefilter : colSpec.datefilter,
1669 dateonlyinterval : colSpec.dateonlyinterval,
1670 parentIdlClass : colSpec.parentIdlClass,
1671 cssSelector : colSpec.cssSelector
1676 // Add a column to the columns collection.
1677 // Columns may come from a slim eg-columns-field or
1678 // directly from the IDL.
1679 cols.add = function(colSpec, fromIDL, fromExpand, idl_info) {
1681 // First added column with the specified path takes precedence.
1682 // This allows for specific definitions followed by wildcard
1683 // definitions. If a match is found, back out.
1684 if (cols.columns.filter(function(c) {
1685 return (c.path == colSpec.path) })[0]) {
1686 console.debug('skipping pre-existing column ' + colSpec.path);
1690 var column = fromExpand ? colSpec : cols.cloneFromScope(colSpec);
1692 if (column.path && column.path.match(/\*$/))
1693 return cols.expandPath(colSpec);
1695 if (!fromExpand) column.explicit = true;
1697 if (!column.name) column.name = column.path;
1698 if (!column.path) column.path = column.name;
1700 if (column.visible || (!cols.defaultToHidden && !column.hidden))
1701 column.visible = true;
1703 if (column.sortable || (!cols.defaultToNoSort && !column.nonsortable))
1704 column.sortable = true;
1706 if (column.multisortable ||
1707 (!cols.defaultToNoMultiSort && !column.nonmultisortable))
1708 column.multisortable = true;
1710 if (cols.defaultDateFormat && ! column.dateformat) {
1711 column.dateformat = cols.defaultDateFormat;
1714 if (cols.defaultDateOnlyInterval && ! column.dateonlyinterval) {
1715 column.dateonlyinterval = cols.defaultDateOnlyInterval;
1718 if (cols.defaultDateContext && ! column.datecontext) {
1719 column.datecontext = cols.defaultDateContext;
1722 if (cols.defaultDateFilter && ! column.datefilter) {
1723 column.datefilter = cols.defaultDateFilter;
1726 cols.columns.push(column);
1728 // Track which columns are visible by default in case we
1729 // need to reset column visibility
1731 cols.stockVisible.push(column.name);
1733 if (fromIDL) return; // directly from egIDL. nothing left to do.
1735 // lookup the matching IDL field
1736 if (!idl_info && cols.idlClass)
1737 idl_info = cols.idlFieldFromPath(column.path);
1740 // column is not represented within the IDL
1741 column.adhoc = true;
1745 column.datatype = idl_info.idl_field.datatype;
1747 if (!column.label) {
1748 column.label = idl_info.idl_field.label || column.name;
1751 if (fromExpand && idl_info.idl_class) {
1752 column.idlclass = '';
1753 if (idl_info.field_parent_label && idl_info.idl_parent.label != idl_info.idl_class.label) {
1754 column.idlclass = (idl_info.field_parent_label || idl_info.idl_parent.label || idl_info.idl_parent.name);
1756 column.idlclass += idl_info.idl_class.label || idl_info.idl_class.name;
1761 // finds the IDL field from the dotpath, using the columns
1762 // idlClass as the base.
1763 cols.idlFieldFromPath = function(dotpath) {
1764 var class_obj = egCore.idl.classes[cols.idlClass];
1765 if (!dotpath) return null;
1767 var path_parts = dotpath.split(/\./);
1771 for (var path_idx in path_parts) {
1772 var part = path_parts[path_idx];
1773 idl_parent = idl_field;
1774 idl_field = class_obj.field_map[part];
1777 if (idl_field['class'] && (
1778 idl_field.datatype == 'link' ||
1779 idl_field.datatype == 'org_unit')) {
1780 class_obj = egCore.idl.classes[idl_field['class']];
1788 idl_parent: idl_parent,
1789 idl_field : idl_field,
1790 idl_class : class_obj
1796 instance : function(args) { return new ColumnsProvider(args) }
1802 * Generic data provider template class. This is basically an abstract
1803 * class factory service whose instances can be locally modified to
1804 * meet the needs of each individual grid.
1806 .factory('egGridDataProvider',
1807 ['$q','$timeout','$filter','egCore',
1808 function($q , $timeout , $filter , egCore) {
1810 function GridDataProvider(args) {
1811 var gridData = this;
1812 if (!args) args = {};
1815 gridData.get = args.get;
1816 gridData.query = args.query;
1817 gridData.idlClass = args.idlClass;
1818 gridData.columnsProvider = args.columnsProvider;
1820 // Delivers a stream of array data via promise.notify()
1821 // Useful for passing an array of data to egGrid.get()
1822 // If a count is provided, the array will be trimmed to
1823 // the range defined by count and offset
1824 gridData.arrayNotifier = function(arr, offset, count) {
1825 if (!arr || arr.length == 0) return $q.when();
1827 if (gridData.columnsProvider.clientSort
1829 && gridData.sort.length > 0
1831 var sorter_cache = [];
1832 arr.sort(function(a,b) {
1833 for (var si = 0; si < gridData.sort.length; si++) {
1834 if (!sorter_cache[si]) { // Build sort structure on first comparison, reuse thereafter
1835 var field = gridData.sort[si];
1838 if (angular.isObject(field)) {
1839 dir = Object.values(field)[0];
1840 field = Object.keys(field)[0];
1843 var path = gridData.columnsProvider.findColumn(field).path || field;
1844 var comparator = gridData.columnsProvider.findColumn(field).comparator ||
1845 function (x,y) { if (x < y) return -1; if (x > y) return 1; return 0 };
1847 sorter_cache[si] = {
1850 comparator : comparator
1854 var sc = sorter_cache[si];
1858 if (a._isfieldmapper || angular.isFunction(a[sc.field])) {
1859 try {af = a[sc.field](); bf = b[sc.field]() } catch (e) {};
1861 af = a[sc.field]; bf = b[sc.field];
1863 if (af === undefined && sc.field.indexOf('.') > -1) { // assume an object, not flat path
1864 var parts = sc.field.split('.');
1867 angular.forEach(parts, function (p) {
1869 if (af._isfieldmapper || angular.isFunction(af[p])) af = af[p]();
1873 if (bf._isfieldmapper || angular.isFunction(bf[p])) bf = bf[p]();
1879 if (af === undefined) af = null;
1880 if (bf === undefined) bf = null;
1882 if (af === null && bf !== null) return 1;
1883 if (bf === null && af !== null) return -1;
1885 if (!(bf === null && af === null)) {
1886 var partial = sc.comparator(af,bf);
1888 if (sc.dir == 'desc') {
1889 if (partial > 0) return -1;
1901 if (count) arr = arr.slice(offset, offset + count);
1902 var def = $q.defer();
1903 // promise notifications are only witnessed when delivered
1904 // after the caller has his hands on the promise object
1905 $timeout(function() {
1906 angular.forEach(arr, def.notify);
1912 // Calls the grid refresh function. Once instantiated, the
1913 // grid will replace this function with it's own refresh()
1914 gridData.refresh = function(noReset) { }
1916 if (!gridData.get) {
1917 // returns a promise whose notify() delivers items
1918 gridData.get = function(index, count) {
1919 console.error("egGridDataProvider.get() not implemented");
1923 // attempts a flat field lookup first. If the column is not
1924 // found on the top-level object, attempts a nested lookup
1925 // TODO: consider a caching layer to speed up template
1926 // rendering, particularly for nested objects?
1927 gridData.itemFieldValue = function(item, column) {
1929 if (column.name in item) {
1930 if (typeof item[column.name] == 'function') {
1931 val = item[column.name]();
1933 val = item[column.name];
1936 val = gridData.nestedItemFieldValue(item, column);
1942 // TODO: deprecate me
1943 gridData.flatItemFieldValue = function(item, column) {
1944 console.warn('gridData.flatItemFieldValue deprecated; '
1945 + 'leave provider.itemFieldValue unset');
1946 return item[column.name];
1949 // given an object and a dot-separated path to a field,
1950 // extract the value of the field. The path can refer
1951 // to function names or object attributes. If the final
1952 // value is an IDL field, run the value through its
1953 // corresponding output filter.
1954 gridData.nestedItemFieldValue = function(obj, column) {
1955 item = obj; // keep a copy around
1957 if (obj === null || obj === undefined || obj === '') return '';
1958 if (!column.path) return obj;
1961 var parts = column.path.split('.');
1963 angular.forEach(parts, function(step, idx) {
1964 // object is not fleshed to the expected extent
1965 if (typeof obj != 'object') {
1966 if (typeof obj != 'undefined' && column.flesher) {
1967 obj = column.flesher(obj, column, item);
1974 if (!obj) return '';
1976 var cls = obj.classname;
1977 if (cls && (class_obj = egCore.idl.classes[cls])) {
1978 idl_field = class_obj.field_map[step];
1979 obj = obj[step] ? obj[step]() : '';
1981 if (angular.isFunction(obj[step])) {
1989 // We found a nested IDL object which may or may not have
1990 // been configured as a top-level column. Grab the datatype.
1991 if (idl_field && !column.datatype)
1992 column.datatype = idl_field.datatype;
1994 if (obj === null || obj === undefined || obj === '') return '';
2000 instance : function(args) {
2001 return new GridDataProvider(args);
2008 // Factory service for egGridDataManager instances, which are
2009 // responsible for collecting flattened grid data.
2010 .factory('egGridFlatDataProvider',
2011 ['$q','egCore','egGridDataProvider',
2012 function($q , egCore , egGridDataProvider) {
2015 instance : function(args) {
2016 var provider = egGridDataProvider.instance(args);
2018 provider.get = function(offset, count) {
2020 // no query means no call
2021 if (!provider.query ||
2022 angular.equals(provider.query, {}))
2025 // find all of the currently visible columns
2026 var queryFields = {}
2027 angular.forEach(provider.columnsProvider.columns,
2029 // only query IDL-tracked columns
2030 if (!col.adhoc && col.name && col.path && (col.required || col.visible))
2031 queryFields[col.name] = col.path;
2035 return egCore.net.request(
2037 'open-ils.fielder.flattened_search',
2038 egCore.auth.token(), provider.idlClass,
2039 queryFields, provider.query,
2040 { sort : provider.sort,
2046 //provider.itemFieldValue = provider.flatItemFieldValue;
2053 .directive('egGridColumnDragSource', function() {
2056 require : '^egGrid',
2057 link : function(scope, element, attrs, egGridCtrl) {
2058 angular.element(element).attr('draggable', 'true');
2060 element.bind('dragstart', function(e) {
2061 egGridCtrl.dragColumn = attrs.column;
2062 egGridCtrl.dragType = attrs.dragType || 'move'; // or resize
2063 egGridCtrl.colResizeDir = 0;
2065 if (egGridCtrl.dragType == 'move') {
2066 // style the column getting moved
2067 angular.element(e.target).addClass(
2068 'eg-grid-column-move-handle-active');
2072 element.bind('dragend', function(e) {
2073 if (egGridCtrl.dragType == 'move') {
2074 angular.element(e.target).removeClass(
2075 'eg-grid-column-move-handle-active');
2082 .directive('egGridColumnDragDest', function() {
2085 require : '^egGrid',
2086 link : function(scope, element, attrs, egGridCtrl) {
2088 element.bind('dragover', function(e) { // required for drop
2089 e.stopPropagation();
2091 e.dataTransfer.dropEffect = 'move';
2093 if (egGridCtrl.colResizeDir == 0) return; // move
2095 var cols = egGridCtrl.columnsProvider;
2096 var srcCol = egGridCtrl.dragColumn;
2097 var srcColIdx = cols.indexOf(srcCol);
2099 if (egGridCtrl.colResizeDir == -1) {
2100 if (cols.indexOf(attrs.column) <= srcColIdx) {
2101 egGridCtrl.modifyColumnFlex(
2102 egGridCtrl.columnsProvider.findColumn(
2103 egGridCtrl.dragColumn), -1);
2104 if (cols.columns[srcColIdx+1]) {
2105 // source column shrinks by one, column to the
2106 // right grows by one.
2107 egGridCtrl.modifyColumnFlex(
2108 cols.columns[srcColIdx+1], 1);
2113 if (cols.indexOf(attrs.column) > srcColIdx) {
2114 egGridCtrl.modifyColumnFlex(
2115 egGridCtrl.columnsProvider.findColumn(
2116 egGridCtrl.dragColumn), 1);
2117 if (cols.columns[srcColIdx+1]) {
2118 // source column grows by one, column to the
2119 // right grows by one.
2120 egGridCtrl.modifyColumnFlex(
2121 cols.columns[srcColIdx+1], -1);
2129 element.bind('dragenter', function(e) {
2130 e.stopPropagation();
2132 if (egGridCtrl.dragType == 'move') {
2133 angular.element(e.target).addClass('eg-grid-col-hover');
2135 // resize grips are on the right side of each column.
2136 // dragenter will either occur on the source column
2137 // (dragging left) or the column to the right.
2138 if (egGridCtrl.colResizeDir == 0) {
2139 if (egGridCtrl.dragColumn == attrs.column) {
2140 egGridCtrl.colResizeDir = -1; // west
2142 egGridCtrl.colResizeDir = 1; // east
2148 element.bind('dragleave', function(e) {
2149 e.stopPropagation();
2151 if (egGridCtrl.dragType == 'move') {
2152 angular.element(e.target).removeClass('eg-grid-col-hover');
2156 element.bind('drop', function(e) {
2157 e.stopPropagation();
2159 egGridCtrl.colResizeDir = 0;
2160 if (egGridCtrl.dragType == 'move') {
2161 angular.element(e.target).removeClass('eg-grid-col-hover');
2162 egGridCtrl.onColumnDrop(attrs.column); // move the column
2169 .directive('egGridMenuItem', function() {
2172 require : '^egGrid',
2178 handler : '=', // onclick handler function
2179 divider : '=', // if true, show a divider only
2180 handlerData : '=', // if set, passed as second argument to handler
2181 disabled : '=', // function
2182 hidden : '=' // function
2184 link : function(scope, element, attrs, egGridCtrl) {
2185 egGridCtrl.addMenuItem({
2186 checkbox : scope.checkbox,
2187 checked : scope.checked ? true : false,
2188 label : scope.label,
2189 standalone : scope.standalone ? true : false,
2190 handler : scope.handler,
2191 divider : scope.divider,
2192 disabled : scope.disabled,
2193 hidden : scope.hidden,
2194 handlerData : scope.handlerData
2201 /* https://stackoverflow.com/questions/17343696/adding-an-ng-click-event-inside-a-filter/17344875#17344875 */
2202 .directive('compile', ['$compile', function ($compile) {
2203 return function(scope, element, attrs) {
2204 // pass through column defs from grid cell's scope
2205 scope.col = scope.$parent.col;
2208 // watch the 'compile' expression for changes
2209 return scope.$eval(attrs.compile);
2212 // when the 'compile' expression changes
2213 // assign it into the current DOM
2214 element.html(value);
2216 // compile the new DOM and link it to the current
2218 // NOTE: we only compile .childNodes so that
2219 // we don't get into infinite loop compiling ourselves
2220 $compile(element.contents())(scope);
2229 * Translates bare IDL object values into display values.
2230 * 1. Passes dates through the angular date filter
2231 * 2. Converts bools to translated Yes/No strings
2232 * Others likely to follow...
2234 .filter('egGridValueFilter', ['$filter','egCore', 'egStrings', function($filter,egCore,egStrings) {
2235 function traversePath(obj,path) {
2236 var list = path.split('.');
2237 for (var part in path) {
2238 if (obj[path]) obj = obj[path]
2244 var GVF = function(value, column, item) {
2245 switch(column.datatype) {
2248 // Browser will translate true/false for us
2250 case '1' : // legacy
2252 return egStrings.YES;
2254 case '0' : // legacy
2256 return egStrings.NO;
2257 // value may be null, '', etc.
2258 default : return '';
2261 var interval = angular.isFunction(item[column.dateonlyinterval])
2262 ? item[column.dateonlyinterval]()
2263 : item[column.dateonlyinterval];
2265 if (column.dateonlyinterval && !interval) // try it as a dotted path
2266 interval = traversePath(item, column.dateonlyinterval);
2268 var context = angular.isFunction(item[column.datecontext])
2269 ? item[column.datecontext]()
2270 : item[column.datecontext];
2272 if (column.datecontext && !context) // try it as a dotted path
2273 context = traversePath(item, column.datecontext);
2275 var date_filter = column.datefilter || 'egOrgDateInContext';
2277 return $filter(date_filter)(value, column.dateformat, context, interval);
2279 return $filter('currency')(value);
2285 GVF.$stateful = true;