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);
889 // Returns true of the contents of the cell overflow its container.
890 // parentDepth tells the code how far up the DOM tree to traverse
891 // via parentNode before stopping to inspect the value.
892 // There's no way to pass a reference to a DOM node directly via
893 // a scope function (except ng-click, etc.) so pass the
894 // DOM id instead and get the node from there.
895 $scope.cellOverflowed = function(id, parentDepth) {
896 var node = document.getElementById(id);
898 for (var i = 0; i < parentDepth; i++) {
899 node = node.parentNode;
901 return node.scrollHeight > node.clientHeight
902 || node.scrollWidth > node.clientWidth;
905 // Generates a unique identifier per cell per grid.
906 $scope.cellId = function(col, item) {
907 if (!col || !item) return '';
908 return 'grid-cell-span-'
909 // differentiate grids
910 + ($scope.persistKey || $scope.idlClass || $scope.grid_element.id)
911 // differentiate rows and columns.
912 + '-' + col.name + '-' + $scope.indexValue(item);
916 // handles click, control-click, and shift-click
917 $scope.handleRowClick = function($event, item) {
918 var index = grid.indexValue(item);
920 var origSelected = Object.keys($scope.selected);
922 if (!$scope.canMultiSelect) {
923 grid.selectOneItem(index);
924 grid.lastSelectedItemIndex = index;
928 if ($event.ctrlKey || $event.metaKey /* mac command */) {
930 if (grid.toggleSelectOneItem(index))
931 grid.lastSelectedItemIndex = index;
933 } else if ($event.shiftKey) {
936 if (!grid.lastSelectedItemIndex ||
937 index == grid.lastSelectedItemIndex) {
938 grid.selectOneItem(index);
939 grid.lastSelectedItemIndex = index;
943 var selecting = false;
944 var ascending = grid.itemComesBefore(
945 grid.lastSelectedItemIndex, item);
947 grid.indexOf(grid.lastSelectedItemIndex);
949 // update to new last-selected
950 grid.lastSelectedItemIndex = index;
952 // select each row between the last selected and
953 // currently selected items
955 startPos += ascending ? 1 : -1;
956 var curItem = $scope.items[startPos];
958 var curIdx = grid.indexValue(curItem);
959 $scope.selected[curIdx] = true;
960 if (curIdx == index) break; // all done
962 $scope.selected = angular.copy($scope.selected);
966 grid.selectOneItem(index);
967 grid.lastSelectedItemIndex = index;
971 // Builds a sort expression from column sort priorities.
972 // called on page load and any time the priorities are modified.
973 grid.compileSort = function() {
974 var sortList = grid.columnsProvider.columns.filter(
975 function(col) { return Number(col.sort) != 0 }
978 if (Math.abs(a.sort) < Math.abs(b.sort))
984 if (sortList.length) {
985 grid.dataProvider.sort = sortList.map(function(col) {
987 blob[col.name] = col.sort < 0 ? 'desc' : 'asc';
993 // builds a sort expression using a single column,
994 // toggling between ascending and descending sort.
995 $scope.quickSort = function(col_name) {
996 var sort = grid.dataProvider.sort;
997 if (sort && sort.length &&
998 sort[0] == col_name) {
1000 blob[col_name] = 'desc';
1001 grid.dataProvider.sort = [blob];
1003 grid.dataProvider.sort = [col_name];
1010 // show / hide the grid configuration row
1011 $scope.toggleConfDisplay = function() {
1012 if ($scope.showGridConf) {
1013 $scope.showGridConf = false;
1014 if (grid.columnsProvider.hasSortableColumn()) {
1015 // only refresh the grid if the user has the
1016 // ability to modify the sort priorities.
1022 $scope.showGridConf = true;
1025 delete $scope.lastModColumn;
1026 $scope.gridColumnPickerIsOpen = false;
1029 // called when a dragged column is dropped onto itself
1030 // or any other column
1031 grid.onColumnDrop = function(target) {
1032 if (angular.isUndefined(target)) return;
1033 if (target == grid.dragColumn) return;
1034 var srcIdx, targetIdx, srcCol;
1035 angular.forEach(grid.columnsProvider.columns,
1036 function(col, idx) {
1037 if (col.name == grid.dragColumn) {
1040 } else if (col.name == target) {
1046 if (srcIdx < targetIdx) targetIdx--;
1048 // move src column from old location to new location in
1049 // the columns array, then force a page refresh
1050 grid.columnsProvider.columns.splice(srcIdx, 1);
1051 grid.columnsProvider.columns.splice(targetIdx, 0, srcCol);
1055 // prepares a string for inclusion within a CSV document
1056 // by escaping commas and quotes and removing newlines.
1057 grid.csvDatum = function(str) {
1059 if (!str) return '';
1060 str = str.replace(/\n/g, '');
1061 if (str.match(/\,/) || str.match(/"/)) {
1062 str = str.replace(/"/g, '""');
1063 str = '"' + str + '"';
1068 /** Export the full data set as CSV.
1070 * 1. User clicks the 'download csv' link
1071 * 2. All grid data is retrieved asychronously
1072 * 3. Once all data is all present and CSV-ized, the download
1073 * attributes are linked to the href.
1074 * 4. The href .click() action is prgrammatically fired again,
1075 * telling the browser to download the data, now that the
1076 * data is available for download.
1077 * 5 Once downloaded, the href attributes are reset.
1079 grid.csvExportInProgress = false;
1080 $scope.generateCSVExportURL = function($event) {
1082 if (grid.csvExportInProgress) {
1083 // This is secondary href click handler. Give the
1084 // browser a moment to start the download, then reset
1085 // the CSV download attributes / state.
1088 $scope.csvExportURL = '';
1089 $scope.csvExportFileName = '';
1090 grid.csvExportInProgress = false;
1096 grid.csvExportInProgress = true;
1097 $scope.gridColumnPickerIsOpen = false;
1099 // let the file name describe the grid
1100 $scope.csvExportFileName =
1101 ($scope.mainLabel || grid.persistKey || 'eg_grid_data')
1102 .replace(/\s+/g, '_') + '_' + $scope.page();
1104 // toss the CSV into a Blob and update the export URL
1105 grid.generateCSV().then(function(csv) {
1106 var blob = new Blob([csv], {type : 'text/plain'});
1107 $scope.csvExportURL =
1108 ($window.URL || $window.webkitURL).createObjectURL(blob);
1110 // Fire the 2nd click event now that the browser has
1111 // information on how to download the CSV file.
1112 $timeout(function() {$event.target.click()});
1117 * TODO: does this serve any purpose given we can
1118 * print formatted HTML? If so, generateCSV() now
1119 * returns a promise, needs light refactoring...
1120 $scope.printCSV = function() {
1121 $scope.gridColumnPickerIsOpen = false;
1122 egCore.print.print({
1123 context : 'default',
1124 content : grid.generateCSV(),
1125 content_type : 'text/plain'
1130 // Given a row item and column definition, extract the
1131 // text content for printing. Templated columns must be
1132 // processed and parsed as HTML, then boiled down to their
1134 grid.getItemTextContent = function(item, col) {
1137 val = $scope.translateCellTemplate(col, item);
1139 var node = new DOMParser()
1140 .parseFromString(val, 'text/html');
1141 val = $(node).text();
1144 val = grid.dataProvider.itemFieldValue(item, col);
1145 val = $filter('egGridValueFilter')(val, col, item);
1150 $scope.getHtmlTooltip = function(col, item) {
1151 if ($scope.cellOverflowed($scope.cellId(col, item), 1)) {
1152 return grid.getItemTextContent(item, col);
1158 * Fetches all grid data and transates each item into a simple
1159 * key-value pair of column name => text-value.
1160 * Included in the response for convenience is the list of
1161 * currently visible column definitions.
1162 * TODO: currently fetches a maximum of 10k rows. Does this
1163 * need to be configurable?
1165 grid.getAllItemsAsText = function() {
1166 var text_items = [];
1168 // we don't know the total number of rows we're about
1169 // to retrieve, but we can indicate the number retrieved
1170 // so far as each item arrives.
1171 egProgressDialog.open({value : 0});
1173 var visible_cols = grid.columnsProvider.columns.filter(
1174 function(c) { return c.visible });
1176 return grid.dataProvider.get(0, 10000).then(
1178 return {items : text_items, columns : visible_cols};
1182 egProgressDialog.increment();
1184 angular.forEach(visible_cols, function(col) {
1185 text_item[col.name] =
1186 grid.getItemTextContent(item, col);
1188 text_items.push(text_item);
1190 ).finally(egProgressDialog.close);
1193 // Fetch "all" of the grid data, translate it into print-friendly
1194 // text, and send it to the printer service.
1195 $scope.printHTML = function() {
1196 $scope.gridColumnPickerIsOpen = false;
1197 return grid.getAllItemsAsText().then(function(text_items) {
1198 return egCore.print.print({
1199 template : 'grid_html',
1205 $scope.showColumnDialog = function() {
1206 return $uibModal.open({
1207 templateUrl: './share/t_grid_columns',
1210 controller: ['$scope', '$uibModalInstance',
1211 function($dialogScope, $uibModalInstance) {
1212 $dialogScope.modifyColumnPos = $scope.modifyColumnPos;
1213 $dialogScope.disableMultiSort = $scope.disableMultiSort;
1214 $dialogScope.columns = $scope.columns;
1216 // Push visible columns to the top of the list
1217 $dialogScope.elevateVisible = function() {
1219 angular.forEach($dialogScope.columns, function(col) {
1220 if (col.visible) new_cols.push(col);
1222 angular.forEach($dialogScope.columns, function(col) {
1223 if (!col.visible) new_cols.push(col);
1226 // Update all references to the list of columns
1227 $dialogScope.columns =
1229 grid.columnsProvider.columns =
1233 $dialogScope.toggle = function(col) {
1234 col.visible = !Boolean(col.visible);
1236 $dialogScope.ok = $dialogScope.cancel = function() {
1237 delete $scope.lastModColumn;
1238 $uibModalInstance.close()
1245 // generates CSV for the currently visible grid contents
1246 grid.generateCSV = function() {
1247 return grid.getAllItemsAsText().then(function(text_items) {
1248 var columns = text_items.columns;
1249 var items = text_items.items;
1253 angular.forEach(columns, function(col) {
1254 csvStr += grid.csvDatum(col.label);
1258 csvStr = csvStr.replace(/,$/,'\n');
1261 angular.forEach(items, function(item) {
1262 angular.forEach(columns, function(col) {
1263 csvStr += grid.csvDatum(item[col.name]);
1266 csvStr = csvStr.replace(/,$/,'\n');
1273 // Interpolate the value for column.linkpath within the context
1274 // of the row item to generate the final link URL.
1275 $scope.generateLinkPath = function(col, item) {
1276 return egCore.strings.$replace(col.linkpath, {item : item});
1279 // If a column provides its own HTML template, translate it,
1280 // using the current item for the template scope.
1281 // note: $sce is required to avoid security restrictions and
1282 // is OK here, since the template comes directly from a
1283 // local HTML template (not user input).
1284 $scope.translateCellTemplate = function(col, item) {
1285 var html = egCore.strings.$replace(col.template, {item : item});
1286 return $sce.trustAsHtml(html);
1289 $scope.collect = function() { grid.collect() }
1292 $scope.confirmAllowAllAndCollect = function(){
1293 egConfirmDialog.open(egStrings.CONFIRM_LONG_RUNNING_ACTION_ALL_ROWS_TITLE,
1294 egStrings.CONFIRM_LONG_RUNNING_ACTION_MSG)
1298 $scope.limit(10000);
1303 // asks the dataProvider for a page of data
1304 grid.collect = function() {
1306 // avoid firing the collect if there is nothing to collect.
1307 if (grid.selfManagedData && !grid.dataProvider.query) return;
1309 if (grid.collecting) return; // avoid parallel collect()
1310 grid.collecting = true;
1312 console.debug('egGrid.collect() offset='
1313 + grid.offset + '; limit=' + grid.limit);
1315 // ensure all of our dropdowns are closed
1316 // TODO: git rid of these and just use dropdown-toggle,
1317 // which is more reliable.
1318 $scope.gridColumnPickerIsOpen = false;
1319 $scope.gridRowCountIsOpen = false;
1320 $scope.gridPageSelectIsOpen = false;
1323 $scope.selected = {};
1325 // Inform the caller we've asked the data provider
1326 // for data. This is useful for knowing when collection
1327 // has started (e.g. to display a progress dialg) when
1328 // using the stock (flattener) data provider, where the
1329 // user is not directly defining a get() handler.
1330 if (grid.controls.collectStarted)
1331 grid.controls.collectStarted(grid.offset, grid.limit);
1333 grid.dataProvider.get(grid.offset, grid.limit).then(
1335 if (grid.controls.allItemsRetrieved)
1336 grid.controls.allItemsRetrieved();
1341 $scope.items.push(item)
1342 if (grid.controls.itemRetrieved)
1343 grid.controls.itemRetrieved(item);
1344 if ($scope.selectAll)
1345 $scope.selected[grid.indexValue(item)] = true
1347 }).finally(function() {
1348 console.debug('egGrid.collect() complete');
1349 grid.collecting = false
1350 $scope.selected = angular.copy($scope.selected);
1360 * eg-grid-field : used for collecting custom field data from the templates.
1361 * This directive does not direct display, it just passes data up to the
1364 .directive('egGridField', function() {
1366 require : '^egGrid',
1369 flesher: '=', // optional; function that can flesh a linked field, given the value
1370 comparator: '=', // optional; function that can sort the thing at the end of 'path'
1371 name : '@', // required; unique name
1372 path : '@', // optional; flesh path
1373 ignore: '@', // optional; fields to ignore when path is a wildcard
1374 label : '@', // optional; display label
1375 flex : '@', // optional; default flex width
1376 align : '@', // optional; default alignment, left/center/right
1377 dateformat : '@', // optional: passed down to egGridValueFilter
1378 datecontext: '@', // optional: passed down to egGridValueFilter to choose TZ
1379 datefilter: '@', // optional: passed down to egGridValueFilter to choose specialized date filters
1380 dateonlyinterval: '@', // optional: passed down to egGridValueFilter to choose a "better" format
1382 // if a field is part of an IDL object, but we are unable to
1383 // determine the class, because it's nested within a hash
1384 // (i.e. we can't navigate directly to the object via the IDL),
1385 // idlClass lets us specify the class. This is particularly
1386 // useful for nested wildcard fields.
1387 parentIdlClass : '@',
1389 // optional: for non-IDL columns, specifying a datatype
1390 // lets the caller control which display filter is used.
1391 // datatype should match the standard IDL datatypes.
1394 // optional hash of functions that can be imported into
1395 // the directive's scope; meant for cases where the "compiled"
1399 // optional: CSS class name that we want to have for this field.
1400 // Auto generated from path if nothing is passed in via eg-grid-field declaration
1403 link : function(scope, element, attrs, egGridCtrl) {
1405 // boolean fields are presented as value-less attributes
1415 'required' // if set, always fetch data for this column
1418 if (angular.isDefined(attrs[field]))
1419 scope[field] = true;
1423 scope.cssSelector = attrs['cssSelector'] ? attrs['cssSelector'] : "";
1425 // auto-generate CSS selector name for field if none declared in tt2 and there's a path
1426 if (scope.path && !scope.cssSelector){
1427 var cssClass = 'grid' + "." + scope.path;
1428 cssClass = cssClass.replace(/\./g,'-');
1429 element.addClass(cssClass);
1430 scope.cssSelector = cssClass;
1433 // any HTML content within the field is its custom template
1434 var tmpl = element.html();
1435 if (tmpl && !tmpl.match(/^\s*$/))
1436 scope.template = tmpl
1438 egGridCtrl.columnsProvider.add(scope);
1445 * eg-grid-action : used for specifying actions which may be applied
1446 * to items within the grid.
1448 .directive('egGridAction', function() {
1450 require : '^egGrid',
1454 group : '@', // Action group, ungrouped if not set
1455 label : '@', // Action label
1456 handler : '=', // Action function handler
1458 disabled : '=', // function
1461 link : function(scope, element, attrs, egGridCtrl) {
1462 egGridCtrl.addAction({
1464 group : scope.group,
1465 label : scope.label,
1466 divider : scope.divider,
1467 handler : scope.handler,
1468 disabled : scope.disabled,
1475 .factory('egGridColumnsProvider', ['egCore', function(egCore) {
1477 function ColumnsProvider(args) {
1480 cols.stockVisible = [];
1481 cols.idlClass = args.idlClass;
1482 cols.clientSort = args.clientSort;
1483 cols.defaultToHidden = args.defaultToHidden;
1484 cols.defaultToNoSort = args.defaultToNoSort;
1485 cols.defaultToNoMultiSort = args.defaultToNoMultiSort;
1486 cols.defaultDateFormat = args.defaultDateFormat;
1487 cols.defaultDateContext = args.defaultDateContext;
1489 // resets column width, visibility, and sort behavior
1490 // Visibility resets to the visibility settings defined in the
1491 // template (i.e. the original egGridField values).
1492 cols.reset = function() {
1493 angular.forEach(cols.columns, function(col) {
1497 if (cols.stockVisible.indexOf(col.name) > -1) {
1500 col.visible = false;
1505 // returns true if any columns are sortable
1506 cols.hasSortableColumn = function() {
1507 return cols.columns.filter(
1509 return col.sortable || col.multisortable;
1514 cols.showAllColumns = function() {
1515 angular.forEach(cols.columns, function(column) {
1516 column.visible = true;
1520 cols.hideAllColumns = function() {
1521 angular.forEach(cols.columns, function(col) {
1526 cols.indexOf = function(name) {
1527 for (var i = 0; i < cols.columns.length; i++) {
1528 if (cols.columns[i].name == name)
1534 cols.findColumn = function(name) {
1535 return cols.columns[cols.indexOf(name)];
1538 cols.compileAutoColumns = function() {
1539 var idl_class = egCore.idl.classes[cols.idlClass];
1544 if (field.virtual) return;
1545 if (field.datatype == 'link' || field.datatype == 'org_unit') {
1546 // if the field is a link and the linked class has a
1547 // "selector" field specified, use the selector field
1548 // as the display field for the columns.
1549 // flattener will take care of the fleshing.
1550 if (field['class']) {
1551 var selector_field = egCore.idl.classes[field['class']].fields
1552 .filter(function(f) { return Boolean(f.selector) })[0];
1553 if (selector_field) {
1554 field.path = field.name + '.' + selector_field.selector;
1558 cols.add(field, true);
1563 // if a column definition has a path with a wildcard, create
1564 // columns for all non-virtual fields at the specified
1565 // position in the path.
1566 cols.expandPath = function(colSpec) {
1568 var ignoreList = [];
1570 ignoreList = colSpec.ignore.split(' ');
1572 var dotpath = colSpec.path.replace(/\.?\*$/,'');
1576 if (colSpec.parentIdlClass) {
1577 class_obj = egCore.idl.classes[colSpec.parentIdlClass];
1579 class_obj = egCore.idl.classes[cols.idlClass];
1581 var idl_parent = class_obj;
1582 var old_field_label = '';
1584 if (!class_obj) return;
1586 //console.debug('egGrid: auto dotpath is: ' + dotpath);
1587 var path_parts = dotpath.split(/\./);
1589 // find the IDL class definition for the last element in the
1590 // path before the .*
1591 // an empty path_parts means expand the root class
1594 for (var path_idx in path_parts) {
1595 old_field = idl_field;
1597 var part = path_parts[path_idx];
1598 idl_field = class_obj.field_map[part];
1600 // unless we're at the end of the list, this field should
1601 // link to another class.
1602 if (idl_field && idl_field['class'] && (
1603 idl_field.datatype == 'link' ||
1604 idl_field.datatype == 'org_unit')) {
1605 if (old_field_label) old_field_label += ' : ';
1606 old_field_label += idl_field.label;
1607 class_obj = egCore.idl.classes[idl_field['class']];
1608 if (old_field) idl_parent = old_field;
1610 if (path_idx < (path_parts.length - 1)) {
1611 // we ran out of classes to hop through before
1612 // we ran out of path components
1613 console.error("egGrid: invalid IDL path: " + dotpath);
1620 angular.forEach(class_obj.fields, function(field) {
1622 // Only show wildcard fields where we have data to show
1623 // Virtual and un-fleshed links will not have any data.
1624 if (field.virtual ||
1625 (field.datatype == 'link' || field.datatype == 'org_unit') ||
1626 ignoreList.indexOf(field.name) > -1
1630 var col = cols.cloneFromScope(colSpec);
1631 col.path = (dotpath ? dotpath + '.' + field.name : field.name);
1633 // log line below is very chatty. disable until needed.
1634 // console.debug('egGrid: field: ' +field.name + '; parent field: ' + js2JSON(idl_parent));
1635 cols.add(col, false, true,
1636 {idl_parent : idl_parent, idl_field : field, idl_class : class_obj, field_parent_label : old_field_label });
1639 cols.columns = cols.columns.sort(
1641 if (a.explicit) return -1;
1642 if (b.explicit) return 1;
1644 if (a.idlclass && b.idlclass) {
1645 if (a.idlclass < b.idlclass) return -1;
1646 if (b.idlclass < a.idlclass) return 1;
1649 if (a.path && b.path && a.path.lastIndexOf('.') && b.path.lastIndexOf('.')) {
1650 if (a.path.substring(0, a.path.lastIndexOf('.')) < b.path.substring(0, b.path.lastIndexOf('.'))) return -1;
1651 if (b.path.substring(0, b.path.lastIndexOf('.')) < a.path.substring(0, a.path.lastIndexOf('.'))) return 1;
1654 if (a.label && b.label) {
1655 if (a.label < b.label) return -1;
1656 if (b.label < a.label) return 1;
1659 return a.name < b.name ? -1 : 1;
1666 "egGrid: wildcard path does not resolve to an object: "
1671 // angular.clone(scopeObject) is not permittable. Manually copy
1672 // the fields over that we need (so the scope object can go away).
1673 cols.cloneFromScope = function(colSpec) {
1675 flesher : colSpec.flesher,
1676 comparator : colSpec.comparator,
1677 name : colSpec.name,
1678 label : colSpec.label,
1679 path : colSpec.path,
1680 align : colSpec.align || 'left',
1681 flex : Number(colSpec.flex) || 2,
1682 sort : Number(colSpec.sort) || 0,
1683 required : colSpec.required,
1684 linkpath : colSpec.linkpath,
1685 template : colSpec.template,
1686 visible : colSpec.visible,
1687 compiled : colSpec.compiled,
1688 handlers : colSpec.handlers,
1689 hidden : colSpec.hidden,
1690 datatype : colSpec.datatype,
1691 sortable : colSpec.sortable,
1692 nonsortable : colSpec.nonsortable,
1693 multisortable : colSpec.multisortable,
1694 nonmultisortable : colSpec.nonmultisortable,
1695 dateformat : colSpec.dateformat,
1696 datecontext : colSpec.datecontext,
1697 datefilter : colSpec.datefilter,
1698 dateonlyinterval : colSpec.dateonlyinterval,
1699 parentIdlClass : colSpec.parentIdlClass,
1700 cssSelector : colSpec.cssSelector
1705 // Add a column to the columns collection.
1706 // Columns may come from a slim eg-columns-field or
1707 // directly from the IDL.
1708 cols.add = function(colSpec, fromIDL, fromExpand, idl_info) {
1710 // First added column with the specified path takes precedence.
1711 // This allows for specific definitions followed by wildcard
1712 // definitions. If a match is found, back out.
1713 if (cols.columns.filter(function(c) {
1714 return (c.path == colSpec.path) })[0]) {
1715 console.debug('skipping pre-existing column ' + colSpec.path);
1719 var column = fromExpand ? colSpec : cols.cloneFromScope(colSpec);
1721 if (column.path && column.path.match(/\*$/))
1722 return cols.expandPath(colSpec);
1724 if (!fromExpand) column.explicit = true;
1726 if (!column.name) column.name = column.path;
1727 if (!column.path) column.path = column.name;
1729 if (column.visible || (!cols.defaultToHidden && !column.hidden))
1730 column.visible = true;
1732 if (column.sortable || (!cols.defaultToNoSort && !column.nonsortable))
1733 column.sortable = true;
1735 if (column.multisortable ||
1736 (!cols.defaultToNoMultiSort && !column.nonmultisortable))
1737 column.multisortable = true;
1739 if (cols.defaultDateFormat && ! column.dateformat) {
1740 column.dateformat = cols.defaultDateFormat;
1743 if (cols.defaultDateOnlyInterval && ! column.dateonlyinterval) {
1744 column.dateonlyinterval = cols.defaultDateOnlyInterval;
1747 if (cols.defaultDateContext && ! column.datecontext) {
1748 column.datecontext = cols.defaultDateContext;
1751 if (cols.defaultDateFilter && ! column.datefilter) {
1752 column.datefilter = cols.defaultDateFilter;
1755 cols.columns.push(column);
1757 // Track which columns are visible by default in case we
1758 // need to reset column visibility
1760 cols.stockVisible.push(column.name);
1762 if (fromIDL) return; // directly from egIDL. nothing left to do.
1764 // lookup the matching IDL field
1765 if (!idl_info && cols.idlClass)
1766 idl_info = cols.idlFieldFromPath(column.path);
1769 // column is not represented within the IDL
1770 column.adhoc = true;
1774 column.datatype = idl_info.idl_field.datatype;
1776 if (!column.label) {
1777 column.label = idl_info.idl_field.label || column.name;
1780 if (fromExpand && idl_info.idl_class) {
1781 column.idlclass = '';
1782 if (idl_info.field_parent_label && idl_info.idl_parent.label != idl_info.idl_class.label) {
1783 column.idlclass = (idl_info.field_parent_label || idl_info.idl_parent.label || idl_info.idl_parent.name);
1785 column.idlclass += idl_info.idl_class.label || idl_info.idl_class.name;
1790 // finds the IDL field from the dotpath, using the columns
1791 // idlClass as the base.
1792 cols.idlFieldFromPath = function(dotpath) {
1793 var class_obj = egCore.idl.classes[cols.idlClass];
1794 if (!dotpath) return null;
1796 var path_parts = dotpath.split(/\./);
1800 for (var path_idx in path_parts) {
1801 var part = path_parts[path_idx];
1802 idl_parent = idl_field;
1803 idl_field = class_obj.field_map[part];
1806 if (idl_field['class'] && (
1807 idl_field.datatype == 'link' ||
1808 idl_field.datatype == 'org_unit')) {
1809 class_obj = egCore.idl.classes[idl_field['class']];
1817 idl_parent: idl_parent,
1818 idl_field : idl_field,
1819 idl_class : class_obj
1825 instance : function(args) { return new ColumnsProvider(args) }
1831 * Generic data provider template class. This is basically an abstract
1832 * class factory service whose instances can be locally modified to
1833 * meet the needs of each individual grid.
1835 .factory('egGridDataProvider',
1836 ['$q','$timeout','$filter','egCore',
1837 function($q , $timeout , $filter , egCore) {
1839 function GridDataProvider(args) {
1840 var gridData = this;
1841 if (!args) args = {};
1844 gridData.get = args.get;
1845 gridData.query = args.query;
1846 gridData.idlClass = args.idlClass;
1847 gridData.columnsProvider = args.columnsProvider;
1849 // Delivers a stream of array data via promise.notify()
1850 // Useful for passing an array of data to egGrid.get()
1851 // If a count is provided, the array will be trimmed to
1852 // the range defined by count and offset
1853 gridData.arrayNotifier = function(arr, offset, count) {
1854 if (!arr || arr.length == 0) return $q.when();
1856 if (gridData.columnsProvider.clientSort
1858 && gridData.sort.length > 0
1860 var sorter_cache = [];
1861 arr.sort(function(a,b) {
1862 for (var si = 0; si < gridData.sort.length; si++) {
1863 if (!sorter_cache[si]) { // Build sort structure on first comparison, reuse thereafter
1864 var field = gridData.sort[si];
1867 if (angular.isObject(field)) {
1868 dir = Object.values(field)[0];
1869 field = Object.keys(field)[0];
1872 var path = gridData.columnsProvider.findColumn(field).path || field;
1873 var comparator = gridData.columnsProvider.findColumn(field).comparator ||
1874 function (x,y) { if (x < y) return -1; if (x > y) return 1; return 0 };
1876 sorter_cache[si] = {
1879 comparator : comparator
1883 var sc = sorter_cache[si];
1887 if (a._isfieldmapper || angular.isFunction(a[sc.field])) {
1888 try {af = a[sc.field](); bf = b[sc.field]() } catch (e) {};
1890 af = a[sc.field]; bf = b[sc.field];
1892 if (af === undefined && sc.field.indexOf('.') > -1) { // assume an object, not flat path
1893 var parts = sc.field.split('.');
1896 angular.forEach(parts, function (p) {
1898 if (af._isfieldmapper || angular.isFunction(af[p])) af = af[p]();
1902 if (bf._isfieldmapper || angular.isFunction(bf[p])) bf = bf[p]();
1908 if (af === undefined) af = null;
1909 if (bf === undefined) bf = null;
1911 if (af === null && bf !== null) return 1;
1912 if (bf === null && af !== null) return -1;
1914 if (!(bf === null && af === null)) {
1915 var partial = sc.comparator(af,bf);
1917 if (sc.dir == 'desc') {
1918 if (partial > 0) return -1;
1930 if (count) arr = arr.slice(offset, offset + count);
1931 var def = $q.defer();
1932 // promise notifications are only witnessed when delivered
1933 // after the caller has his hands on the promise object
1934 $timeout(function() {
1935 angular.forEach(arr, def.notify);
1941 // Calls the grid refresh function. Once instantiated, the
1942 // grid will replace this function with it's own refresh()
1943 gridData.refresh = function(noReset) { }
1945 if (!gridData.get) {
1946 // returns a promise whose notify() delivers items
1947 gridData.get = function(index, count) {
1948 console.error("egGridDataProvider.get() not implemented");
1952 // attempts a flat field lookup first. If the column is not
1953 // found on the top-level object, attempts a nested lookup
1954 // TODO: consider a caching layer to speed up template
1955 // rendering, particularly for nested objects?
1956 gridData.itemFieldValue = function(item, column) {
1958 if (column.name in item) {
1959 if (typeof item[column.name] == 'function') {
1960 val = item[column.name]();
1962 val = item[column.name];
1965 val = gridData.nestedItemFieldValue(item, column);
1971 // TODO: deprecate me
1972 gridData.flatItemFieldValue = function(item, column) {
1973 console.warn('gridData.flatItemFieldValue deprecated; '
1974 + 'leave provider.itemFieldValue unset');
1975 return item[column.name];
1978 // given an object and a dot-separated path to a field,
1979 // extract the value of the field. The path can refer
1980 // to function names or object attributes. If the final
1981 // value is an IDL field, run the value through its
1982 // corresponding output filter.
1983 gridData.nestedItemFieldValue = function(obj, column) {
1984 item = obj; // keep a copy around
1986 if (obj === null || obj === undefined || obj === '') return '';
1987 if (!column.path) return obj;
1990 var parts = column.path.split('.');
1992 angular.forEach(parts, function(step, idx) {
1993 // object is not fleshed to the expected extent
1994 if (typeof obj != 'object') {
1995 if (typeof obj != 'undefined' && column.flesher) {
1996 obj = column.flesher(obj, column, item);
2003 if (!obj) return '';
2005 var cls = obj.classname;
2006 if (cls && (class_obj = egCore.idl.classes[cls])) {
2007 idl_field = class_obj.field_map[step];
2008 obj = obj[step] ? obj[step]() : '';
2010 if (angular.isFunction(obj[step])) {
2018 // We found a nested IDL object which may or may not have
2019 // been configured as a top-level column. Grab the datatype.
2020 if (idl_field && !column.datatype)
2021 column.datatype = idl_field.datatype;
2023 if (obj === null || obj === undefined || obj === '') return '';
2029 instance : function(args) {
2030 return new GridDataProvider(args);
2037 // Factory service for egGridDataManager instances, which are
2038 // responsible for collecting flattened grid data.
2039 .factory('egGridFlatDataProvider',
2040 ['$q','egCore','egGridDataProvider',
2041 function($q , egCore , egGridDataProvider) {
2044 instance : function(args) {
2045 var provider = egGridDataProvider.instance(args);
2047 provider.get = function(offset, count) {
2049 // no query means no call
2050 if (!provider.query ||
2051 angular.equals(provider.query, {}))
2054 // find all of the currently visible columns
2055 var queryFields = {}
2056 angular.forEach(provider.columnsProvider.columns,
2058 // only query IDL-tracked columns
2059 if (!col.adhoc && col.name && col.path && (col.required || col.visible))
2060 queryFields[col.name] = col.path;
2064 return egCore.net.request(
2066 'open-ils.fielder.flattened_search',
2067 egCore.auth.token(), provider.idlClass,
2068 queryFields, provider.query,
2069 { sort : provider.sort,
2075 //provider.itemFieldValue = provider.flatItemFieldValue;
2082 .directive('egGridColumnDragSource', function() {
2085 require : '^egGrid',
2086 link : function(scope, element, attrs, egGridCtrl) {
2087 angular.element(element).attr('draggable', 'true');
2089 element.bind('dragstart', function(e) {
2090 egGridCtrl.dragColumn = attrs.column;
2091 egGridCtrl.dragType = attrs.dragType || 'move'; // or resize
2092 egGridCtrl.colResizeDir = 0;
2094 if (egGridCtrl.dragType == 'move') {
2095 // style the column getting moved
2096 angular.element(e.target).addClass(
2097 'eg-grid-column-move-handle-active');
2101 element.bind('dragend', function(e) {
2102 if (egGridCtrl.dragType == 'move') {
2103 angular.element(e.target).removeClass(
2104 'eg-grid-column-move-handle-active');
2111 .directive('egGridColumnDragDest', function() {
2114 require : '^egGrid',
2115 link : function(scope, element, attrs, egGridCtrl) {
2117 element.bind('dragover', function(e) { // required for drop
2118 e.stopPropagation();
2120 e.dataTransfer.dropEffect = 'move';
2122 if (egGridCtrl.colResizeDir == 0) return; // move
2124 var cols = egGridCtrl.columnsProvider;
2125 var srcCol = egGridCtrl.dragColumn;
2126 var srcColIdx = cols.indexOf(srcCol);
2128 if (egGridCtrl.colResizeDir == -1) {
2129 if (cols.indexOf(attrs.column) <= srcColIdx) {
2130 egGridCtrl.modifyColumnFlex(
2131 egGridCtrl.columnsProvider.findColumn(
2132 egGridCtrl.dragColumn), -1);
2133 if (cols.columns[srcColIdx+1]) {
2134 // source column shrinks by one, column to the
2135 // right grows by one.
2136 egGridCtrl.modifyColumnFlex(
2137 cols.columns[srcColIdx+1], 1);
2142 if (cols.indexOf(attrs.column) > srcColIdx) {
2143 egGridCtrl.modifyColumnFlex(
2144 egGridCtrl.columnsProvider.findColumn(
2145 egGridCtrl.dragColumn), 1);
2146 if (cols.columns[srcColIdx+1]) {
2147 // source column grows by one, column to the
2148 // right grows by one.
2149 egGridCtrl.modifyColumnFlex(
2150 cols.columns[srcColIdx+1], -1);
2158 element.bind('dragenter', function(e) {
2159 e.stopPropagation();
2161 if (egGridCtrl.dragType == 'move') {
2162 angular.element(e.target).addClass('eg-grid-col-hover');
2164 // resize grips are on the right side of each column.
2165 // dragenter will either occur on the source column
2166 // (dragging left) or the column to the right.
2167 if (egGridCtrl.colResizeDir == 0) {
2168 if (egGridCtrl.dragColumn == attrs.column) {
2169 egGridCtrl.colResizeDir = -1; // west
2171 egGridCtrl.colResizeDir = 1; // east
2177 element.bind('dragleave', function(e) {
2178 e.stopPropagation();
2180 if (egGridCtrl.dragType == 'move') {
2181 angular.element(e.target).removeClass('eg-grid-col-hover');
2185 element.bind('drop', function(e) {
2186 e.stopPropagation();
2188 egGridCtrl.colResizeDir = 0;
2189 if (egGridCtrl.dragType == 'move') {
2190 angular.element(e.target).removeClass('eg-grid-col-hover');
2191 egGridCtrl.onColumnDrop(attrs.column); // move the column
2198 .directive('egGridMenuItem', function() {
2201 require : '^egGrid',
2207 handler : '=', // onclick handler function
2208 divider : '=', // if true, show a divider only
2209 handlerData : '=', // if set, passed as second argument to handler
2210 disabled : '=', // function
2211 hidden : '=' // function
2213 link : function(scope, element, attrs, egGridCtrl) {
2214 egGridCtrl.addMenuItem({
2215 checkbox : scope.checkbox,
2216 checked : scope.checked ? true : false,
2217 label : scope.label,
2218 standalone : scope.standalone ? true : false,
2219 handler : scope.handler,
2220 divider : scope.divider,
2221 disabled : scope.disabled,
2222 hidden : scope.hidden,
2223 handlerData : scope.handlerData
2230 /* https://stackoverflow.com/questions/17343696/adding-an-ng-click-event-inside-a-filter/17344875#17344875 */
2231 .directive('compile', ['$compile', function ($compile) {
2232 return function(scope, element, attrs) {
2233 // pass through column defs from grid cell's scope
2234 scope.col = scope.$parent.col;
2237 // watch the 'compile' expression for changes
2238 return scope.$eval(attrs.compile);
2241 // when the 'compile' expression changes
2242 // assign it into the current DOM
2243 element.html(value);
2245 // compile the new DOM and link it to the current
2247 // NOTE: we only compile .childNodes so that
2248 // we don't get into infinite loop compiling ourselves
2249 $compile(element.contents())(scope);
2258 * Translates bare IDL object values into display values.
2259 * 1. Passes dates through the angular date filter
2260 * 2. Converts bools to translated Yes/No strings
2261 * Others likely to follow...
2263 .filter('egGridValueFilter', ['$filter','egCore', 'egStrings', function($filter,egCore,egStrings) {
2264 function traversePath(obj,path) {
2265 var list = path.split('.');
2266 for (var part in path) {
2267 if (obj[path]) obj = obj[path]
2273 var GVF = function(value, column, item) {
2274 switch(column.datatype) {
2277 // Browser will translate true/false for us
2279 case '1' : // legacy
2281 return egStrings.YES;
2283 case '0' : // legacy
2285 return egStrings.NO;
2286 // value may be null, '', etc.
2287 default : return '';
2290 var interval = angular.isFunction(item[column.dateonlyinterval])
2291 ? item[column.dateonlyinterval]()
2292 : item[column.dateonlyinterval];
2294 if (column.dateonlyinterval && !interval) // try it as a dotted path
2295 interval = traversePath(item, column.dateonlyinterval);
2297 var context = angular.isFunction(item[column.datecontext])
2298 ? item[column.datecontext]()
2299 : item[column.datecontext];
2301 if (column.datecontext && !context) // try it as a dotted path
2302 context = traversePath(item, column.datecontext);
2304 var date_filter = column.datefilter || 'egOrgDateInContext';
2306 return $filter(date_filter)(value, column.dateformat, context, interval);
2308 return $filter('currency')(value);
2314 GVF.$stateful = true;