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 primary grid label
60 // if true, use the IDL class label as the mainLabel
63 // optional context menu label
66 dateformat : '@', // optional: passed down to egGridValueFilter
67 datecontext: '@', // optional: passed down to egGridValueFilter to choose TZ
68 datefilter: '@', // optional: passed down to egGridValueFilter to choose specialized date filters
69 dateonlyinterval: '@', // optional: passed down to egGridValueFilter to choose a "better" format
71 // Hash of control functions.
73 // These functions are defined by the calling scope and
74 // invoked as-is by the grid w/ the specified parameters.
76 // collectStarted : function() {}
77 // itemRetrieved : function(item) {}
78 // allItemsRetrieved : function() {}
81 // If defined, the grid will watch the return value from
82 // the function defined at watchQuery on each digest and
83 // re-draw the grid when query changes occur.
85 // watchQuery : function() { /* return grid query */ }
88 // These functions are defined by the grid and thus
89 // replace any values defined for these attributes from the
92 // activateItem : function(item) {}
93 // allItems : function(allItems) {}
94 // selectedItems : function(selected) {}
95 // selectItems : function(ids) {}
96 // setQuery : function(queryStruct) {} // causes reload
97 // setSort : function(sortSturct) {} // causes reload
101 // TODO: avoid hard-coded url
102 templateUrl : '/eg/staff/share/t_autogrid',
104 link : function(scope, element, attrs) {
105 // link() is called after page compilation, which means our
106 // eg-grid-field's have been parsed and loaded. Now it's
107 // safe to perform our initial page load.
109 // load auto fields after eg-grid-field's so they are not clobbered
110 scope.handleAutoFields();
113 scope.grid_element = element;
115 .find('.eg-grid-content-body')
116 .bind('contextmenu', scope.showActionContextMenu);
120 '$scope','$q','egCore','egGridFlatDataProvider','$location',
121 'egGridColumnsProvider','$filter','$window','$sce','$timeout',
123 function($scope, $q , egCore, egGridFlatDataProvider , $location,
124 egGridColumnsProvider , $filter , $window , $sce , $timeout,
129 grid.init = function() {
132 $scope.showGridConf = false;
133 grid.totalCount = -1;
134 $scope.selected = {};
135 $scope.actionGroups = [{actions:[]}]; // Grouped actions for selected items
136 $scope.menuItems = []; // global actions
138 // returns true if any rows are selected.
139 $scope.hasSelected = function() {
140 return grid.getSelectedItems().length > 0 };
142 var features = ($scope.features) ?
143 $scope.features.split(',') : [];
144 delete $scope.features;
146 $scope.showIndex = (features.indexOf('-index') == -1);
148 $scope.allowAll = (features.indexOf('allowAll') > -1);
149 $scope.startSelected = $scope.selectAll = (features.indexOf('startSelected') > -1);
150 $scope.showActions = (features.indexOf('-actions') == -1);
151 $scope.showPagination = (features.indexOf('-pagination') == -1);
152 $scope.showPicker = (features.indexOf('-picker') == -1);
154 $scope.showMenu = (features.indexOf('-menu') == -1);
156 // remove some unneeded values from the scope to reduce bloat
158 grid.idlClass = $scope.idlClass;
159 delete $scope.idlClass;
161 grid.persistKey = $scope.persistKey;
162 delete $scope.persistKey;
164 var stored_limit = 0;
165 if ($scope.showPagination) {
166 if (grid.persistKey) {
167 var stored_limit = Number(
168 egCore.hatch.getLocalItem('eg.grid.' + grid.persistKey + '.limit')
172 stored_limit = 10000; // maybe support "Inf"?
175 grid.limit = Number(stored_limit) || Number($scope.pageSize) || 25;
177 grid.indexField = $scope.idField;
178 delete $scope.idField;
180 grid.dataProvider = $scope.itemsProvider;
182 if (!grid.indexField && grid.idlClass)
183 grid.indexField = egCore.idl.classes[grid.idlClass].pkey;
185 grid.columnsProvider = egGridColumnsProvider.instance({
186 idlClass : grid.idlClass,
187 clientSort : (features.indexOf('clientsort') > -1 && features.indexOf('-clientsort') == -1),
188 defaultToHidden : (features.indexOf('-display') > -1),
189 defaultToNoSort : (features.indexOf('-sort') > -1),
190 defaultToNoMultiSort : (features.indexOf('-multisort') > -1),
191 defaultDateFormat : $scope.dateformat,
192 defaultDateContext : $scope.datecontext,
193 defaultDateFilter : $scope.datefilter,
194 defaultDateOnlyInterval : $scope.dateonlyinterval
196 $scope.canMultiSelect = (features.indexOf('-multiselect') == -1);
198 $scope.handleAutoFields = function() {
199 if ($scope.autoFields) {
200 if (grid.autoLabel) {
202 egCore.idl.classes[grid.idlClass].label;
204 grid.columnsProvider.compileAutoColumns();
205 delete $scope.autoFields;
209 if (!grid.dataProvider) {
210 // no provider, um, provided.
211 // Use a flat data provider
213 grid.selfManagedData = true;
214 grid.dataProvider = egGridFlatDataProvider.instance({
215 indexField : grid.indexField,
216 idlClass : grid.idlClass,
217 columnsProvider : grid.columnsProvider,
222 // make grid ref available in get() to set totalCount, if known.
223 // this allows us disable the 'next' paging button correctly
224 grid.dataProvider.grid = grid;
226 grid.dataProvider.columnsProvider = grid.columnsProvider;
228 $scope.itemFieldValue = grid.dataProvider.itemFieldValue;
229 $scope.indexValue = function(item) {
230 return grid.indexValue(item)
233 grid.applyControlFunctions();
235 grid.loadConfig().then(function() {
236 // link columns to scope after loadConfig(), since it
237 // replaces the columns array.
238 $scope.columns = grid.columnsProvider.columns;
241 // NOTE: grid.collect() is first called from link(), not here.
244 // link our control functions into the gridControls
245 // scope object so the caller can access them.
246 grid.applyControlFunctions = function() {
248 // we use some of these controls internally, so sett
249 // them up even if the caller doesn't request them.
250 var controls = $scope.gridControls || {};
252 controls.columnMap = function() {
254 angular.forEach(grid.columnsProvider.columns, function (c) {
260 controls.columnsProvider = function() {
261 return grid.columnsProvider;
264 // link in the control functions
265 controls.selectedItems = function() {
266 return grid.getSelectedItems()
269 controls.selectItemsByValue = function(c,v) {
270 return grid.selectItemsByValue(c,v)
273 controls.allItems = function() {
277 controls.selectItems = function(ids) {
279 $scope.selected = {};
280 angular.forEach(ids, function(i) {
281 $scope.selected[''+i] = true;
285 // if the caller provided a functional setQuery,
286 // extract the value before replacing it
287 if (controls.setQuery) {
288 grid.dataProvider.query =
292 controls.setQuery = function(query) {
293 grid.dataProvider.query = query;
297 if (controls.watchQuery) {
298 // capture the initial query value
299 grid.dataProvider.query = controls.watchQuery();
302 $scope.gridWatchQuery = controls.watchQuery;
303 $scope.$watch('gridWatchQuery()', function(newv) {
304 controls.setQuery(newv);
308 // if the caller provided a functional setSort
309 // extract the value before replacing it
310 grid.dataProvider.sort =
311 controls.setSort ? controls.setSort() : [];
313 controls.setSort = function(sort) {
317 controls.refresh = function(noReset) {
318 if (!noReset) grid.offset = 0;
322 controls.setLimit = function(limit,forget) {
323 if (!forget && grid.persistKey)
324 egCore.hatch.setLocalItem('eg.grid.' + grid.persistKey + '.limit', limit);
327 controls.getLimit = function() {
330 controls.setOffset = function(offset) {
331 grid.offset = offset;
333 controls.getOffset = function() {
337 controls.saveConfig = function () {
338 return $scope.saveConfig();
341 grid.dataProvider.refresh = controls.refresh;
342 grid.controls = controls;
345 // If a menu item provides its own HTML template, translate it,
346 // using the menu item for the template scope.
347 // note: $sce is required to avoid security restrictions and
348 // is OK here, since the template comes directly from a
349 // local HTML template (not user input).
350 $scope.translateMenuItemTemplate = function(item) {
351 var html = egCore.strings.$replace(item.template, {item : item});
352 return $sce.trustAsHtml(html);
355 // add a new (global) grid menu item
356 grid.addMenuItem = function(item) {
357 $scope.menuItems.push(item);
358 var handler = item.handler;
359 item.handler = function() {
360 $scope.gridMenuIsOpen = false; // close menu
363 item.handlerData, grid.getSelectedItems());
368 // add a selected-items action
369 grid.addAction = function(act) {
371 $scope.actionGroups.forEach(function(g){
372 if (g.label === act.group) {
378 $scope.actionGroups.push({
385 // remove the stored column configuration preferenc, then recover
386 // the column visibility information from the initial page load.
387 $scope.resetColumns = function() {
388 $scope.gridColumnPickerIsOpen = false;
389 egCore.hatch.removeItem('eg.grid.' + grid.persistKey)
391 grid.columnsProvider.reset();
392 if (grid.selfManagedData) grid.collect();
396 $scope.showAllColumns = function() {
397 $scope.gridColumnPickerIsOpen = false;
398 grid.columnsProvider.showAllColumns();
399 if (grid.selfManagedData) grid.collect();
402 $scope.hideAllColumns = function() {
403 $scope.gridColumnPickerIsOpen = false;
404 grid.columnsProvider.hideAllColumns();
405 // note: no need to fetch new data if no columns are visible
408 $scope.toggleColumnVisibility = function(col) {
409 $scope.gridColumnPickerIsOpen = false;
410 col.visible = !col.visible;
412 // egGridFlatDataProvider only retrieves data to be
413 // displayed. When column visibility changes, it's
414 // necessary to fetch the newly visible column data.
415 if (grid.selfManagedData) grid.collect();
418 // save the columns configuration (position, sort, width) to
419 // eg.grid.<persist-key>
420 $scope.saveConfig = function() {
421 $scope.gridColumnPickerIsOpen = false;
423 if (!grid.persistKey) {
425 "Cannot save settings without a grid persist-key");
429 // only store information about visible columns.
430 var conf = grid.columnsProvider.columns.filter(
431 function(col) {return Boolean(col.visible) });
433 // now scrunch the data down to just the needed info
434 conf = conf.map(function(col) {
435 var c = {name : col.name}
436 // Apart from the name, only store non-default values.
437 // No need to store col.visible, since that's implicit
438 if (col.align != 'left') c.align = col.align;
439 if (col.flex != 2) c.flex = col.flex;
440 if (Number(col.sort)) c.sort = Number(c.sort);
444 egCore.hatch.setItem('eg.grid.' + grid.persistKey, conf)
446 // Save operation performed from the grid configuration UI.
447 // Hide the configuration UI and re-draw w/ sort applied
448 if ($scope.showGridConf)
449 $scope.toggleConfDisplay();
454 // load the columns configuration (position, sort, width) from
455 // eg.grid.<persist-key> and apply the loaded settings to the
456 // columns on our columnsProvider
457 grid.loadConfig = function() {
458 if (!grid.persistKey) return $q.when();
460 return egCore.hatch.getItem('eg.grid.' + grid.persistKey)
461 .then(function(conf) {
464 var columns = grid.columnsProvider.columns;
467 angular.forEach(conf, function(col) {
468 var grid_col = columns.filter(
469 function(c) {return c.name == col.name})[0];
472 // saved column does not match a column in the
473 // current grid. skip it.
477 grid_col.align = col.align || 'left';
478 grid_col.flex = col.flex || 2;
479 grid_col.sort = col.sort || 0;
480 // all saved columns are assumed to be true
481 grid_col.visible = true;
483 .filter(function (c) {
484 return c.name == grid_col.name;
487 new_cols.push(grid_col);
490 // columns which are not expressed within the saved
491 // configuration are marked as non-visible and
492 // appended to the end of the new list of columns.
493 angular.forEach(columns, function(col) {
494 var found = conf.filter(
495 function(c) {return (c.name == col.name)})[0];
502 grid.columnsProvider.columns = new_cols;
508 $scope.onContextMenu = function($event) {
509 var col = angular.element($event.target).attr('column');
510 console.log('selected column ' + col);
513 $scope.page = function() {
514 return (grid.offset / grid.limit) + 1;
517 $scope.goToPage = function(page) {
519 if (angular.isNumber(page) && page > 0) {
520 grid.offset = (page - 1) * grid.limit;
525 $scope.offset = function(o) {
526 if (angular.isNumber(o))
531 $scope.limit = function(l) {
532 if (angular.isNumber(l)) {
534 egCore.hatch.setLocalItem('eg.grid.' + grid.persistKey + '.limit', l);
540 $scope.onFirstPage = function() {
541 return grid.offset == 0;
544 $scope.hasNextPage = function() {
545 // we have less data than requested, there must
546 // not be any more pages
547 if (grid.count() < grid.limit) return false;
549 // if the total count is not known, assume that a full
550 // page of data implies more pages are available.
551 if (grid.totalCount == -1) return true;
553 // we have a full page of data, but is there more?
554 return grid.totalCount > (grid.offset + grid.count());
557 $scope.incrementPage = function() {
558 grid.offset += grid.limit;
562 $scope.decrementPage = function() {
563 if (grid.offset < grid.limit) {
566 grid.offset -= grid.limit;
571 // number of items loaded for the current page of results
572 grid.count = function() {
573 return $scope.items.length;
576 // returns the unique identifier value for the provided item
577 // for internal consistency, indexValue is always coerced
579 grid.indexValue = function(item) {
580 if (angular.isObject(item)) {
582 if (angular.isFunction(item[grid.indexField]))
583 return ''+item[grid.indexField]();
584 return ''+item[grid.indexField]; // flat data
587 // passed a non-object; assume it's an index
591 // fires the hide handler function for a context action
592 $scope.actionHide = function(action) {
593 if (typeof action.hide == 'undefined') {
596 if (angular.isFunction(action.hide))
597 return action.hide(action);
601 // fires the disable handler function for a context action
602 $scope.actionDisable = function(action) {
603 if (typeof action.disabled == 'undefined') {
606 if (angular.isFunction(action.disabled))
607 return action.disabled(action);
608 return action.disabled;
611 // fires the action handler function for a context action
612 $scope.actionLauncher = function(action) {
613 if (!action.handler) {
615 'No handler specified for "' + action.label + '"');
619 action.handler(grid.getSelectedItems());
621 console.error('Error executing handler for "'
622 + action.label + '" => ' + E + "\n" + E.stack);
625 if ($scope.action_context_showing) $scope.hideActionContextMenu();
630 $scope.hideActionContextMenu = function () {
631 $($scope.menu_dom).css({
633 width: $scope.action_context_width,
634 top: $scope.action_context_y,
635 left: $scope.action_context_x
637 $($scope.action_context_parent).append($scope.menu_dom);
638 $scope.action_context_oldy = $scope.action_context_oldx = 0;
639 $('body').unbind('click.remove_context_menu_'+$scope.action_context_index);
640 $scope.action_context_showing = false;
643 $scope.action_context_showing = false;
644 $scope.showActionContextMenu = function ($event) {
646 // Have to gather these here, instead of inside link()
647 if (!$scope.menu_dom) $scope.menu_dom = $($scope.grid_element).find('.grid-action-dropdown')[0];
648 if (!$scope.action_context_parent) $scope.action_context_parent = $($scope.menu_dom).parent();
650 // we need the the row that got right-clicked...
651 var e = $event.target; // the DOM element
652 var s = undefined; // the angular scope for that element
653 while(e){ // searching for the row
654 // abort & use the browser default context menu for links (lp1669856):
655 if(e.tagName.toLowerCase() === 'a' && e.href){ return true; }
656 s = angular.element(e).scope();
657 if(s.hasOwnProperty('item')){ break; }
660 // select the right-clicked row if it is not already selected (lp1776557):
661 if(!$scope.selected[grid.indexValue(s.item)]){ $event.target.click(); }
663 if (!$scope.action_context_showing) {
664 $scope.action_context_width = $($scope.menu_dom).css('width');
665 $scope.action_context_y = $($scope.menu_dom).css('top');
666 $scope.action_context_x = $($scope.menu_dom).css('left');
667 $scope.action_context_showing = true;
668 $scope.action_context_index = Math.floor((Math.random() * 1000) + 1);
670 $('body').append($($scope.menu_dom));
671 $('body').bind('click.remove_context_menu_'+$scope.action_context_index, $scope.hideActionContextMenu);
674 $($scope.menu_dom).css({
676 width: $scope.action_context_width,
684 // returns the list of selected item objects
685 grid.getSelectedItems = function() {
686 return $scope.items.filter(
688 return Boolean($scope.selected[grid.indexValue(item)]);
693 grid.getItemByIndex = function(index) {
694 for (var i = 0; i < $scope.items.length; i++) {
695 var item = $scope.items[i];
696 if (grid.indexValue(item) == index)
701 // selects one row after deselecting all of the others
702 grid.selectOneItem = function(index) {
703 $scope.selected = {};
704 $scope.selected[index] = true;
707 // selects items by a column value, first clearing selected list.
708 // we overwrite the object so that we can watch $scope.selected
709 grid.selectItemsByValue = function(column, value) {
710 $scope.selected = {};
711 angular.forEach($scope.items, function(item) {
713 if (angular.isFunction(item[column]))
714 col_value = item[column]();
716 col_value = item[column];
718 if (value == col_value) $scope.selected[grid.indexValue(item)] = true
722 // selects or deselects an item, without affecting the others.
723 // returns true if the item is selected; false if de-selected.
724 // we overwrite the object so that we can watch $scope.selected
725 grid.toggleSelectOneItem = function(index) {
726 if ($scope.selected[index]) {
727 delete $scope.selected[index];
728 $scope.selected = angular.copy($scope.selected);
731 $scope.selected[index] = true;
732 $scope.selected = angular.copy($scope.selected);
737 $scope.updateSelected = function () {
738 return $scope.selected = angular.copy($scope.selected);
741 grid.selectAllItems = function() {
742 angular.forEach($scope.items, function(item) {
743 $scope.selected[grid.indexValue(item)] = true
745 $scope.selected = angular.copy($scope.selected);
748 $scope.$watch('selectAll', function(newVal) {
750 grid.selectAllItems();
752 $scope.selected = {};
756 if ($scope.onSelect) {
757 $scope.$watch('selected', function(newVal) {
758 $scope.onSelect(grid.getSelectedItems());
759 if ($scope.afterSelect) $scope.afterSelect();
763 // returns true if item1 appears in the list before item2;
764 // false otherwise. this is slightly more efficient that
765 // finding the position of each then comparing them.
766 // item1 / item2 may be an item or an item index
767 grid.itemComesBefore = function(itemOrIndex1, itemOrIndex2) {
768 var idx1 = grid.indexValue(itemOrIndex1);
769 var idx2 = grid.indexValue(itemOrIndex2);
771 // use for() for early exit
772 for (var i = 0; i < $scope.items.length; i++) {
773 var idx = grid.indexValue($scope.items[i]);
774 if (idx == idx1) return true;
775 if (idx == idx2) return false;
780 // 0-based position of item in the current data set
781 grid.indexOf = function(item) {
782 var idx = grid.indexValue(item);
783 for (var i = 0; i < $scope.items.length; i++) {
784 if (grid.indexValue($scope.items[i]) == idx)
790 grid.modifyColumnFlex = function(column, val) {
792 // prevent flex:0; use hiding instead
796 $scope.modifyColumnFlex = function(col, val) {
797 $scope.lastModColumn = col;
798 grid.modifyColumnFlex(col, val);
801 $scope.isLastModifiedColumn = function(col) {
802 if ($scope.lastModColumn)
803 return $scope.lastModColumn === col;
807 grid.modifyColumnPos = function(col, diff) {
808 var srcIdx, targetIdx;
809 angular.forEach(grid.columnsProvider.columns,
810 function(c, i) { if (c.name == col.name) srcIdx = i });
812 targetIdx = srcIdx + diff;
815 } else if (targetIdx >= grid.columnsProvider.columns.length) {
816 // Target index follows the last visible column.
818 angular.forEach(grid.columnsProvider.columns,
819 function(column, idx) {
820 if (column.visible) lastVisible = idx;
823 targetIdx = lastVisible + 1;
826 // Splice column out of old position, insert at new position.
827 grid.columnsProvider.columns.splice(srcIdx, 1);
828 grid.columnsProvider.columns.splice(targetIdx, 0, col);
831 $scope.modifyColumnPos = function(col, diff) {
832 $scope.lastModColumn = col;
833 return grid.modifyColumnPos(col, diff);
836 // Returns true of the contents of the cell overflow its container.
837 // parentDepth tells the code how far up the DOM tree to traverse
838 // via parentNode before stopping to inspect the value.
839 // There's no way to pass a reference to a DOM node directly via
840 // a scope function (except ng-click, etc.) so pass the
841 // DOM id instead and get the node from there.
842 $scope.cellOverflowed = function(id, parentDepth) {
843 var node = document.getElementById(id);
845 for (var i = 0; i < parentDepth; i++) {
846 node = node.parentNode;
848 return node.scrollHeight > node.clientHeight
849 || node.scrollWidth > node.clientWidth;
852 // Generates a unique identifier per cell per grid.
853 $scope.cellId = function(col, item) {
854 if (!col || !item) return '';
855 return 'grid-cell-span-'
856 // differentiate grids
857 + ($scope.persistKey || $scope.idlClass || $scope.grid_element.id)
858 // differentiate rows and columns.
859 + '-' + col.name + '-' + $scope.indexValue(item);
863 // handles click, control-click, and shift-click
864 $scope.handleRowClick = function($event, item) {
865 var index = grid.indexValue(item);
867 var origSelected = Object.keys($scope.selected);
869 if (!$scope.canMultiSelect) {
870 grid.selectOneItem(index);
871 grid.lastSelectedItemIndex = index;
875 if ($event.ctrlKey || $event.metaKey /* mac command */) {
877 if (grid.toggleSelectOneItem(index))
878 grid.lastSelectedItemIndex = index;
880 } else if ($event.shiftKey) {
883 if (!grid.lastSelectedItemIndex ||
884 index == grid.lastSelectedItemIndex) {
885 grid.selectOneItem(index);
886 grid.lastSelectedItemIndex = index;
890 var selecting = false;
891 var ascending = grid.itemComesBefore(
892 grid.lastSelectedItemIndex, item);
894 grid.indexOf(grid.lastSelectedItemIndex);
896 // update to new last-selected
897 grid.lastSelectedItemIndex = index;
899 // select each row between the last selected and
900 // currently selected items
902 startPos += ascending ? 1 : -1;
903 var curItem = $scope.items[startPos];
905 var curIdx = grid.indexValue(curItem);
906 $scope.selected[curIdx] = true;
907 if (curIdx == index) break; // all done
909 $scope.selected = angular.copy($scope.selected);
913 grid.selectOneItem(index);
914 grid.lastSelectedItemIndex = index;
918 // Builds a sort expression from column sort priorities.
919 // called on page load and any time the priorities are modified.
920 grid.compileSort = function() {
921 var sortList = grid.columnsProvider.columns.filter(
922 function(col) { return Number(col.sort) != 0 }
925 if (Math.abs(a.sort) < Math.abs(b.sort))
931 if (sortList.length) {
932 grid.dataProvider.sort = sortList.map(function(col) {
934 blob[col.name] = col.sort < 0 ? 'desc' : 'asc';
940 // builds a sort expression using a single column,
941 // toggling between ascending and descending sort.
942 $scope.quickSort = function(col_name) {
943 var sort = grid.dataProvider.sort;
944 if (sort && sort.length &&
945 sort[0] == col_name) {
947 blob[col_name] = 'desc';
948 grid.dataProvider.sort = [blob];
950 grid.dataProvider.sort = [col_name];
957 // show / hide the grid configuration row
958 $scope.toggleConfDisplay = function() {
959 if ($scope.showGridConf) {
960 $scope.showGridConf = false;
961 if (grid.columnsProvider.hasSortableColumn()) {
962 // only refresh the grid if the user has the
963 // ability to modify the sort priorities.
969 $scope.showGridConf = true;
972 delete $scope.lastModColumn;
973 $scope.gridColumnPickerIsOpen = false;
976 // called when a dragged column is dropped onto itself
977 // or any other column
978 grid.onColumnDrop = function(target) {
979 if (angular.isUndefined(target)) return;
980 if (target == grid.dragColumn) return;
981 var srcIdx, targetIdx, srcCol;
982 angular.forEach(grid.columnsProvider.columns,
984 if (col.name == grid.dragColumn) {
987 } else if (col.name == target) {
993 if (srcIdx < targetIdx) targetIdx--;
995 // move src column from old location to new location in
996 // the columns array, then force a page refresh
997 grid.columnsProvider.columns.splice(srcIdx, 1);
998 grid.columnsProvider.columns.splice(targetIdx, 0, srcCol);
1002 // prepares a string for inclusion within a CSV document
1003 // by escaping commas and quotes and removing newlines.
1004 grid.csvDatum = function(str) {
1006 if (!str) return '';
1007 str = str.replace(/\n/g, '');
1008 if (str.match(/\,/) || str.match(/"/)) {
1009 str = str.replace(/"/g, '""');
1010 str = '"' + str + '"';
1015 /** Export the full data set as CSV.
1017 * 1. User clicks the 'download csv' link
1018 * 2. All grid data is retrieved asychronously
1019 * 3. Once all data is all present and CSV-ized, the download
1020 * attributes are linked to the href.
1021 * 4. The href .click() action is prgrammatically fired again,
1022 * telling the browser to download the data, now that the
1023 * data is available for download.
1024 * 5 Once downloaded, the href attributes are reset.
1026 grid.csvExportInProgress = false;
1027 $scope.generateCSVExportURL = function($event) {
1029 if (grid.csvExportInProgress) {
1030 // This is secondary href click handler. Give the
1031 // browser a moment to start the download, then reset
1032 // the CSV download attributes / state.
1035 $scope.csvExportURL = '';
1036 $scope.csvExportFileName = '';
1037 grid.csvExportInProgress = false;
1043 grid.csvExportInProgress = true;
1044 $scope.gridColumnPickerIsOpen = false;
1046 // let the file name describe the grid
1047 $scope.csvExportFileName =
1048 ($scope.mainLabel || grid.persistKey || 'eg_grid_data')
1049 .replace(/\s+/g, '_') + '_' + $scope.page();
1051 // toss the CSV into a Blob and update the export URL
1052 grid.generateCSV().then(function(csv) {
1053 var blob = new Blob([csv], {type : 'text/plain'});
1054 $scope.csvExportURL =
1055 ($window.URL || $window.webkitURL).createObjectURL(blob);
1057 // Fire the 2nd click event now that the browser has
1058 // information on how to download the CSV file.
1059 $timeout(function() {$event.target.click()});
1064 * TODO: does this serve any purpose given we can
1065 * print formatted HTML? If so, generateCSV() now
1066 * returns a promise, needs light refactoring...
1067 $scope.printCSV = function() {
1068 $scope.gridColumnPickerIsOpen = false;
1069 egCore.print.print({
1070 context : 'default',
1071 content : grid.generateCSV(),
1072 content_type : 'text/plain'
1077 // Given a row item and column definition, extract the
1078 // text content for printing. Templated columns must be
1079 // processed and parsed as HTML, then boiled down to their
1081 grid.getItemTextContent = function(item, col) {
1084 val = $scope.translateCellTemplate(col, item);
1086 var node = new DOMParser()
1087 .parseFromString(val, 'text/html');
1088 val = $(node).text();
1091 val = grid.dataProvider.itemFieldValue(item, col);
1092 val = $filter('egGridValueFilter')(val, col, item);
1098 * Fetches all grid data and transates each item into a simple
1099 * key-value pair of column name => text-value.
1100 * Included in the response for convenience is the list of
1101 * currently visible column definitions.
1102 * TODO: currently fetches a maximum of 10k rows. Does this
1103 * need to be configurable?
1105 grid.getAllItemsAsText = function() {
1106 var text_items = [];
1108 // we don't know the total number of rows we're about
1109 // to retrieve, but we can indicate the number retrieved
1110 // so far as each item arrives.
1111 egProgressDialog.open({value : 0});
1113 var visible_cols = grid.columnsProvider.columns.filter(
1114 function(c) { return c.visible });
1116 return grid.dataProvider.get(0, 10000).then(
1118 return {items : text_items, columns : visible_cols};
1122 egProgressDialog.increment();
1124 angular.forEach(visible_cols, function(col) {
1125 text_item[col.name] =
1126 grid.getItemTextContent(item, col);
1128 text_items.push(text_item);
1130 ).finally(egProgressDialog.close);
1133 // Fetch "all" of the grid data, translate it into print-friendly
1134 // text, and send it to the printer service.
1135 $scope.printHTML = function() {
1136 $scope.gridColumnPickerIsOpen = false;
1137 return grid.getAllItemsAsText().then(function(text_items) {
1138 return egCore.print.print({
1139 template : 'grid_html',
1145 // generates CSV for the currently visible grid contents
1146 grid.generateCSV = function() {
1147 return grid.getAllItemsAsText().then(function(text_items) {
1148 var columns = text_items.columns;
1149 var items = text_items.items;
1153 angular.forEach(columns, function(col) {
1154 csvStr += grid.csvDatum(col.label);
1158 csvStr = csvStr.replace(/,$/,'\n');
1161 angular.forEach(items, function(item) {
1162 angular.forEach(columns, function(col) {
1163 csvStr += grid.csvDatum(item[col.name]);
1166 csvStr = csvStr.replace(/,$/,'\n');
1173 // Interpolate the value for column.linkpath within the context
1174 // of the row item to generate the final link URL.
1175 $scope.generateLinkPath = function(col, item) {
1176 return egCore.strings.$replace(col.linkpath, {item : item});
1179 // If a column provides its own HTML template, translate it,
1180 // using the current item for the template scope.
1181 // note: $sce is required to avoid security restrictions and
1182 // is OK here, since the template comes directly from a
1183 // local HTML template (not user input).
1184 $scope.translateCellTemplate = function(col, item) {
1185 var html = egCore.strings.$replace(col.template, {item : item});
1186 return $sce.trustAsHtml(html);
1189 $scope.collect = function() { grid.collect() }
1191 // asks the dataProvider for a page of data
1192 grid.collect = function() {
1194 // avoid firing the collect if there is nothing to collect.
1195 if (grid.selfManagedData && !grid.dataProvider.query) return;
1197 if (grid.collecting) return; // avoid parallel collect()
1198 grid.collecting = true;
1200 console.debug('egGrid.collect() offset='
1201 + grid.offset + '; limit=' + grid.limit);
1203 // ensure all of our dropdowns are closed
1204 // TODO: git rid of these and just use dropdown-toggle,
1205 // which is more reliable.
1206 $scope.gridColumnPickerIsOpen = false;
1207 $scope.gridRowCountIsOpen = false;
1208 $scope.gridPageSelectIsOpen = false;
1211 $scope.selected = {};
1213 // Inform the caller we've asked the data provider
1214 // for data. This is useful for knowing when collection
1215 // has started (e.g. to display a progress dialg) when
1216 // using the stock (flattener) data provider, where the
1217 // user is not directly defining a get() handler.
1218 if (grid.controls.collectStarted)
1219 grid.controls.collectStarted(grid.offset, grid.limit);
1221 grid.dataProvider.get(grid.offset, grid.limit).then(
1223 if (grid.controls.allItemsRetrieved)
1224 grid.controls.allItemsRetrieved();
1229 $scope.items.push(item)
1230 if (grid.controls.itemRetrieved)
1231 grid.controls.itemRetrieved(item);
1232 if ($scope.selectAll)
1233 $scope.selected[grid.indexValue(item)] = true
1235 }).finally(function() {
1236 console.debug('egGrid.collect() complete');
1237 grid.collecting = false
1238 $scope.selected = angular.copy($scope.selected);
1248 * eg-grid-field : used for collecting custom field data from the templates.
1249 * This directive does not direct display, it just passes data up to the
1252 .directive('egGridField', function() {
1254 require : '^egGrid',
1257 flesher: '=', // optional; function that can flesh a linked field, given the value
1258 comparator: '=', // optional; function that can sort the thing at the end of 'path'
1259 name : '@', // required; unique name
1260 path : '@', // optional; flesh path
1261 ignore: '@', // optional; fields to ignore when path is a wildcard
1262 label : '@', // optional; display label
1263 flex : '@', // optional; default flex width
1264 align : '@', // optional; default alignment, left/center/right
1265 dateformat : '@', // optional: passed down to egGridValueFilter
1266 datecontext: '@', // optional: passed down to egGridValueFilter to choose TZ
1267 datefilter: '@', // optional: passed down to egGridValueFilter to choose specialized date filters
1268 dateonlyinterval: '@', // optional: passed down to egGridValueFilter to choose a "better" format
1270 // if a field is part of an IDL object, but we are unable to
1271 // determine the class, because it's nested within a hash
1272 // (i.e. we can't navigate directly to the object via the IDL),
1273 // idlClass lets us specify the class. This is particularly
1274 // useful for nested wildcard fields.
1275 parentIdlClass : '@',
1277 // optional: for non-IDL columns, specifying a datatype
1278 // lets the caller control which display filter is used.
1279 // datatype should match the standard IDL datatypes.
1282 link : function(scope, element, attrs, egGridCtrl) {
1284 // boolean fields are presented as value-less attributes
1293 'required' // if set, always fetch data for this column
1296 if (angular.isDefined(attrs[field]))
1297 scope[field] = true;
1301 // any HTML content within the field is its custom template
1302 var tmpl = element.html();
1303 if (tmpl && !tmpl.match(/^\s*$/))
1304 scope.template = tmpl
1306 egGridCtrl.columnsProvider.add(scope);
1313 * eg-grid-action : used for specifying actions which may be applied
1314 * to items within the grid.
1316 .directive('egGridAction', function() {
1318 require : '^egGrid',
1322 group : '@', // Action group, ungrouped if not set
1323 label : '@', // Action label
1324 handler : '=', // Action function handler
1326 disabled : '=', // function
1329 link : function(scope, element, attrs, egGridCtrl) {
1330 egGridCtrl.addAction({
1332 group : scope.group,
1333 label : scope.label,
1334 divider : scope.divider,
1335 handler : scope.handler,
1336 disabled : scope.disabled,
1343 .factory('egGridColumnsProvider', ['egCore', function(egCore) {
1345 function ColumnsProvider(args) {
1348 cols.stockVisible = [];
1349 cols.idlClass = args.idlClass;
1350 cols.clientSort = args.clientSort;
1351 cols.defaultToHidden = args.defaultToHidden;
1352 cols.defaultToNoSort = args.defaultToNoSort;
1353 cols.defaultToNoMultiSort = args.defaultToNoMultiSort;
1354 cols.defaultDateFormat = args.defaultDateFormat;
1355 cols.defaultDateContext = args.defaultDateContext;
1357 // resets column width, visibility, and sort behavior
1358 // Visibility resets to the visibility settings defined in the
1359 // template (i.e. the original egGridField values).
1360 cols.reset = function() {
1361 angular.forEach(cols.columns, function(col) {
1365 if (cols.stockVisible.indexOf(col.name) > -1) {
1368 col.visible = false;
1373 // returns true if any columns are sortable
1374 cols.hasSortableColumn = function() {
1375 return cols.columns.filter(
1377 return col.sortable || col.multisortable;
1382 cols.showAllColumns = function() {
1383 angular.forEach(cols.columns, function(column) {
1384 column.visible = true;
1388 cols.hideAllColumns = function() {
1389 angular.forEach(cols.columns, function(col) {
1394 cols.indexOf = function(name) {
1395 for (var i = 0; i < cols.columns.length; i++) {
1396 if (cols.columns[i].name == name)
1402 cols.findColumn = function(name) {
1403 return cols.columns[cols.indexOf(name)];
1406 cols.compileAutoColumns = function() {
1407 var idl_class = egCore.idl.classes[cols.idlClass];
1412 if (field.virtual) return;
1413 if (field.datatype == 'link' || field.datatype == 'org_unit') {
1414 // if the field is a link and the linked class has a
1415 // "selector" field specified, use the selector field
1416 // as the display field for the columns.
1417 // flattener will take care of the fleshing.
1418 if (field['class']) {
1419 var selector_field = egCore.idl.classes[field['class']].fields
1420 .filter(function(f) { return Boolean(f.selector) })[0];
1421 if (selector_field) {
1422 field.path = field.name + '.' + selector_field.selector;
1426 cols.add(field, true);
1431 // if a column definition has a path with a wildcard, create
1432 // columns for all non-virtual fields at the specified
1433 // position in the path.
1434 cols.expandPath = function(colSpec) {
1436 var ignoreList = [];
1438 ignoreList = colSpec.ignore.split(' ');
1440 var dotpath = colSpec.path.replace(/\.?\*$/,'');
1444 if (colSpec.parentIdlClass) {
1445 class_obj = egCore.idl.classes[colSpec.parentIdlClass];
1447 class_obj = egCore.idl.classes[cols.idlClass];
1449 var idl_parent = class_obj;
1450 var old_field_label = '';
1452 if (!class_obj) return;
1454 console.debug('egGrid: auto dotpath is: ' + dotpath);
1455 var path_parts = dotpath.split(/\./);
1457 // find the IDL class definition for the last element in the
1458 // path before the .*
1459 // an empty path_parts means expand the root class
1462 for (var path_idx in path_parts) {
1463 old_field = idl_field;
1465 var part = path_parts[path_idx];
1466 idl_field = class_obj.field_map[part];
1468 // unless we're at the end of the list, this field should
1469 // link to another class.
1470 if (idl_field && idl_field['class'] && (
1471 idl_field.datatype == 'link' ||
1472 idl_field.datatype == 'org_unit')) {
1473 if (old_field_label) old_field_label += ' : ';
1474 old_field_label += idl_field.label;
1475 class_obj = egCore.idl.classes[idl_field['class']];
1476 if (old_field) idl_parent = old_field;
1478 if (path_idx < (path_parts.length - 1)) {
1479 // we ran out of classes to hop through before
1480 // we ran out of path components
1481 console.error("egGrid: invalid IDL path: " + dotpath);
1488 angular.forEach(class_obj.fields, function(field) {
1490 // Only show wildcard fields where we have data to show
1491 // Virtual and un-fleshed links will not have any data.
1492 if (field.virtual ||
1493 (field.datatype == 'link' || field.datatype == 'org_unit') ||
1494 ignoreList.indexOf(field.name) > -1
1498 var col = cols.cloneFromScope(colSpec);
1499 col.path = (dotpath ? dotpath + '.' + field.name : field.name);
1501 // log line below is very chatty. disable until needed.
1502 // console.debug('egGrid: field: ' +field.name + '; parent field: ' + js2JSON(idl_parent));
1503 cols.add(col, false, true,
1504 {idl_parent : idl_parent, idl_field : field, idl_class : class_obj, field_parent_label : old_field_label });
1507 cols.columns = cols.columns.sort(
1509 if (a.explicit) return -1;
1510 if (b.explicit) return 1;
1512 if (a.idlclass && b.idlclass) {
1513 if (a.idlclass < b.idlclass) return -1;
1514 if (b.idlclass < a.idlclass) return 1;
1517 if (a.path && b.path && a.path.lastIndexOf('.') && b.path.lastIndexOf('.')) {
1518 if (a.path.substring(0, a.path.lastIndexOf('.')) < b.path.substring(0, b.path.lastIndexOf('.'))) return -1;
1519 if (b.path.substring(0, b.path.lastIndexOf('.')) < a.path.substring(0, a.path.lastIndexOf('.'))) return 1;
1522 if (a.label && b.label) {
1523 if (a.label < b.label) return -1;
1524 if (b.label < a.label) return 1;
1527 return a.name < b.name ? -1 : 1;
1534 "egGrid: wildcard path does not resolve to an object: "
1539 // angular.clone(scopeObject) is not permittable. Manually copy
1540 // the fields over that we need (so the scope object can go away).
1541 cols.cloneFromScope = function(colSpec) {
1543 flesher : colSpec.flesher,
1544 comparator : colSpec.comparator,
1545 name : colSpec.name,
1546 label : colSpec.label,
1547 path : colSpec.path,
1548 align : colSpec.align || 'left',
1549 flex : Number(colSpec.flex) || 2,
1550 sort : Number(colSpec.sort) || 0,
1551 required : colSpec.required,
1552 linkpath : colSpec.linkpath,
1553 template : colSpec.template,
1554 visible : colSpec.visible,
1555 hidden : colSpec.hidden,
1556 datatype : colSpec.datatype,
1557 sortable : colSpec.sortable,
1558 nonsortable : colSpec.nonsortable,
1559 multisortable : colSpec.multisortable,
1560 nonmultisortable : colSpec.nonmultisortable,
1561 dateformat : colSpec.dateformat,
1562 datecontext : colSpec.datecontext,
1563 datefilter : colSpec.datefilter,
1564 dateonlyinterval : colSpec.dateonlyinterval,
1565 parentIdlClass : colSpec.parentIdlClass
1570 // Add a column to the columns collection.
1571 // Columns may come from a slim eg-columns-field or
1572 // directly from the IDL.
1573 cols.add = function(colSpec, fromIDL, fromExpand, idl_info) {
1575 // First added column with the specified path takes precedence.
1576 // This allows for specific definitions followed by wildcard
1577 // definitions. If a match is found, back out.
1578 if (cols.columns.filter(function(c) {
1579 return (c.path == colSpec.path) })[0]) {
1580 console.debug('skipping pre-existing column ' + colSpec.path);
1584 var column = fromExpand ? colSpec : cols.cloneFromScope(colSpec);
1586 if (column.path && column.path.match(/\*$/))
1587 return cols.expandPath(colSpec);
1589 if (!fromExpand) column.explicit = true;
1591 if (!column.name) column.name = column.path;
1592 if (!column.path) column.path = column.name;
1594 if (column.visible || (!cols.defaultToHidden && !column.hidden))
1595 column.visible = true;
1597 if (column.sortable || (!cols.defaultToNoSort && !column.nonsortable))
1598 column.sortable = true;
1600 if (column.multisortable ||
1601 (!cols.defaultToNoMultiSort && !column.nonmultisortable))
1602 column.multisortable = true;
1604 if (cols.defaultDateFormat && ! column.dateformat) {
1605 column.dateformat = cols.defaultDateFormat;
1608 if (cols.defaultDateOnlyInterval && ! column.dateonlyinterval) {
1609 column.dateonlyinterval = cols.defaultDateOnlyInterval;
1612 if (cols.defaultDateContext && ! column.datecontext) {
1613 column.datecontext = cols.defaultDateContext;
1616 if (cols.defaultDateFilter && ! column.datefilter) {
1617 column.datefilter = cols.defaultDateFilter;
1620 cols.columns.push(column);
1622 // Track which columns are visible by default in case we
1623 // need to reset column visibility
1625 cols.stockVisible.push(column.name);
1627 if (fromIDL) return; // directly from egIDL. nothing left to do.
1629 // lookup the matching IDL field
1630 if (!idl_info && cols.idlClass)
1631 idl_info = cols.idlFieldFromPath(column.path);
1634 // column is not represented within the IDL
1635 column.adhoc = true;
1639 column.datatype = idl_info.idl_field.datatype;
1641 if (!column.label) {
1642 column.label = idl_info.idl_field.label || column.name;
1645 if (fromExpand && idl_info.idl_class) {
1646 column.idlclass = '';
1647 if (idl_info.field_parent_label && idl_info.idl_parent.label != idl_info.idl_class.label) {
1648 column.idlclass = (idl_info.field_parent_label || idl_info.idl_parent.label || idl_info.idl_parent.name);
1650 column.idlclass += idl_info.idl_class.label || idl_info.idl_class.name;
1655 // finds the IDL field from the dotpath, using the columns
1656 // idlClass as the base.
1657 cols.idlFieldFromPath = function(dotpath) {
1658 var class_obj = egCore.idl.classes[cols.idlClass];
1659 var path_parts = dotpath.split(/\./);
1663 for (var path_idx in path_parts) {
1664 var part = path_parts[path_idx];
1665 idl_parent = idl_field;
1666 idl_field = class_obj.field_map[part];
1669 if (idl_field['class'] && (
1670 idl_field.datatype == 'link' ||
1671 idl_field.datatype == 'org_unit')) {
1672 class_obj = egCore.idl.classes[idl_field['class']];
1680 idl_parent: idl_parent,
1681 idl_field : idl_field,
1682 idl_class : class_obj
1688 instance : function(args) { return new ColumnsProvider(args) }
1694 * Generic data provider template class. This is basically an abstract
1695 * class factory service whose instances can be locally modified to
1696 * meet the needs of each individual grid.
1698 .factory('egGridDataProvider',
1699 ['$q','$timeout','$filter','egCore',
1700 function($q , $timeout , $filter , egCore) {
1702 function GridDataProvider(args) {
1703 var gridData = this;
1704 if (!args) args = {};
1707 gridData.get = args.get;
1708 gridData.query = args.query;
1709 gridData.idlClass = args.idlClass;
1710 gridData.columnsProvider = args.columnsProvider;
1712 // Delivers a stream of array data via promise.notify()
1713 // Useful for passing an array of data to egGrid.get()
1714 // If a count is provided, the array will be trimmed to
1715 // the range defined by count and offset
1716 gridData.arrayNotifier = function(arr, offset, count) {
1717 if (!arr || arr.length == 0) return $q.when();
1719 if (gridData.columnsProvider.clientSort
1721 && gridData.sort.length > 0
1723 var sorter_cache = [];
1724 arr.sort(function(a,b) {
1725 for (var si = 0; si < gridData.sort.length; si++) {
1726 if (!sorter_cache[si]) { // Build sort structure on first comparison, reuse thereafter
1727 var field = gridData.sort[si];
1730 if (angular.isObject(field)) {
1731 dir = Object.values(field)[0];
1732 field = Object.keys(field)[0];
1735 var path = gridData.columnsProvider.findColumn(field).path || field;
1736 var comparator = gridData.columnsProvider.findColumn(field).comparator ||
1737 function (x,y) { if (x < y) return -1; if (x > y) return 1; return 0 };
1739 sorter_cache[si] = {
1742 comparator : comparator
1746 var sc = sorter_cache[si];
1750 if (a._isfieldmapper || angular.isFunction(a[sc.field])) {
1751 try {af = a[sc.field](); bf = b[sc.field]() } catch (e) {};
1753 af = a[sc.field]; bf = b[sc.field];
1755 if (af === undefined && sc.field.indexOf('.') > -1) { // assume an object, not flat path
1756 var parts = sc.field.split('.');
1759 angular.forEach(parts, function (p) {
1761 if (af._isfieldmapper || angular.isFunction(af[p])) af = af[p]();
1765 if (bf._isfieldmapper || angular.isFunction(bf[p])) bf = bf[p]();
1771 if (af === undefined) af = null;
1772 if (bf === undefined) bf = null;
1774 if (af === null && bf !== null) return 1;
1775 if (bf === null && af !== null) return -1;
1777 if (!(bf === null && af === null)) {
1778 var partial = sc.comparator(af,bf);
1780 if (sc.dir == 'desc') {
1781 if (partial > 0) return -1;
1793 if (count) arr = arr.slice(offset, offset + count);
1794 var def = $q.defer();
1795 // promise notifications are only witnessed when delivered
1796 // after the caller has his hands on the promise object
1797 $timeout(function() {
1798 angular.forEach(arr, def.notify);
1804 // Calls the grid refresh function. Once instantiated, the
1805 // grid will replace this function with it's own refresh()
1806 gridData.refresh = function(noReset) { }
1808 if (!gridData.get) {
1809 // returns a promise whose notify() delivers items
1810 gridData.get = function(index, count) {
1811 console.error("egGridDataProvider.get() not implemented");
1815 // attempts a flat field lookup first. If the column is not
1816 // found on the top-level object, attempts a nested lookup
1817 // TODO: consider a caching layer to speed up template
1818 // rendering, particularly for nested objects?
1819 gridData.itemFieldValue = function(item, column) {
1821 if (column.name in item) {
1822 if (typeof item[column.name] == 'function') {
1823 val = item[column.name]();
1825 val = item[column.name];
1828 val = gridData.nestedItemFieldValue(item, column);
1834 // TODO: deprecate me
1835 gridData.flatItemFieldValue = function(item, column) {
1836 console.warn('gridData.flatItemFieldValue deprecated; '
1837 + 'leave provider.itemFieldValue unset');
1838 return item[column.name];
1841 // given an object and a dot-separated path to a field,
1842 // extract the value of the field. The path can refer
1843 // to function names or object attributes. If the final
1844 // value is an IDL field, run the value through its
1845 // corresponding output filter.
1846 gridData.nestedItemFieldValue = function(obj, column) {
1847 item = obj; // keep a copy around
1849 if (obj === null || obj === undefined || obj === '') return '';
1850 if (!column.path) return obj;
1853 var parts = column.path.split('.');
1855 angular.forEach(parts, function(step, idx) {
1856 // object is not fleshed to the expected extent
1857 if (typeof obj != 'object') {
1858 if (typeof obj != 'undefined' && column.flesher) {
1859 obj = column.flesher(obj, column, item);
1866 if (!obj) return '';
1868 var cls = obj.classname;
1869 if (cls && (class_obj = egCore.idl.classes[cls])) {
1870 idl_field = class_obj.field_map[step];
1871 obj = obj[step] ? obj[step]() : '';
1873 if (angular.isFunction(obj[step])) {
1881 // We found a nested IDL object which may or may not have
1882 // been configured as a top-level column. Grab the datatype.
1883 if (idl_field && !column.datatype)
1884 column.datatype = idl_field.datatype;
1886 if (obj === null || obj === undefined || obj === '') return '';
1892 instance : function(args) {
1893 return new GridDataProvider(args);
1900 // Factory service for egGridDataManager instances, which are
1901 // responsible for collecting flattened grid data.
1902 .factory('egGridFlatDataProvider',
1903 ['$q','egCore','egGridDataProvider',
1904 function($q , egCore , egGridDataProvider) {
1907 instance : function(args) {
1908 var provider = egGridDataProvider.instance(args);
1910 provider.get = function(offset, count) {
1912 // no query means no call
1913 if (!provider.query ||
1914 angular.equals(provider.query, {}))
1917 // find all of the currently visible columns
1918 var queryFields = {}
1919 angular.forEach(provider.columnsProvider.columns,
1921 // only query IDL-tracked columns
1922 if (!col.adhoc && (col.required || col.visible))
1923 queryFields[col.name] = col.path;
1927 return egCore.net.request(
1929 'open-ils.fielder.flattened_search',
1930 egCore.auth.token(), provider.idlClass,
1931 queryFields, provider.query,
1932 { sort : provider.sort,
1938 //provider.itemFieldValue = provider.flatItemFieldValue;
1945 .directive('egGridColumnDragSource', function() {
1948 require : '^egGrid',
1949 link : function(scope, element, attrs, egGridCtrl) {
1950 angular.element(element).attr('draggable', 'true');
1952 element.bind('dragstart', function(e) {
1953 egGridCtrl.dragColumn = attrs.column;
1954 egGridCtrl.dragType = attrs.dragType || 'move'; // or resize
1955 egGridCtrl.colResizeDir = 0;
1957 if (egGridCtrl.dragType == 'move') {
1958 // style the column getting moved
1959 angular.element(e.target).addClass(
1960 'eg-grid-column-move-handle-active');
1964 element.bind('dragend', function(e) {
1965 if (egGridCtrl.dragType == 'move') {
1966 angular.element(e.target).removeClass(
1967 'eg-grid-column-move-handle-active');
1974 .directive('egGridColumnDragDest', function() {
1977 require : '^egGrid',
1978 link : function(scope, element, attrs, egGridCtrl) {
1980 element.bind('dragover', function(e) { // required for drop
1981 e.stopPropagation();
1983 e.dataTransfer.dropEffect = 'move';
1985 if (egGridCtrl.colResizeDir == 0) return; // move
1987 var cols = egGridCtrl.columnsProvider;
1988 var srcCol = egGridCtrl.dragColumn;
1989 var srcColIdx = cols.indexOf(srcCol);
1991 if (egGridCtrl.colResizeDir == -1) {
1992 if (cols.indexOf(attrs.column) <= srcColIdx) {
1993 egGridCtrl.modifyColumnFlex(
1994 egGridCtrl.columnsProvider.findColumn(
1995 egGridCtrl.dragColumn), -1);
1996 if (cols.columns[srcColIdx+1]) {
1997 // source column shrinks by one, column to the
1998 // right grows by one.
1999 egGridCtrl.modifyColumnFlex(
2000 cols.columns[srcColIdx+1], 1);
2005 if (cols.indexOf(attrs.column) > srcColIdx) {
2006 egGridCtrl.modifyColumnFlex(
2007 egGridCtrl.columnsProvider.findColumn(
2008 egGridCtrl.dragColumn), 1);
2009 if (cols.columns[srcColIdx+1]) {
2010 // source column grows by one, column to the
2011 // right grows by one.
2012 egGridCtrl.modifyColumnFlex(
2013 cols.columns[srcColIdx+1], -1);
2021 element.bind('dragenter', function(e) {
2022 e.stopPropagation();
2024 if (egGridCtrl.dragType == 'move') {
2025 angular.element(e.target).addClass('eg-grid-col-hover');
2027 // resize grips are on the right side of each column.
2028 // dragenter will either occur on the source column
2029 // (dragging left) or the column to the right.
2030 if (egGridCtrl.colResizeDir == 0) {
2031 if (egGridCtrl.dragColumn == attrs.column) {
2032 egGridCtrl.colResizeDir = -1; // west
2034 egGridCtrl.colResizeDir = 1; // east
2040 element.bind('dragleave', function(e) {
2041 e.stopPropagation();
2043 if (egGridCtrl.dragType == 'move') {
2044 angular.element(e.target).removeClass('eg-grid-col-hover');
2048 element.bind('drop', function(e) {
2049 e.stopPropagation();
2051 egGridCtrl.colResizeDir = 0;
2052 if (egGridCtrl.dragType == 'move') {
2053 angular.element(e.target).removeClass('eg-grid-col-hover');
2054 egGridCtrl.onColumnDrop(attrs.column); // move the column
2061 .directive('egGridMenuItem', function() {
2064 require : '^egGrid',
2070 handler : '=', // onclick handler function
2071 divider : '=', // if true, show a divider only
2072 handlerData : '=', // if set, passed as second argument to handler
2073 disabled : '=', // function
2074 hidden : '=' // function
2076 link : function(scope, element, attrs, egGridCtrl) {
2077 egGridCtrl.addMenuItem({
2078 checkbox : scope.checkbox,
2079 checked : scope.checked ? true : false,
2080 label : scope.label,
2081 standalone : scope.standalone ? true : false,
2082 handler : scope.handler,
2083 divider : scope.divider,
2084 disabled : scope.disabled,
2085 hidden : scope.hidden,
2086 handlerData : scope.handlerData
2096 * Translates bare IDL object values into display values.
2097 * 1. Passes dates through the angular date filter
2098 * 2. Converts bools to translated Yes/No strings
2099 * Others likely to follow...
2101 .filter('egGridValueFilter', ['$filter','egCore', 'egStrings', function($filter,egCore,egStrings) {
2102 function traversePath(obj,path) {
2103 var list = path.split('.');
2104 for (var part in path) {
2105 if (obj[path]) obj = obj[path]
2111 var GVF = function(value, column, item) {
2112 switch(column.datatype) {
2115 // Browser will translate true/false for us
2117 case '1' : // legacy
2119 return egStrings.YES;
2121 case '0' : // legacy
2123 return egStrings.NO;
2124 // value may be null, '', etc.
2125 default : return '';
2128 var interval = angular.isFunction(item[column.dateonlyinterval])
2129 ? item[column.dateonlyinterval]()
2130 : item[column.dateonlyinterval];
2132 if (column.dateonlyinterval && !interval) // try it as a dotted path
2133 interval = traversePath(item, column.dateonlyinterval);
2135 var context = angular.isFunction(item[column.datecontext])
2136 ? item[column.datecontext]()
2137 : item[column.datecontext];
2139 if (column.datecontext && !context) // try it as a dotted path
2140 context = traversePath(item, column.datecontext);
2142 var date_filter = column.datefilter || 'egOrgDateInContext';
2144 return $filter(date_filter)(value, column.dateformat, context, interval);
2146 return $filter('currency')(value);
2152 GVF.$stateful = true;