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 controls.contextMenuItem = function() {
285 return $scope.contextMenuItem;
288 // link in the control functions
289 controls.selectedItems = function() {
290 return grid.getSelectedItems()
293 controls.selectItemsByValue = function(c,v) {
294 return grid.selectItemsByValue(c,v)
297 controls.allItems = function() {
301 controls.selectItems = function(ids) {
303 $scope.selected = {};
304 angular.forEach(ids, function(i) {
305 $scope.selected[''+i] = true;
309 // if the caller provided a functional setQuery,
310 // extract the value before replacing it
311 if (controls.setQuery) {
312 grid.dataProvider.query =
316 controls.setQuery = function(query) {
317 grid.dataProvider.query = query;
321 if (controls.watchQuery) {
322 // capture the initial query value
323 grid.dataProvider.query = controls.watchQuery();
326 $scope.gridWatchQuery = controls.watchQuery;
327 $scope.$watch('gridWatchQuery()', function(newv) {
328 controls.setQuery(newv);
332 // if the caller provided a functional setSort
333 // extract the value before replacing it
334 grid.dataProvider.sort =
335 controls.setSort ? controls.setSort() : [];
337 controls.setSort = function(sort) {
341 controls.refresh = function(noReset) {
342 if (!noReset) grid.offset = 0;
346 controls.prepend = function(limit) {
350 controls.setLimit = function(limit,forget) {
352 if (!forget && grid.persistKey) {
356 controls.getLimit = function() {
359 controls.setOffset = function(offset) {
360 grid.offset = offset;
362 controls.getOffset = function() {
366 controls.saveConfig = function () {
367 return $scope.saveConfig();
370 grid.dataProvider.refresh = controls.refresh;
371 grid.dataProvider.prepend = controls.prepend;
372 grid.controls = controls;
375 // If a menu item provides its own HTML template, translate it,
376 // using the menu item for the template scope.
377 // note: $sce is required to avoid security restrictions and
378 // is OK here, since the template comes directly from a
379 // local HTML template (not user input).
380 $scope.translateMenuItemTemplate = function(item) {
381 var html = egCore.strings.$replace(item.template, {item : item});
382 return $sce.trustAsHtml(html);
385 // add a new (global) grid menu item
386 grid.addMenuItem = function(item) {
387 $scope.menuItems.push(item);
388 var handler = item.handler;
389 item.handler = function() {
390 $scope.gridMenuIsOpen = false; // close menu
393 item.handlerData, grid.getSelectedItems());
398 // add a selected-items action
399 grid.addAction = function(act) {
401 $scope.actionGroups.forEach(function(g){
402 if (g.label === act.group) {
408 $scope.actionGroups.push({
415 // remove the stored column configuration preferenc, then recover
416 // the column visibility information from the initial page load.
417 $scope.resetColumns = function() {
418 $scope.gridColumnPickerIsOpen = false;
419 egCore.hatch.removeItem('eg.grid.' + grid.persistKey)
421 grid.columnsProvider.reset();
422 if (grid.selfManagedData) grid.collect();
426 $scope.showAllColumns = function() {
427 $scope.gridColumnPickerIsOpen = false;
428 grid.columnsProvider.showAllColumns();
429 if (grid.selfManagedData) grid.collect();
432 $scope.hideAllColumns = function() {
433 $scope.gridColumnPickerIsOpen = false;
434 grid.columnsProvider.hideAllColumns();
435 // note: no need to fetch new data if no columns are visible
438 $scope.toggleColumnVisibility = function(col) {
439 $scope.gridColumnPickerIsOpen = false;
440 col.visible = !col.visible;
442 // egGridFlatDataProvider only retrieves data to be
443 // displayed. When column visibility changes, it's
444 // necessary to fetch the newly visible column data.
445 if (grid.selfManagedData) grid.collect();
448 // save the columns configuration (position, sort, width) to
449 // eg.grid.<persist-key>
450 $scope.saveConfig = function() {
451 $scope.gridColumnPickerIsOpen = false;
453 if (!grid.persistKey) {
455 "Cannot save settings without a grid persist-key");
459 // only store information about visible columns.
460 var cols = grid.columnsProvider.columns.filter(
461 function(col) {return Boolean(col.visible) });
463 // now scrunch the data down to just the needed info
464 cols = cols.map(function(col) {
465 var c = {name : col.name}
466 // Apart from the name, only store non-default values.
467 // No need to store col.visible, since that's implicit
468 if (col.align != 'left') c.align = col.align;
469 if (col.flex != 2) c.flex = col.flex;
470 if (Number(col.sort)) c.sort = Number(col.sort);
480 egCore.hatch.setItem('eg.grid.' + grid.persistKey, conf)
482 // Save operation performed from the grid configuration UI.
483 // Hide the configuration UI and re-draw w/ sort applied
484 if ($scope.showGridConf)
485 $scope.toggleConfDisplay();
487 // Once a version-2 grid config is saved (with limit
488 // included) we can remove the local limit pref.
489 egCore.hatch.removeLocalItem(
490 'eg.grid.' + grid.persistKey + '.limit');
495 // load the columns configuration (position, sort, width) from
496 // eg.grid.<persist-key> and apply the loaded settings to the
497 // columns on our columnsProvider
498 grid.loadConfig = function() {
499 if (!grid.persistKey) return $q.when();
501 return egCore.hatch.getItem('eg.grid.' + grid.persistKey)
502 .then(function(conf) {
505 // load all column options before validating saved columns
506 $scope.handleAutoFields();
508 var columns = grid.columnsProvider.columns;
511 if (Array.isArray(conf)) {
513 'upgrading version 1 grid config to version 2');
521 grid.limit = Number(conf.limit);
524 angular.forEach(conf.columns, function(col) {
525 var grid_col = columns.filter(
526 function(c) {return c.name == col.name})[0];
529 // saved column does not match a column in the
530 // current grid. skip it.
534 grid_col.align = col.align || 'left';
535 grid_col.flex = col.flex || 2;
536 grid_col.sort = col.sort || 0;
537 // all saved columns are assumed to be true
538 grid_col.visible = true;
540 .filter(function (c) {
541 return c.name == grid_col.name;
544 new_cols.push(grid_col);
547 // columns which are not expressed within the saved
548 // configuration are marked as non-visible and
549 // appended to the end of the new list of columns.
550 angular.forEach(columns, function(col) {
551 var found = conf.columns.filter(
552 function(c) {return (c.name == col.name)})[0];
559 grid.columnsProvider.columns = new_cols;
565 $scope.onContextMenu = function($event) {
566 var col = angular.element($event.target).attr('column');
567 console.log('selected column ' + col);
570 $scope.page = function() {
571 return (grid.offset / grid.limit) + 1;
574 $scope.goToPage = function(page) {
576 if (angular.isNumber(page) && page > 0) {
577 grid.offset = (page - 1) * grid.limit;
582 $scope.offset = function(o) {
583 if (angular.isNumber(o))
588 $scope.limit = function(l) {
589 if (angular.isNumber(l)) {
591 if (grid.persistKey) {
598 $scope.onFirstPage = function() {
599 return grid.offset == 0;
602 $scope.hasNextPage = function() {
603 // we have less data than requested, there must
604 // not be any more pages
605 if (grid.count() < grid.limit) return false;
607 // if the total count is not known, assume that a full
608 // page of data implies more pages are available.
609 if (grid.totalCount == -1) return true;
611 // we have a full page of data, but is there more?
612 return grid.totalCount > (grid.offset + grid.count());
615 $scope.incrementPage = function() {
616 grid.offset += grid.limit;
620 $scope.decrementPage = function() {
621 if (grid.offset < grid.limit) {
624 grid.offset -= grid.limit;
629 // number of items loaded for the current page of results
630 grid.count = function() {
631 return $scope.items.length;
634 // returns the unique identifier value for the provided item
635 // for internal consistency, indexValue is always coerced
637 grid.indexValue = function(item) {
638 if (angular.isObject(item)) {
640 if (angular.isFunction(item[grid.indexField]))
641 return ''+item[grid.indexField]();
642 return ''+item[grid.indexField]; // flat data
645 // passed a non-object; assume it's an index
649 // fires the hide handler function for a context action
650 $scope.actionHide = function(action) {
651 if (typeof action.hide == 'undefined') {
654 if (angular.isFunction(action.hide))
655 return action.hide(action);
659 // fires the disable handler function for a context action
660 $scope.actionDisable = function(action) {
661 if(grid.getSelectedItems().length == 0 && action.handler.length > 0) {
664 if (typeof action.disabled == 'undefined') {
667 if (angular.isFunction(action.disabled))
668 return action.disabled(action);
669 return action.disabled;
672 // fires the action handler function for a context action
673 $scope.actionLauncher = function(action) {
674 if (!action.handler) {
676 'No handler specified for "' + action.label + '"');
680 action.handler(grid.getSelectedItems());
682 console.error('Error executing handler for "'
683 + action.label + '" => ' + E + "\n" + E.stack);
686 if ($scope.action_context_showing) $scope.hideActionContextMenu();
691 $scope.hideActionContextMenu = function () {
692 $($scope.menu_dom).css({
694 width: $scope.action_context_width,
695 top: $scope.action_context_y,
696 left: $scope.action_context_x
698 $($scope.action_context_parent).append($scope.menu_dom);
699 $scope.action_context_oldy = $scope.action_context_oldx = 0;
700 $('body').unbind('click.remove_context_menu_'+$scope.action_context_index);
701 $scope.action_context_showing = false;
704 $scope.action_context_showing = false;
705 $scope.showActionContextMenu = function ($event) {
707 // Have to gather these here, instead of inside link()
708 if (!$scope.menu_dom) $scope.menu_dom = $($scope.grid_element).find('.grid-action-dropdown')[0];
709 if (!$scope.action_context_parent) $scope.action_context_parent = $($scope.menu_dom).parent();
711 // we need the the row that got right-clicked...
712 var e = $event.target; // the DOM element
713 var s = undefined; // the angular scope for that element
714 while(e){ // searching for the row
715 // abort & use the browser default context menu for links (lp1669856):
716 if(e.tagName.toLowerCase() === 'a' && e.href){ return true; }
717 s = angular.element(e).scope();
718 if(s.hasOwnProperty('item')){ break; }
722 $scope.contextMenuItem = grid.indexValue(s.item);
724 // select the right-clicked row if it is not already selected (lp1776557):
725 if(!$scope.selected[grid.indexValue(s.item)]){ $event.target.click(); }
727 if (!$scope.action_context_showing) {
728 $scope.action_context_width = $($scope.menu_dom).css('width');
729 $scope.action_context_y = $($scope.menu_dom).css('top');
730 $scope.action_context_x = $($scope.menu_dom).css('left');
731 $scope.action_context_showing = true;
732 $scope.action_context_index = Math.floor((Math.random() * 1000) + 1);
734 $('body').append($($scope.menu_dom));
735 $('body').bind('click.remove_context_menu_'+$scope.action_context_index, $scope.hideActionContextMenu);
738 $($scope.menu_dom).css({
740 width: $scope.action_context_width,
748 // returns the list of selected item objects
749 grid.getSelectedItems = function() {
750 return $scope.items.filter(
752 return Boolean($scope.selected[grid.indexValue(item)]);
757 grid.getItemByIndex = function(index) {
758 for (var i = 0; i < $scope.items.length; i++) {
759 var item = $scope.items[i];
760 if (grid.indexValue(item) == index)
765 // selects one row after deselecting all of the others
766 grid.selectOneItem = function(index) {
767 $scope.selected = {};
768 $scope.selected[index] = true;
771 // selects items by a column value, first clearing selected list.
772 // we overwrite the object so that we can watch $scope.selected
773 grid.selectItemsByValue = function(column, value) {
774 $scope.selected = {};
775 angular.forEach($scope.items, function(item) {
777 if (angular.isFunction(item[column]))
778 col_value = item[column]();
780 col_value = item[column];
782 if (value == col_value) $scope.selected[grid.indexValue(item)] = true
786 // selects or deselects an item, without affecting the others.
787 // returns true if the item is selected; false if de-selected.
788 // we overwrite the object so that we can watch $scope.selected
789 grid.toggleSelectOneItem = function(index) {
790 if ($scope.selected[index]) {
791 delete $scope.selected[index];
792 $scope.selected = angular.copy($scope.selected);
795 $scope.selected[index] = true;
796 $scope.selected = angular.copy($scope.selected);
801 $scope.updateSelected = function () {
802 return $scope.selected = angular.copy($scope.selected);
805 grid.selectAllItems = function() {
806 angular.forEach($scope.items, function(item) {
807 $scope.selected[grid.indexValue(item)] = true
809 $scope.selected = angular.copy($scope.selected);
812 $scope.$watch('selectAll', function(newVal) {
814 grid.selectAllItems();
816 $scope.selected = {};
820 if ($scope.onSelect) {
821 $scope.$watch('selected', function(newVal) {
822 $scope.onSelect(grid.getSelectedItems());
823 if ($scope.afterSelect) $scope.afterSelect();
827 // returns true if item1 appears in the list before item2;
828 // false otherwise. this is slightly more efficient that
829 // finding the position of each then comparing them.
830 // item1 / item2 may be an item or an item index
831 grid.itemComesBefore = function(itemOrIndex1, itemOrIndex2) {
832 var idx1 = grid.indexValue(itemOrIndex1);
833 var idx2 = grid.indexValue(itemOrIndex2);
835 // use for() for early exit
836 for (var i = 0; i < $scope.items.length; i++) {
837 var idx = grid.indexValue($scope.items[i]);
838 if (idx == idx1) return true;
839 if (idx == idx2) return false;
844 // 0-based position of item in the current data set
845 grid.indexOf = function(item) {
846 var idx = grid.indexValue(item);
847 for (var i = 0; i < $scope.items.length; i++) {
848 if (grid.indexValue($scope.items[i]) == idx)
854 grid.modifyColumnFlex = function(column, val) {
856 // prevent flex:0; use hiding instead
860 $scope.modifyColumnFlex = function(col, val) {
861 $scope.lastModColumn = col;
862 grid.modifyColumnFlex(col, val);
865 $scope.isLastModifiedColumn = function(col) {
866 if ($scope.lastModColumn)
867 return $scope.lastModColumn === col;
871 grid.modifyColumnPos = function(col, diff) {
872 var srcIdx, targetIdx;
873 angular.forEach(grid.columnsProvider.columns,
874 function(c, i) { if (c.name == col.name) srcIdx = i });
876 targetIdx = srcIdx + diff;
879 } else if (targetIdx >= grid.columnsProvider.columns.length) {
880 // Target index follows the last visible column.
882 angular.forEach(grid.columnsProvider.columns,
883 function(column, idx) {
884 if (column.visible) lastVisible = idx;
888 // When moving a column (down) causes one or more
889 // visible columns to shuffle forward, our column
890 // moves into the slot of the last visible column.
891 // Otherwise, put it into the slot directly following
892 // the last visible column.
894 srcIdx <= lastVisible ? lastVisible : lastVisible + 1;
897 // Splice column out of old position, insert at new position.
898 grid.columnsProvider.columns.splice(srcIdx, 1);
899 grid.columnsProvider.columns.splice(targetIdx, 0, col);
902 $scope.modifyColumnPos = function(col, diff) {
903 $scope.lastModColumn = col;
904 return grid.modifyColumnPos(col, diff);
908 // handles click, control-click, and shift-click
909 $scope.handleRowClick = function($event, item) {
910 var index = grid.indexValue(item);
912 var origSelected = Object.keys($scope.selected);
914 if (!$scope.canMultiSelect) {
915 grid.selectOneItem(index);
916 grid.lastSelectedItemIndex = index;
920 if ($event.ctrlKey || $event.metaKey /* mac command */) {
922 if (grid.toggleSelectOneItem(index))
923 grid.lastSelectedItemIndex = index;
925 } else if ($event.shiftKey) {
928 if (!grid.lastSelectedItemIndex ||
929 index == grid.lastSelectedItemIndex) {
930 grid.selectOneItem(index);
931 grid.lastSelectedItemIndex = index;
935 var selecting = false;
936 var ascending = grid.itemComesBefore(
937 grid.lastSelectedItemIndex, item);
939 grid.indexOf(grid.lastSelectedItemIndex);
941 // update to new last-selected
942 grid.lastSelectedItemIndex = index;
944 // select each row between the last selected and
945 // currently selected items
947 startPos += ascending ? 1 : -1;
948 var curItem = $scope.items[startPos];
950 var curIdx = grid.indexValue(curItem);
951 $scope.selected[curIdx] = true;
952 if (curIdx == index) break; // all done
954 $scope.selected = angular.copy($scope.selected);
958 grid.selectOneItem(index);
959 grid.lastSelectedItemIndex = index;
963 // Builds a sort expression from column sort priorities.
964 // called on page load and any time the priorities are modified.
965 grid.compileSort = function() {
966 var sortList = grid.columnsProvider.columns.filter(
967 function(col) { return Number(col.sort) != 0 }
970 if (Math.abs(a.sort) < Math.abs(b.sort))
976 if (sortList.length) {
977 grid.dataProvider.sort = sortList.map(function(col) {
979 blob[col.name] = col.sort < 0 ? 'desc' : 'asc';
985 // builds a sort expression using a single column,
986 // toggling between ascending and descending sort.
987 $scope.quickSort = function(col_name) {
988 var sort = grid.dataProvider.sort;
989 if (sort && sort.length &&
990 sort[0] == col_name) {
992 blob[col_name] = 'desc';
993 grid.dataProvider.sort = [blob];
995 grid.dataProvider.sort = [col_name];
1002 // show / hide the grid configuration row
1003 $scope.toggleConfDisplay = function() {
1004 if ($scope.showGridConf) {
1005 $scope.showGridConf = false;
1006 if (grid.columnsProvider.hasSortableColumn()) {
1007 // only refresh the grid if the user has the
1008 // ability to modify the sort priorities.
1014 $scope.showGridConf = true;
1017 delete $scope.lastModColumn;
1018 $scope.gridColumnPickerIsOpen = false;
1021 // called when a dragged column is dropped onto itself
1022 // or any other column
1023 grid.onColumnDrop = function(target) {
1024 if (angular.isUndefined(target)) return;
1025 if (target == grid.dragColumn) return;
1026 var srcIdx, targetIdx, srcCol;
1027 angular.forEach(grid.columnsProvider.columns,
1028 function(col, idx) {
1029 if (col.name == grid.dragColumn) {
1032 } else if (col.name == target) {
1038 if (srcIdx < targetIdx) targetIdx--;
1040 // move src column from old location to new location in
1041 // the columns array, then force a page refresh
1042 grid.columnsProvider.columns.splice(srcIdx, 1);
1043 grid.columnsProvider.columns.splice(targetIdx, 0, srcCol);
1047 // prepares a string for inclusion within a CSV document
1048 // by escaping commas and quotes and removing newlines.
1049 grid.csvDatum = function(str) {
1051 if (!str) return '';
1052 str = str.replace(/\n/g, '');
1053 if (str.match(/\,/) || str.match(/"/)) {
1054 str = str.replace(/"/g, '""');
1055 str = '"' + str + '"';
1060 /** Export the full data set as CSV.
1062 * 1. User clicks the 'download csv' link
1063 * 2. All grid data is retrieved asychronously
1064 * 3. Once all data is all present and CSV-ized, the download
1065 * attributes are linked to the href.
1066 * 4. The href .click() action is prgrammatically fired again,
1067 * telling the browser to download the data, now that the
1068 * data is available for download.
1069 * 5 Once downloaded, the href attributes are reset.
1071 grid.csvExportInProgress = false;
1072 $scope.generateCSVExportURL = function($event) {
1074 if (grid.csvExportInProgress) {
1075 // This is secondary href click handler. Give the
1076 // browser a moment to start the download, then reset
1077 // the CSV download attributes / state.
1080 $scope.csvExportURL = '';
1081 $scope.csvExportFileName = '';
1082 grid.csvExportInProgress = false;
1088 grid.csvExportInProgress = true;
1089 $scope.gridColumnPickerIsOpen = false;
1091 // let the file name describe the grid
1092 $scope.csvExportFileName =
1093 ($scope.mainLabel || grid.persistKey || 'eg_grid_data')
1094 .replace(/\s+/g, '_') + '_' + $scope.page();
1096 // toss the CSV into a Blob and update the export URL
1097 grid.generateCSV().then(function(csv) {
1098 var blob = new Blob([csv], {type : 'text/plain'});
1099 $scope.csvExportURL =
1100 ($window.URL || $window.webkitURL).createObjectURL(blob);
1102 // Fire the 2nd click event now that the browser has
1103 // information on how to download the CSV file.
1104 $timeout(function() {$event.target.click()});
1109 * TODO: does this serve any purpose given we can
1110 * print formatted HTML? If so, generateCSV() now
1111 * returns a promise, needs light refactoring...
1112 $scope.printCSV = function() {
1113 $scope.gridColumnPickerIsOpen = false;
1114 egCore.print.print({
1115 context : 'default',
1116 content : grid.generateCSV(),
1117 content_type : 'text/plain'
1122 // Given a row item and column definition, extract the
1123 // text content for printing. Templated columns must be
1124 // processed and parsed as HTML, then boiled down to their
1126 grid.getItemTextContent = function(item, col) {
1129 val = $scope.translateCellTemplate(col, item);
1131 var node = new DOMParser()
1132 .parseFromString(val, 'text/html');
1133 val = $(node).text();
1136 val = grid.dataProvider.itemFieldValue(item, col);
1137 if (val === null || val === undefined || val === '') return '';
1138 val = $filter('egGridValueFilter')(val, col, item);
1143 $scope.getHtmlTooltip = function(col, item) {
1144 return grid.getItemTextContent(item, col);
1148 * Fetches all grid data and transates each item into a simple
1149 * key-value pair of column name => text-value.
1150 * Included in the response for convenience is the list of
1151 * currently visible column definitions.
1152 * TODO: currently fetches a maximum of 10k rows. Does this
1153 * need to be configurable?
1155 grid.getAllItemsAsText = function() {
1156 var text_items = [];
1158 // we don't know the total number of rows we're about
1159 // to retrieve, but we can indicate the number retrieved
1160 // so far as each item arrives.
1161 egProgressDialog.open({value : 0});
1163 var visible_cols = grid.columnsProvider.columns.filter(
1164 function(c) { return c.visible });
1166 return grid.dataProvider.get(0, 10000).then(
1168 return {items : text_items, columns : visible_cols};
1172 egProgressDialog.increment();
1174 angular.forEach(visible_cols, function(col) {
1175 text_item[col.name] =
1176 grid.getItemTextContent(item, col);
1178 text_items.push(text_item);
1180 ).finally(egProgressDialog.close);
1183 // Fetch "all" of the grid data, translate it into print-friendly
1184 // text, and send it to the printer service.
1185 $scope.printHTML = function() {
1186 $scope.gridColumnPickerIsOpen = false;
1187 return grid.getAllItemsAsText().then(function(text_items) {
1188 return egCore.print.print({
1189 template : 'grid_html',
1195 $scope.showColumnDialog = function() {
1196 return $uibModal.open({
1197 templateUrl: './share/t_grid_columns',
1200 controller: ['$scope', '$uibModalInstance',
1201 function($dialogScope, $uibModalInstance) {
1202 $dialogScope.modifyColumnPos = $scope.modifyColumnPos;
1203 $dialogScope.disableMultiSort = $scope.disableMultiSort;
1204 $dialogScope.columns = $scope.columns;
1206 // Push visible columns to the top of the list
1207 $dialogScope.elevateVisible = function() {
1209 angular.forEach($dialogScope.columns, function(col) {
1210 if (col.visible) new_cols.push(col);
1212 angular.forEach($dialogScope.columns, function(col) {
1213 if (!col.visible) new_cols.push(col);
1216 // Update all references to the list of columns
1217 $dialogScope.columns =
1219 grid.columnsProvider.columns =
1223 $dialogScope.toggle = function(col) {
1224 col.visible = !Boolean(col.visible);
1226 $dialogScope.ok = $dialogScope.cancel = function() {
1227 delete $scope.lastModColumn;
1228 if (grid.columnsProvider.hasSortableColumn()) {
1229 // only refresh the grid if the user has the
1230 // ability to modify the sort priorities.
1235 $uibModalInstance.close()
1242 // generates CSV for the currently visible grid contents
1243 grid.generateCSV = function() {
1244 return grid.getAllItemsAsText().then(function(text_items) {
1245 var columns = text_items.columns;
1246 var items = text_items.items;
1250 angular.forEach(columns, function(col) {
1251 csvStr += grid.csvDatum(col.label);
1255 csvStr = csvStr.replace(/,$/,'\n');
1258 angular.forEach(items, function(item) {
1259 angular.forEach(columns, function(col) {
1260 csvStr += grid.csvDatum(item[col.name]);
1263 csvStr = csvStr.replace(/,$/,'\n');
1270 // Interpolate the value for column.linkpath within the context
1271 // of the row item to generate the final link URL.
1272 $scope.generateLinkPath = function(col, item) {
1273 return egCore.strings.$replace(col.linkpath, {item : item});
1276 // If a column provides its own HTML template, translate it,
1277 // using the current item for the template scope.
1278 // note: $sce is required to avoid security restrictions and
1279 // is OK here, since the template comes directly from a
1280 // local HTML template (not user input).
1281 $scope.translateCellTemplate = function(col, item) {
1282 var html = egCore.strings.$replace(col.template, {item : item});
1283 return $sce.trustAsHtml(html);
1286 $scope.collect = function() { grid.collect() }
1289 $scope.confirmAllowAllAndCollect = function(){
1290 egConfirmDialog.open(egStrings.CONFIRM_LONG_RUNNING_ACTION_ALL_ROWS_TITLE,
1291 egStrings.CONFIRM_LONG_RUNNING_ACTION_MSG)
1295 $scope.limit(10000);
1300 // asks the dataProvider for a page of data
1301 grid.collect = function() {
1303 // avoid firing the collect if there is nothing to collect.
1304 if (grid.selfManagedData && !grid.dataProvider.query) return;
1306 if (grid.collecting) return; // avoid parallel collect()
1307 grid.collecting = true;
1309 console.debug('egGrid.collect() offset='
1310 + grid.offset + '; limit=' + grid.limit);
1312 // ensure all of our dropdowns are closed
1313 // TODO: git rid of these and just use dropdown-toggle,
1314 // which is more reliable.
1315 $scope.gridColumnPickerIsOpen = false;
1316 $scope.gridRowCountIsOpen = false;
1317 $scope.gridPageSelectIsOpen = false;
1320 $scope.selected = {};
1322 // Inform the caller we've asked the data provider
1323 // for data. This is useful for knowing when collection
1324 // has started (e.g. to display a progress dialg) when
1325 // using the stock (flattener) data provider, where the
1326 // user is not directly defining a get() handler.
1327 if (grid.controls.collectStarted)
1328 grid.controls.collectStarted(grid.offset, grid.limit);
1330 grid.dataProvider.get(grid.offset, grid.limit).then(
1332 if (grid.controls.allItemsRetrieved)
1333 grid.controls.allItemsRetrieved();
1338 $scope.items.push(item)
1339 if (grid.controls.itemRetrieved)
1340 grid.controls.itemRetrieved(item);
1341 if ($scope.selectAll)
1342 $scope.selected[grid.indexValue(item)] = true
1344 }).finally(function() {
1345 console.debug('egGrid.collect() complete');
1346 grid.collecting = false
1347 $scope.selected = angular.copy($scope.selected);
1351 grid.prepend = function(limit) {
1352 var ran_into_duplicate = false;
1353 var sort = grid.dataProvider.sort;
1354 if (sort && sort.length) {
1355 // If sorting is in effect, we have no way
1356 // of knowing that the new item should be
1357 // visible _if the sort order is retained_.
1358 // However, since the grids that do prepending in
1359 // the first place are ones where we always
1360 // want the new row to show up on top, we'll
1361 // remove the current sort options.
1362 grid.dataProvider.sort = [];
1364 if (grid.offset > 0) {
1365 // if we're prepending, we're forcing the
1366 // offset back to zero to display the top
1372 if (grid.collecting) return; // avoid parallel collect() or prepend()
1373 grid.collecting = true;
1374 console.debug('egGrid.prepend() starting');
1375 // Note that we can count on the most-recently added
1376 // item being at offset 0 in the data provider only
1377 // for arrayNotifier data sources that do not have
1378 // sort options currently set.
1379 grid.dataProvider.get(0, 1).then(
1384 var newIdx = grid.indexValue(item);
1385 angular.forEach($scope.items, function(existing) {
1386 if (grid.indexValue(existing) == newIdx) {
1387 console.debug('egGrid.prepend(): refusing to add duplicate item ' + newIdx);
1388 ran_into_duplicate = true;
1392 $scope.items.unshift(item);
1393 if (limit && $scope.items.length > limit) {
1394 // this accommodates the checkin grid that
1395 // allows the user to set a definite limit
1396 // without requiring that entire collect()
1397 $scope.items.length = limit;
1399 if ($scope.items.length > grid.limit) {
1400 $scope.items.length = grid.limit;
1402 if (grid.controls.itemRetrieved)
1403 grid.controls.itemRetrieved(item);
1404 if ($scope.selectAll)
1405 $scope.selected[grid.indexValue(item)] = true
1407 }).finally(function() {
1408 console.debug('egGrid.prepend() complete');
1409 grid.collecting = false;
1410 $scope.selected = angular.copy($scope.selected);
1411 if (ran_into_duplicate) {
1423 * eg-grid-field : used for collecting custom field data from the templates.
1424 * This directive does not direct display, it just passes data up to the
1427 .directive('egGridField', function() {
1429 require : '^egGrid',
1432 flesher: '=', // optional; function that can flesh a linked field, given the value
1433 comparator: '=', // optional; function that can sort the thing at the end of 'path'
1434 name : '@', // required; unique name
1435 path : '@', // optional; flesh path
1436 ignore: '@', // optional; fields to ignore when path is a wildcard
1437 label : '@', // optional; display label
1438 flex : '@', // optional; default flex width
1439 align : '@', // optional; default alignment, left/center/right
1440 dateformat : '@', // optional: passed down to egGridValueFilter
1441 datecontext: '@', // optional: passed down to egGridValueFilter to choose TZ
1442 datefilter: '@', // optional: passed down to egGridValueFilter to choose specialized date filters
1443 dateonlyinterval: '@', // optional: passed down to egGridValueFilter to choose a "better" format
1445 // if a field is part of an IDL object, but we are unable to
1446 // determine the class, because it's nested within a hash
1447 // (i.e. we can't navigate directly to the object via the IDL),
1448 // idlClass lets us specify the class. This is particularly
1449 // useful for nested wildcard fields.
1450 parentIdlClass : '@',
1452 // optional: for non-IDL columns, specifying a datatype
1453 // lets the caller control which display filter is used.
1454 // datatype should match the standard IDL datatypes.
1457 // optional hash of functions that can be imported into
1458 // the directive's scope; meant for cases where the "compiled"
1462 // optional: CSS class name that we want to have for this field.
1463 // Auto generated from path if nothing is passed in via eg-grid-field declaration
1466 link : function(scope, element, attrs, egGridCtrl) {
1468 // boolean fields are presented as value-less attributes
1478 'required' // if set, always fetch data for this column
1481 if (angular.isDefined(attrs[field]))
1482 scope[field] = true;
1486 scope.cssSelector = attrs['cssSelector'] ? attrs['cssSelector'] : "";
1488 // auto-generate CSS selector name for field if none declared in tt2 and there's a path
1489 if (scope.path && !scope.cssSelector){
1490 var cssClass = 'grid' + "." + scope.path;
1491 cssClass = cssClass.replace(/\./g,'-');
1492 element.addClass(cssClass);
1493 scope.cssSelector = cssClass;
1496 // any HTML content within the field is its custom template
1497 var tmpl = element.html();
1498 if (tmpl && !tmpl.match(/^\s*$/))
1499 scope.template = tmpl
1501 egGridCtrl.columnsProvider.add(scope);
1508 * eg-grid-action : used for specifying actions which may be applied
1509 * to items within the grid.
1511 .directive('egGridAction', function() {
1513 require : '^egGrid',
1517 group : '@', // Action group, ungrouped if not set
1518 label : '@', // Action label
1519 handler : '=', // Action function handler
1521 disabled : '=', // function
1524 link : function(scope, element, attrs, egGridCtrl) {
1525 egGridCtrl.addAction({
1527 group : scope.group,
1528 label : scope.label,
1529 divider : scope.divider,
1530 handler : scope.handler,
1531 disabled : scope.disabled,
1538 .factory('egGridColumnsProvider', ['egCore', function(egCore) {
1540 function ColumnsProvider(args) {
1543 cols.stockVisible = [];
1544 cols.idlClass = args.idlClass;
1545 cols.clientSort = args.clientSort;
1546 cols.defaultToHidden = args.defaultToHidden;
1547 cols.defaultToNoSort = args.defaultToNoSort;
1548 cols.defaultToNoMultiSort = args.defaultToNoMultiSort;
1549 cols.defaultDateFormat = args.defaultDateFormat;
1550 cols.defaultDateContext = args.defaultDateContext;
1552 // resets column width, visibility, and sort behavior
1553 // Visibility resets to the visibility settings defined in the
1554 // template (i.e. the original egGridField values).
1555 cols.reset = function() {
1556 angular.forEach(cols.columns, function(col) {
1560 if (cols.stockVisible.indexOf(col.name) > -1) {
1563 col.visible = false;
1568 // returns true if any columns are sortable
1569 cols.hasSortableColumn = function() {
1570 return cols.columns.filter(
1572 return col.sortable || col.multisortable;
1577 cols.showAllColumns = function() {
1578 angular.forEach(cols.columns, function(column) {
1579 column.visible = true;
1583 cols.hideAllColumns = function() {
1584 angular.forEach(cols.columns, function(col) {
1589 cols.indexOf = function(name) {
1590 for (var i = 0; i < cols.columns.length; i++) {
1591 if (cols.columns[i].name == name)
1597 cols.findColumn = function(name) {
1598 return cols.columns[cols.indexOf(name)];
1601 cols.compileAutoColumns = function() {
1602 var idl_class = egCore.idl.classes[cols.idlClass];
1607 if (field.virtual) return;
1608 // Columns declared in the markup take precedence
1609 // of matching auto-columns.
1610 if (cols.findColumn(field.name)) return;
1611 if (field.datatype == 'link' || field.datatype == 'org_unit') {
1612 // if the field is a link and the linked class has a
1613 // "selector" field specified, use the selector field
1614 // as the display field for the columns.
1615 // flattener will take care of the fleshing.
1616 if (field['class']) {
1617 var selector_field = egCore.idl.classes[field['class']].fields
1618 .filter(function(f) { return Boolean(f.selector) })[0];
1619 if (selector_field) {
1620 field.path = field.name + '.' + selector_field.selector;
1624 cols.add(field, true);
1629 // if a column definition has a path with a wildcard, create
1630 // columns for all non-virtual fields at the specified
1631 // position in the path.
1632 cols.expandPath = function(colSpec) {
1634 var ignoreList = [];
1636 ignoreList = colSpec.ignore.split(' ');
1638 var dotpath = colSpec.path.replace(/\.?\*$/,'');
1642 if (colSpec.parentIdlClass) {
1643 class_obj = egCore.idl.classes[colSpec.parentIdlClass];
1645 class_obj = egCore.idl.classes[cols.idlClass];
1647 var idl_parent = class_obj;
1648 var old_field_label = '';
1650 if (!class_obj) return;
1652 //console.debug('egGrid: auto dotpath is: ' + dotpath);
1653 var path_parts = dotpath.split(/\./);
1655 // find the IDL class definition for the last element in the
1656 // path before the .*
1657 // an empty path_parts means expand the root class
1660 for (var path_idx in path_parts) {
1661 old_field = idl_field;
1663 var part = path_parts[path_idx];
1664 idl_field = class_obj.field_map[part];
1666 // unless we're at the end of the list, this field should
1667 // link to another class.
1668 if (idl_field && idl_field['class'] && (
1669 idl_field.datatype == 'link' ||
1670 idl_field.datatype == 'org_unit')) {
1671 if (old_field_label) old_field_label += ' : ';
1672 old_field_label += idl_field.label;
1673 class_obj = egCore.idl.classes[idl_field['class']];
1674 if (old_field) idl_parent = old_field;
1676 if (path_idx < (path_parts.length - 1)) {
1677 // we ran out of classes to hop through before
1678 // we ran out of path components
1679 console.error("egGrid: invalid IDL path: " + dotpath);
1686 angular.forEach(class_obj.fields, function(field) {
1688 // Only show wildcard fields where we have data to show
1689 // Virtual and un-fleshed links will not have any data.
1690 if (field.virtual ||
1691 (field.datatype == 'link' || field.datatype == 'org_unit') ||
1692 ignoreList.indexOf(field.name) > -1
1696 var col = cols.cloneFromScope(colSpec);
1697 col.path = (dotpath ? dotpath + '.' + field.name : field.name);
1699 // log line below is very chatty. disable until needed.
1700 // console.debug('egGrid: field: ' +field.name + '; parent field: ' + js2JSON(idl_parent));
1701 cols.add(col, false, true,
1702 {idl_parent : idl_parent, idl_field : field, idl_class : class_obj, field_parent_label : old_field_label });
1705 cols.columns = cols.columns.sort(
1707 if (a.explicit) return -1;
1708 if (b.explicit) return 1;
1710 if (a.idlclass && b.idlclass) {
1711 if (a.idlclass < b.idlclass) return -1;
1712 if (b.idlclass < a.idlclass) return 1;
1715 if (a.path && b.path && a.path.lastIndexOf('.') && b.path.lastIndexOf('.')) {
1716 if (a.path.substring(0, a.path.lastIndexOf('.')) < b.path.substring(0, b.path.lastIndexOf('.'))) return -1;
1717 if (b.path.substring(0, b.path.lastIndexOf('.')) < a.path.substring(0, a.path.lastIndexOf('.'))) return 1;
1720 if (a.label && b.label) {
1721 if (a.label < b.label) return -1;
1722 if (b.label < a.label) return 1;
1725 return a.name < b.name ? -1 : 1;
1732 "egGrid: wildcard path does not resolve to an object: "
1737 // angular.clone(scopeObject) is not permittable. Manually copy
1738 // the fields over that we need (so the scope object can go away).
1739 cols.cloneFromScope = function(colSpec) {
1741 flesher : colSpec.flesher,
1742 comparator : colSpec.comparator,
1743 name : colSpec.name,
1744 label : colSpec.label,
1745 path : colSpec.path,
1746 align : colSpec.align || 'left',
1747 flex : Number(colSpec.flex) || 2,
1748 sort : Number(colSpec.sort) || 0,
1749 required : colSpec.required,
1750 linkpath : colSpec.linkpath,
1751 template : colSpec.template,
1752 visible : colSpec.visible,
1753 compiled : colSpec.compiled,
1754 handlers : colSpec.handlers,
1755 hidden : colSpec.hidden,
1756 datatype : colSpec.datatype,
1757 sortable : colSpec.sortable,
1758 nonsortable : colSpec.nonsortable,
1759 multisortable : colSpec.multisortable,
1760 nonmultisortable : colSpec.nonmultisortable,
1761 dateformat : colSpec.dateformat,
1762 datecontext : colSpec.datecontext,
1763 datefilter : colSpec.datefilter,
1764 dateonlyinterval : colSpec.dateonlyinterval,
1765 parentIdlClass : colSpec.parentIdlClass,
1766 cssSelector : colSpec.cssSelector
1771 // Add a column to the columns collection.
1772 // Columns may come from a slim eg-columns-field or
1773 // directly from the IDL.
1774 cols.add = function(colSpec, fromIDL, fromExpand, idl_info) {
1776 // First added column with the specified path takes precedence.
1777 // This allows for specific definitions followed by wildcard
1778 // definitions. If a match is found, back out.
1779 if (cols.columns.filter(function(c) {
1780 return (c.path == colSpec.path) })[0]) {
1781 console.debug('skipping pre-existing column ' + colSpec.path);
1785 var column = fromExpand ? colSpec : cols.cloneFromScope(colSpec);
1787 if (column.path && column.path.match(/\*$/))
1788 return cols.expandPath(colSpec);
1790 if (!fromExpand) column.explicit = true;
1792 if (!column.name) column.name = column.path;
1793 if (!column.path) column.path = column.name;
1795 if (column.visible || (!cols.defaultToHidden && !column.hidden))
1796 column.visible = true;
1798 if (column.sortable || (!cols.defaultToNoSort && !column.nonsortable))
1799 column.sortable = true;
1801 if (column.multisortable ||
1802 (!cols.defaultToNoMultiSort && !column.nonmultisortable))
1803 column.multisortable = true;
1805 if (cols.defaultDateFormat && ! column.dateformat) {
1806 column.dateformat = cols.defaultDateFormat;
1809 if (cols.defaultDateOnlyInterval && ! column.dateonlyinterval) {
1810 column.dateonlyinterval = cols.defaultDateOnlyInterval;
1813 if (cols.defaultDateContext && ! column.datecontext) {
1814 column.datecontext = cols.defaultDateContext;
1817 if (cols.defaultDateFilter && ! column.datefilter) {
1818 column.datefilter = cols.defaultDateFilter;
1821 cols.columns.push(column);
1823 // Track which columns are visible by default in case we
1824 // need to reset column visibility
1826 cols.stockVisible.push(column.name);
1828 if (fromIDL) return; // directly from egIDL. nothing left to do.
1830 // lookup the matching IDL field
1831 if (!idl_info && cols.idlClass)
1832 idl_info = cols.idlFieldFromPath(column.path);
1835 // column is not represented within the IDL
1836 column.adhoc = true;
1840 column.datatype = idl_info.idl_field.datatype;
1842 if (!column.label) {
1843 column.label = idl_info.idl_field.label || column.name;
1846 if (fromExpand && idl_info.idl_class) {
1847 column.idlclass = '';
1848 if (idl_info.field_parent_label && idl_info.idl_parent.label != idl_info.idl_class.label) {
1849 column.idlclass = (idl_info.field_parent_label || idl_info.idl_parent.label || idl_info.idl_parent.name);
1851 column.idlclass += idl_info.idl_class.label || idl_info.idl_class.name;
1856 // finds the IDL field from the dotpath, using the columns
1857 // idlClass as the base.
1858 cols.idlFieldFromPath = function(dotpath) {
1859 var class_obj = egCore.idl.classes[cols.idlClass];
1860 if (!dotpath) return null;
1862 var path_parts = dotpath.split(/\./);
1866 for (var path_idx in path_parts) {
1867 var part = path_parts[path_idx];
1868 idl_parent = idl_field;
1869 idl_field = class_obj.field_map[part];
1872 if (idl_field['class'] && (
1873 idl_field.datatype == 'link' ||
1874 idl_field.datatype == 'org_unit')) {
1875 class_obj = egCore.idl.classes[idl_field['class']];
1883 idl_parent: idl_parent,
1884 idl_field : idl_field,
1885 idl_class : class_obj
1891 instance : function(args) { return new ColumnsProvider(args) }
1897 * Generic data provider template class. This is basically an abstract
1898 * class factory service whose instances can be locally modified to
1899 * meet the needs of each individual grid.
1901 .factory('egGridDataProvider',
1902 ['$q','$timeout','$filter','egCore',
1903 function($q , $timeout , $filter , egCore) {
1905 function GridDataProvider(args) {
1906 var gridData = this;
1907 if (!args) args = {};
1910 gridData.get = args.get;
1911 gridData.query = args.query;
1912 gridData.idlClass = args.idlClass;
1913 gridData.columnsProvider = args.columnsProvider;
1915 // Delivers a stream of array data via promise.notify()
1916 // Useful for passing an array of data to egGrid.get()
1917 // If a count is provided, the array will be trimmed to
1918 // the range defined by count and offset
1919 gridData.arrayNotifier = function(arr, offset, count) {
1920 if (!arr || arr.length == 0) return $q.when();
1922 if (gridData.columnsProvider.clientSort
1924 && gridData.sort.length > 0
1926 var sorter_cache = [];
1927 arr.sort(function(a,b) {
1928 for (var si = 0; si < gridData.sort.length; si++) {
1929 if (!sorter_cache[si]) { // Build sort structure on first comparison, reuse thereafter
1930 var field = gridData.sort[si];
1933 if (angular.isObject(field)) {
1934 dir = Object.values(field)[0];
1935 field = Object.keys(field)[0];
1938 var path = gridData.columnsProvider.findColumn(field).path || field;
1939 var comparator = gridData.columnsProvider.findColumn(field).comparator ||
1940 function (x,y) { if (x < y) return -1; if (x > y) return 1; return 0 };
1942 sorter_cache[si] = {
1945 comparator : comparator
1949 var sc = sorter_cache[si];
1953 if (a._isfieldmapper || angular.isFunction(a[sc.field])) {
1954 try {af = a[sc.field](); bf = b[sc.field]() } catch (e) {};
1956 af = a[sc.field]; bf = b[sc.field];
1958 if (af === undefined && sc.field.indexOf('.') > -1) { // assume an object, not flat path
1959 var parts = sc.field.split('.');
1962 angular.forEach(parts, function (p) {
1964 if (af._isfieldmapper || angular.isFunction(af[p])) af = af[p]();
1968 if (bf._isfieldmapper || angular.isFunction(bf[p])) bf = bf[p]();
1974 if (af === undefined) af = null;
1975 if (bf === undefined) bf = null;
1977 if (af === null && bf !== null) return 1;
1978 if (bf === null && af !== null) return -1;
1980 if (!(bf === null && af === null)) {
1981 var partial = sc.comparator(af,bf);
1983 if (sc.dir == 'desc') {
1984 if (partial > 0) return -1;
1996 if (count) arr = arr.slice(offset, offset + count);
1997 var def = $q.defer();
1998 // promise notifications are only witnessed when delivered
1999 // after the caller has his hands on the promise object
2000 $timeout(function() {
2001 angular.forEach(arr, def.notify);
2007 // Calls the grid refresh function. Once instantiated, the
2008 // grid will replace this function with it's own refresh()
2009 gridData.refresh = function(noReset) { }
2010 gridData.prepend = function(limit) { }
2012 if (!gridData.get) {
2013 // returns a promise whose notify() delivers items
2014 gridData.get = function(index, count) {
2015 console.error("egGridDataProvider.get() not implemented");
2019 // attempts a flat field lookup first. If the column is not
2020 // found on the top-level object, attempts a nested lookup
2021 // TODO: consider a caching layer to speed up template
2022 // rendering, particularly for nested objects?
2023 gridData.itemFieldValue = function(item, column) {
2025 if (column.name in item) {
2026 if (typeof item[column.name] == 'function') {
2027 val = item[column.name]();
2029 val = item[column.name];
2032 val = gridData.nestedItemFieldValue(item, column);
2038 // TODO: deprecate me
2039 gridData.flatItemFieldValue = function(item, column) {
2040 console.warn('gridData.flatItemFieldValue deprecated; '
2041 + 'leave provider.itemFieldValue unset');
2042 return item[column.name];
2045 // given an object and a dot-separated path to a field,
2046 // extract the value of the field. The path can refer
2047 // to function names or object attributes. If the final
2048 // value is an IDL field, run the value through its
2049 // corresponding output filter.
2050 gridData.nestedItemFieldValue = function(obj, column) {
2051 item = obj; // keep a copy around
2053 if (obj === null || obj === undefined || obj === '') return '';
2054 if (!column.path) return obj;
2057 var parts = column.path.split('.');
2059 angular.forEach(parts, function(step, idx) {
2060 // object is not fleshed to the expected extent
2061 if (typeof obj != 'object') {
2062 if (typeof obj != 'undefined' && column.flesher) {
2063 obj = column.flesher(obj, column, item);
2070 if (!obj) return '';
2072 var cls = obj.classname;
2073 if (cls && (class_obj = egCore.idl.classes[cls])) {
2074 idl_field = class_obj.field_map[step];
2075 obj = obj[step] ? obj[step]() : '';
2077 if (angular.isFunction(obj[step])) {
2085 // We found a nested IDL object which may or may not have
2086 // been configured as a top-level column. Grab the datatype.
2087 if (idl_field && !column.datatype)
2088 column.datatype = idl_field.datatype;
2090 if (obj === null || obj === undefined || obj === '') return '';
2096 instance : function(args) {
2097 return new GridDataProvider(args);
2104 // Factory service for egGridDataManager instances, which are
2105 // responsible for collecting flattened grid data.
2106 .factory('egGridFlatDataProvider',
2107 ['$q','egCore','egGridDataProvider',
2108 function($q , egCore , egGridDataProvider) {
2111 instance : function(args) {
2112 var provider = egGridDataProvider.instance(args);
2114 provider.get = function(offset, count) {
2116 // no query means no call
2117 if (!provider.query ||
2118 angular.equals(provider.query, {}))
2121 // find all of the currently visible columns
2122 var queryFields = {}
2123 angular.forEach(provider.columnsProvider.columns,
2125 // only query IDL-tracked columns
2126 if (!col.adhoc && col.name && col.path && (col.required || col.visible))
2127 queryFields[col.name] = col.path;
2131 return egCore.net.request(
2133 'open-ils.fielder.flattened_search',
2134 egCore.auth.token(), provider.idlClass,
2135 queryFields, provider.query,
2136 { sort : provider.sort,
2142 //provider.itemFieldValue = provider.flatItemFieldValue;
2149 .directive('egGridColumnDragSource', function() {
2152 require : '^egGrid',
2153 link : function(scope, element, attrs, egGridCtrl) {
2154 angular.element(element).attr('draggable', 'true');
2156 element.bind('dragstart', function(e) {
2157 egGridCtrl.dragColumn = attrs.column;
2158 egGridCtrl.dragType = attrs.dragType || 'move'; // or resize
2159 egGridCtrl.colResizeDir = 0;
2161 if (egGridCtrl.dragType == 'move') {
2162 // style the column getting moved
2163 angular.element(e.target).addClass(
2164 'eg-grid-column-move-handle-active');
2168 element.bind('dragend', function(e) {
2169 if (egGridCtrl.dragType == 'move') {
2170 angular.element(e.target).removeClass(
2171 'eg-grid-column-move-handle-active');
2178 .directive('egGridColumnDragDest', function() {
2181 require : '^egGrid',
2182 link : function(scope, element, attrs, egGridCtrl) {
2184 element.bind('dragover', function(e) { // required for drop
2185 e.stopPropagation();
2187 e.dataTransfer.dropEffect = 'move';
2189 if (egGridCtrl.colResizeDir == 0) return; // move
2191 var cols = egGridCtrl.columnsProvider;
2192 var srcCol = egGridCtrl.dragColumn;
2193 var srcColIdx = cols.indexOf(srcCol);
2195 if (egGridCtrl.colResizeDir == -1) {
2196 if (cols.indexOf(attrs.column) <= srcColIdx) {
2197 egGridCtrl.modifyColumnFlex(
2198 egGridCtrl.columnsProvider.findColumn(
2199 egGridCtrl.dragColumn), -1);
2200 if (cols.columns[srcColIdx+1]) {
2201 // source column shrinks by one, column to the
2202 // right grows by one.
2203 egGridCtrl.modifyColumnFlex(
2204 cols.columns[srcColIdx+1], 1);
2209 if (cols.indexOf(attrs.column) > srcColIdx) {
2210 egGridCtrl.modifyColumnFlex(
2211 egGridCtrl.columnsProvider.findColumn(
2212 egGridCtrl.dragColumn), 1);
2213 if (cols.columns[srcColIdx+1]) {
2214 // source column grows by one, column to the
2215 // right grows by one.
2216 egGridCtrl.modifyColumnFlex(
2217 cols.columns[srcColIdx+1], -1);
2225 element.bind('dragenter', function(e) {
2226 e.stopPropagation();
2228 if (egGridCtrl.dragType == 'move') {
2229 angular.element(e.target).addClass('eg-grid-col-hover');
2231 // resize grips are on the right side of each column.
2232 // dragenter will either occur on the source column
2233 // (dragging left) or the column to the right.
2234 if (egGridCtrl.colResizeDir == 0) {
2235 if (egGridCtrl.dragColumn == attrs.column) {
2236 egGridCtrl.colResizeDir = -1; // west
2238 egGridCtrl.colResizeDir = 1; // east
2244 element.bind('dragleave', function(e) {
2245 e.stopPropagation();
2247 if (egGridCtrl.dragType == 'move') {
2248 angular.element(e.target).removeClass('eg-grid-col-hover');
2252 element.bind('drop', function(e) {
2253 e.stopPropagation();
2255 egGridCtrl.colResizeDir = 0;
2256 if (egGridCtrl.dragType == 'move') {
2257 angular.element(e.target).removeClass('eg-grid-col-hover');
2258 egGridCtrl.onColumnDrop(attrs.column); // move the column
2265 .directive('egGridMenuItem', function() {
2268 require : '^egGrid',
2274 handler : '=', // onclick handler function
2275 divider : '=', // if true, show a divider only
2276 handlerData : '=', // if set, passed as second argument to handler
2277 disabled : '=', // function
2278 hidden : '=' // function
2280 link : function(scope, element, attrs, egGridCtrl) {
2281 egGridCtrl.addMenuItem({
2282 checkbox : scope.checkbox,
2283 checked : scope.checked ? true : false,
2284 label : scope.label,
2285 standalone : scope.standalone ? true : false,
2286 handler : scope.handler,
2287 divider : scope.divider,
2288 disabled : scope.disabled,
2289 hidden : scope.hidden,
2290 handlerData : scope.handlerData
2297 /* https://stackoverflow.com/questions/17343696/adding-an-ng-click-event-inside-a-filter/17344875#17344875 */
2298 .directive('compile', ['$compile', function ($compile) {
2299 return function(scope, element, attrs) {
2300 // pass through column defs from grid cell's scope
2301 scope.col = scope.$parent.col;
2304 // watch the 'compile' expression for changes
2305 return scope.$eval(attrs.compile);
2308 // when the 'compile' expression changes
2309 // assign it into the current DOM
2310 element.html(value);
2312 // compile the new DOM and link it to the current
2314 // NOTE: we only compile .childNodes so that
2315 // we don't get into infinite loop compiling ourselves
2316 $compile(element.contents())(scope);
2325 * Translates bare IDL object values into display values.
2326 * 1. Passes dates through the angular date filter
2327 * 2. Converts bools to translated Yes/No strings
2328 * Others likely to follow...
2330 .filter('egGridValueFilter', ['$filter','egCore', 'egStrings', function($filter,egCore,egStrings) {
2331 function traversePath(obj,path) {
2332 var list = path.split('.');
2333 for (var part in path) {
2334 if (obj[path]) obj = obj[path]
2340 var GVF = function(value, column, item) {
2341 switch(column.datatype) {
2345 case '1' : // legacy
2347 return egStrings.YES;
2349 case '0' : // legacy
2351 return egStrings.NO;
2352 // value may be null, '', etc.
2353 default : return '';
2356 var interval = angular.isFunction(item[column.dateonlyinterval])
2357 ? item[column.dateonlyinterval]()
2358 : item[column.dateonlyinterval];
2360 if (column.dateonlyinterval && !interval) // try it as a dotted path
2361 interval = traversePath(item, column.dateonlyinterval);
2363 var context = angular.isFunction(item[column.datecontext])
2364 ? item[column.datecontext]()
2365 : item[column.datecontext];
2367 if (column.datecontext && !context) // try it as a dotted path
2368 context = traversePath(item, column.datecontext);
2370 var date_filter = column.datefilter || 'egOrgDateInContext';
2372 return $filter(date_filter)(value, column.dateformat, context, interval);
2374 return $filter('currency')(value);
2380 GVF.$stateful = true;