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) {
113 // link() is called after page compilation, which means our
114 // eg-grid-field's have been parsed and loaded. Now it's
115 // safe to perform our initial page load.
117 // load auto fields after eg-grid-field's so they are not clobbered
118 scope.handleAutoFields();
121 scope.grid_element = element;
123 .find('.eg-grid-content-body')
124 .bind('contextmenu', scope.showActionContextMenu);
128 '$scope','$q','egCore','egGridFlatDataProvider','$location',
129 'egGridColumnsProvider','$filter','$window','$sce','$timeout',
130 'egProgressDialog','$uibModal','egConfirmDialog','egStrings',
131 function($scope, $q , egCore, egGridFlatDataProvider , $location,
132 egGridColumnsProvider , $filter , $window , $sce , $timeout,
133 egProgressDialog, $uibModal , egConfirmDialog , egStrings) {
137 grid.init = function() {
140 $scope.showGridConf = false;
141 grid.totalCount = -1;
142 $scope.selected = {};
143 $scope.actionGroups = [{actions:[]}]; // Grouped actions for selected items
144 $scope.menuItems = []; // global actions
146 // returns true if any rows are selected.
147 $scope.hasSelected = function() {
148 return grid.getSelectedItems().length > 0 };
150 var features = ($scope.features) ?
151 $scope.features.split(',') : [];
152 delete $scope.features;
154 $scope.showIndex = (features.indexOf('-index') == -1);
156 $scope.allowAll = (features.indexOf('allowAll') > -1);
157 $scope.startSelected = $scope.selectAll = (features.indexOf('startSelected') > -1);
158 $scope.showActions = (features.indexOf('-actions') == -1);
159 $scope.showPagination = (features.indexOf('-pagination') == -1);
160 $scope.showPicker = (features.indexOf('-picker') == -1);
162 $scope.showMenu = (features.indexOf('-menu') == -1);
164 // remove some unneeded values from the scope to reduce bloat
166 grid.idlClass = $scope.idlClass;
167 delete $scope.idlClass;
169 grid.persistKey = $scope.persistKey;
170 delete $scope.persistKey;
172 var stored_limit = 0;
173 if ($scope.showPagination) {
174 // localStorage of grid limits is deprecated. Limits
175 // are now stored along with the columns configuration.
176 // Values found in localStorage will be migrated upon
178 if (grid.persistKey) {
179 var stored_limit = Number(
180 egCore.hatch.getLocalItem('eg.grid.' + grid.persistKey + '.limit')
184 stored_limit = 10000; // maybe support "Inf"?
187 grid.limit = Number(stored_limit) || Number($scope.pageSize) || 25;
189 grid.indexField = $scope.idField;
190 delete $scope.idField;
192 grid.dataProvider = $scope.itemsProvider;
194 if (!grid.indexField && grid.idlClass)
195 grid.indexField = egCore.idl.classes[grid.idlClass].pkey;
197 grid.columnsProvider = egGridColumnsProvider.instance({
198 idlClass : grid.idlClass,
199 clientSort : (features.indexOf('clientsort') > -1 && features.indexOf('-clientsort') == -1),
200 defaultToHidden : (features.indexOf('-display') > -1),
201 defaultToNoSort : (features.indexOf('-sort') > -1),
202 defaultToNoMultiSort : (features.indexOf('-multisort') > -1),
203 defaultDateFormat : $scope.dateformat,
204 defaultDateContext : $scope.datecontext,
205 defaultDateFilter : $scope.datefilter,
206 defaultDateOnlyInterval : $scope.dateonlyinterval
208 $scope.canMultiSelect = (features.indexOf('-multiselect') == -1);
210 $scope.handleAutoFields = function() {
211 if ($scope.autoFields) {
212 if (grid.autoLabel) {
214 egCore.idl.classes[grid.idlClass].label;
216 grid.columnsProvider.compileAutoColumns();
217 delete $scope.autoFields;
221 if (!grid.dataProvider) {
222 // no provider, um, provided.
223 // Use a flat data provider
225 grid.selfManagedData = true;
226 grid.dataProvider = egGridFlatDataProvider.instance({
227 indexField : grid.indexField,
228 idlClass : grid.idlClass,
229 columnsProvider : grid.columnsProvider,
234 // make grid ref available in get() to set totalCount, if known.
235 // this allows us disable the 'next' paging button correctly
236 grid.dataProvider.grid = grid;
238 grid.dataProvider.columnsProvider = grid.columnsProvider;
240 $scope.itemFieldValue = grid.dataProvider.itemFieldValue;
241 $scope.indexValue = function(item) {
242 return grid.indexValue(item)
245 grid.applyControlFunctions();
247 grid.loadConfig().then(function() {
248 // link columns to scope after loadConfig(), since it
249 // replaces the columns array.
250 $scope.columns = grid.columnsProvider.columns;
253 // NOTE: grid.collect() is first called from link(), not here.
256 // link our control functions into the gridControls
257 // scope object so the caller can access them.
258 grid.applyControlFunctions = function() {
260 // we use some of these controls internally, so sett
261 // them up even if the caller doesn't request them.
262 var controls = $scope.gridControls || {};
264 controls.columnMap = function() {
266 angular.forEach(grid.columnsProvider.columns, function (c) {
272 controls.columnsProvider = function() {
273 return grid.columnsProvider;
276 // link in the control functions
277 controls.selectedItems = function() {
278 return grid.getSelectedItems()
281 controls.allItems = function() {
285 controls.selectItems = function(ids) {
287 $scope.selected = {};
288 angular.forEach(ids, function(i) {
289 $scope.selected[''+i] = true;
293 // if the caller provided a functional setQuery,
294 // extract the value before replacing it
295 if (controls.setQuery) {
296 grid.dataProvider.query =
300 controls.setQuery = function(query) {
301 grid.dataProvider.query = query;
305 if (controls.watchQuery) {
306 // capture the initial query value
307 grid.dataProvider.query = controls.watchQuery();
310 $scope.gridWatchQuery = controls.watchQuery;
311 $scope.$watch('gridWatchQuery()', function(newv) {
312 controls.setQuery(newv);
316 // if the caller provided a functional setSort
317 // extract the value before replacing it
318 grid.dataProvider.sort =
319 controls.setSort ? controls.setSort() : [];
321 controls.setSort = function(sort) {
325 controls.refresh = function(noReset) {
326 if (!noReset) grid.offset = 0;
330 controls.setLimit = function(limit,forget) {
332 if (!forget && grid.persistKey) {
336 controls.getLimit = function() {
339 controls.setOffset = function(offset) {
340 grid.offset = offset;
342 controls.getOffset = function() {
346 controls.saveConfig = function () {
347 return $scope.saveConfig();
350 grid.dataProvider.refresh = controls.refresh;
351 grid.controls = controls;
354 // If a menu item provides its own HTML template, translate it,
355 // using the menu item for the template scope.
356 // note: $sce is required to avoid security restrictions and
357 // is OK here, since the template comes directly from a
358 // local HTML template (not user input).
359 $scope.translateMenuItemTemplate = function(item) {
360 var html = egCore.strings.$replace(item.template, {item : item});
361 return $sce.trustAsHtml(html);
364 // add a new (global) grid menu item
365 grid.addMenuItem = function(item) {
366 $scope.menuItems.push(item);
367 var handler = item.handler;
368 item.handler = function() {
369 $scope.gridMenuIsOpen = false; // close menu
372 item.handlerData, grid.getSelectedItems());
377 // add a selected-items action
378 grid.addAction = function(act) {
380 $scope.actionGroups.forEach(function(g){
381 if (g.label === act.group) {
387 $scope.actionGroups.push({
394 // remove the stored column configuration preferenc, then recover
395 // the column visibility information from the initial page load.
396 $scope.resetColumns = function() {
397 $scope.gridColumnPickerIsOpen = false;
398 egCore.hatch.removeItem('eg.grid.' + grid.persistKey)
400 grid.columnsProvider.reset();
401 if (grid.selfManagedData) grid.collect();
405 $scope.showAllColumns = function() {
406 $scope.gridColumnPickerIsOpen = false;
407 grid.columnsProvider.showAllColumns();
408 if (grid.selfManagedData) grid.collect();
411 $scope.hideAllColumns = function() {
412 $scope.gridColumnPickerIsOpen = false;
413 grid.columnsProvider.hideAllColumns();
414 // note: no need to fetch new data if no columns are visible
417 $scope.toggleColumnVisibility = function(col) {
418 $scope.gridColumnPickerIsOpen = false;
419 col.visible = !col.visible;
421 // egGridFlatDataProvider only retrieves data to be
422 // displayed. When column visibility changes, it's
423 // necessary to fetch the newly visible column data.
424 if (grid.selfManagedData) grid.collect();
427 // save the columns configuration (position, sort, width) to
428 // eg.grid.<persist-key>
429 $scope.saveConfig = function() {
430 $scope.gridColumnPickerIsOpen = false;
432 if (!grid.persistKey) {
434 "Cannot save settings without a grid persist-key");
438 // only store information about visible columns.
439 var cols = grid.columnsProvider.columns.filter(
440 function(col) {return Boolean(col.visible) });
442 // now scrunch the data down to just the needed info
443 cols = cols.map(function(col) {
444 var c = {name : col.name}
445 // Apart from the name, only store non-default values.
446 // No need to store col.visible, since that's implicit
447 if (col.align != 'left') c.align = col.align;
448 if (col.flex != 2) c.flex = col.flex;
449 if (Number(col.sort)) c.sort = Number(c.sort);
459 egCore.hatch.setItem('eg.grid.' + grid.persistKey, conf)
461 // Save operation performed from the grid configuration UI.
462 // Hide the configuration UI and re-draw w/ sort applied
463 if ($scope.showGridConf)
464 $scope.toggleConfDisplay();
466 // Once a version-2 grid config is saved (with limit
467 // included) we can remove the local limit pref.
468 egCore.hatch.removeLocalItem(
469 'eg.grid.' + grid.persistKey + '.limit');
474 // load the columns configuration (position, sort, width) from
475 // eg.grid.<persist-key> and apply the loaded settings to the
476 // columns on our columnsProvider
477 grid.loadConfig = function() {
478 if (!grid.persistKey) return $q.when();
480 return egCore.hatch.getItem('eg.grid.' + grid.persistKey)
481 .then(function(conf) {
484 var columns = grid.columnsProvider.columns;
487 if (Array.isArray(conf)) {
489 'upgrading version 1 grid config to version 2');
497 grid.limit = Number(conf.limit);
500 angular.forEach(conf.columns, function(col) {
501 var grid_col = columns.filter(
502 function(c) {return c.name == col.name})[0];
505 // saved column does not match a column in the
506 // current grid. skip it.
510 grid_col.align = col.align || 'left';
511 grid_col.flex = col.flex || 2;
512 grid_col.sort = col.sort || 0;
513 // all saved columns are assumed to be true
514 grid_col.visible = true;
516 .filter(function (c) {
517 return c.name == grid_col.name;
520 new_cols.push(grid_col);
523 // columns which are not expressed within the saved
524 // configuration are marked as non-visible and
525 // appended to the end of the new list of columns.
526 angular.forEach(columns, function(col) {
527 var found = conf.columns.filter(
528 function(c) {return (c.name == col.name)})[0];
535 grid.columnsProvider.columns = new_cols;
541 $scope.onContextMenu = function($event) {
542 var col = angular.element($event.target).attr('column');
543 console.log('selected column ' + col);
546 $scope.page = function() {
547 return (grid.offset / grid.limit) + 1;
550 $scope.goToPage = function(page) {
552 if (angular.isNumber(page) && page > 0) {
553 grid.offset = (page - 1) * grid.limit;
558 $scope.offset = function(o) {
559 if (angular.isNumber(o))
564 $scope.limit = function(l) {
565 if (angular.isNumber(l)) {
567 if (grid.persistKey) {
574 $scope.onFirstPage = function() {
575 return grid.offset == 0;
578 $scope.hasNextPage = function() {
579 // we have less data than requested, there must
580 // not be any more pages
581 if (grid.count() < grid.limit) return false;
583 // if the total count is not known, assume that a full
584 // page of data implies more pages are available.
585 if (grid.totalCount == -1) return true;
587 // we have a full page of data, but is there more?
588 return grid.totalCount > (grid.offset + grid.count());
591 $scope.incrementPage = function() {
592 grid.offset += grid.limit;
596 $scope.decrementPage = function() {
597 if (grid.offset < grid.limit) {
600 grid.offset -= grid.limit;
605 // number of items loaded for the current page of results
606 grid.count = function() {
607 return $scope.items.length;
610 // returns the unique identifier value for the provided item
611 // for internal consistency, indexValue is always coerced
613 grid.indexValue = function(item) {
614 if (angular.isObject(item)) {
616 if (angular.isFunction(item[grid.indexField]))
617 return ''+item[grid.indexField]();
618 return ''+item[grid.indexField]; // flat data
621 // passed a non-object; assume it's an index
625 // fires the hide handler function for a context action
626 $scope.actionHide = function(action) {
627 if (typeof action.hide == 'undefined') {
630 if (angular.isFunction(action.hide))
631 return action.hide(action);
635 // fires the disable handler function for a context action
636 $scope.actionDisable = function(action) {
637 if (typeof action.disabled == 'undefined') {
640 if (angular.isFunction(action.disabled))
641 return action.disabled(action);
642 return action.disabled;
645 // fires the action handler function for a context action
646 $scope.actionLauncher = function(action) {
647 if (!action.handler) {
649 'No handler specified for "' + action.label + '"');
653 action.handler(grid.getSelectedItems());
655 console.error('Error executing handler for "'
656 + action.label + '" => ' + E + "\n" + E.stack);
659 if ($scope.action_context_showing) $scope.hideActionContextMenu();
664 $scope.hideActionContextMenu = function () {
665 $($scope.menu_dom).css({
667 width: $scope.action_context_width,
668 top: $scope.action_context_y,
669 left: $scope.action_context_x
671 $($scope.action_context_parent).append($scope.menu_dom);
672 $scope.action_context_oldy = $scope.action_context_oldx = 0;
673 $('body').unbind('click.remove_context_menu_'+$scope.action_context_index);
674 $scope.action_context_showing = false;
677 $scope.action_context_showing = false;
678 $scope.showActionContextMenu = function ($event) {
680 // Have to gather these here, instead of inside link()
681 if (!$scope.menu_dom) $scope.menu_dom = $($scope.grid_element).find('.grid-action-dropdown')[0];
682 if (!$scope.action_context_parent) $scope.action_context_parent = $($scope.menu_dom).parent();
684 // we need the index of the row that got right-clicked...
685 var e = $event.target; // the DOM element
686 var s = undefined; // the angular scope for that element
687 while(e){ // searching for the row so we can get its index from s.$index
688 // abort & use the browser default context menu for links (lp1669856):
689 if(e.tagName.toLowerCase() === 'a' && e.href){ return true; }
690 s = angular.element(e).scope();
691 if(s.hasOwnProperty('item')){ break; }
694 /* $scope.items and $scope.selected indexes are "backwards" to each other.
695 $scope.items counts down from the top of the list (most recent item first)
696 $scope.selected counts forward as items are scanned (most recent item last)
697 s.$index is for $scope.items. we need the index for $scope.selected: */
698 var selectable_index = ($scope.items.length-1) - s.$index;
699 // select the right-clicked row if it is not already selected (lp1776557):
700 if(!$scope.selected[selectable_index]){ $event.target.click(); }
702 if (!$scope.action_context_showing) {
703 $scope.action_context_width = $($scope.menu_dom).css('width');
704 $scope.action_context_y = $($scope.menu_dom).css('top');
705 $scope.action_context_x = $($scope.menu_dom).css('left');
706 $scope.action_context_showing = true;
707 $scope.action_context_index = Math.floor((Math.random() * 1000) + 1);
709 $('body').append($($scope.menu_dom));
710 $('body').bind('click.remove_context_menu_'+$scope.action_context_index, $scope.hideActionContextMenu);
713 $($scope.menu_dom).css({
715 width: $scope.action_context_width,
723 // returns the list of selected item objects
724 grid.getSelectedItems = function() {
725 return $scope.items.filter(
727 return Boolean($scope.selected[grid.indexValue(item)]);
732 grid.getItemByIndex = function(index) {
733 for (var i = 0; i < $scope.items.length; i++) {
734 var item = $scope.items[i];
735 if (grid.indexValue(item) == index)
740 // selects one row after deselecting all of the others
741 grid.selectOneItem = function(index) {
742 $scope.selected = {};
743 $scope.selected[index] = true;
746 // selects or deselects an item, without affecting the others.
747 // returns true if the item is selected; false if de-selected.
748 // we overwrite the object so that we can watch $scope.selected
749 grid.toggleSelectOneItem = function(index) {
750 if ($scope.selected[index]) {
751 delete $scope.selected[index];
752 $scope.selected = angular.copy($scope.selected);
755 $scope.selected[index] = true;
756 $scope.selected = angular.copy($scope.selected);
761 $scope.updateSelected = function () {
762 return $scope.selected = angular.copy($scope.selected);
765 grid.selectAllItems = function() {
766 angular.forEach($scope.items, function(item) {
767 $scope.selected[grid.indexValue(item)] = true
769 $scope.selected = angular.copy($scope.selected);
772 $scope.$watch('selectAll', function(newVal) {
774 grid.selectAllItems();
776 $scope.selected = {};
780 if ($scope.onSelect) {
781 $scope.$watch('selected', function(newVal) {
782 $scope.onSelect(grid.getSelectedItems());
783 if ($scope.afterSelect) $scope.afterSelect();
787 // returns true if item1 appears in the list before item2;
788 // false otherwise. this is slightly more efficient that
789 // finding the position of each then comparing them.
790 // item1 / item2 may be an item or an item index
791 grid.itemComesBefore = function(itemOrIndex1, itemOrIndex2) {
792 var idx1 = grid.indexValue(itemOrIndex1);
793 var idx2 = grid.indexValue(itemOrIndex2);
795 // use for() for early exit
796 for (var i = 0; i < $scope.items.length; i++) {
797 var idx = grid.indexValue($scope.items[i]);
798 if (idx == idx1) return true;
799 if (idx == idx2) return false;
804 // 0-based position of item in the current data set
805 grid.indexOf = function(item) {
806 var idx = grid.indexValue(item);
807 for (var i = 0; i < $scope.items.length; i++) {
808 if (grid.indexValue($scope.items[i]) == idx)
814 grid.modifyColumnFlex = function(column, val) {
816 // prevent flex:0; use hiding instead
820 $scope.modifyColumnFlex = function(col, val) {
821 $scope.lastModColumn = col;
822 grid.modifyColumnFlex(col, val);
825 $scope.isLastModifiedColumn = function(col) {
826 if ($scope.lastModColumn)
827 return $scope.lastModColumn === col;
831 grid.modifyColumnPos = function(col, diff) {
832 var srcIdx, targetIdx;
833 angular.forEach(grid.columnsProvider.columns,
834 function(c, i) { if (c.name == col.name) srcIdx = i });
836 targetIdx = srcIdx + diff;
839 } else if (targetIdx >= grid.columnsProvider.columns.length) {
840 // Target index follows the last visible column.
842 angular.forEach(grid.columnsProvider.columns,
843 function(column, idx) {
844 if (column.visible) lastVisible = idx;
848 // When moving a column (down) causes one or more
849 // visible columns to shuffle forward, our column
850 // moves into the slot of the last visible column.
851 // Otherwise, put it into the slot directly following
852 // the last visible column.
854 srcIdx <= lastVisible ? lastVisible : lastVisible + 1;
857 // Splice column out of old position, insert at new position.
858 grid.columnsProvider.columns.splice(srcIdx, 1);
859 grid.columnsProvider.columns.splice(targetIdx, 0, col);
862 $scope.modifyColumnPos = function(col, diff) {
863 $scope.lastModColumn = col;
864 return grid.modifyColumnPos(col, diff);
868 // handles click, control-click, and shift-click
869 $scope.handleRowClick = function($event, item) {
870 var index = grid.indexValue(item);
872 var origSelected = Object.keys($scope.selected);
874 if (!$scope.canMultiSelect) {
875 grid.selectOneItem(index);
876 grid.lastSelectedItemIndex = index;
880 if ($event.ctrlKey || $event.metaKey /* mac command */) {
882 if (grid.toggleSelectOneItem(index))
883 grid.lastSelectedItemIndex = index;
885 } else if ($event.shiftKey) {
888 if (!grid.lastSelectedItemIndex ||
889 index == grid.lastSelectedItemIndex) {
890 grid.selectOneItem(index);
891 grid.lastSelectedItemIndex = index;
895 var selecting = false;
896 var ascending = grid.itemComesBefore(
897 grid.lastSelectedItemIndex, item);
899 grid.indexOf(grid.lastSelectedItemIndex);
901 // update to new last-selected
902 grid.lastSelectedItemIndex = index;
904 // select each row between the last selected and
905 // currently selected items
907 startPos += ascending ? 1 : -1;
908 var curItem = $scope.items[startPos];
910 var curIdx = grid.indexValue(curItem);
911 $scope.selected[curIdx] = true;
912 if (curIdx == index) break; // all done
914 $scope.selected = angular.copy($scope.selected);
918 grid.selectOneItem(index);
919 grid.lastSelectedItemIndex = index;
923 // Builds a sort expression from column sort priorities.
924 // called on page load and any time the priorities are modified.
925 grid.compileSort = function() {
926 var sortList = grid.columnsProvider.columns.filter(
927 function(col) { return Number(col.sort) != 0 }
930 if (Math.abs(a.sort) < Math.abs(b.sort))
936 if (sortList.length) {
937 grid.dataProvider.sort = sortList.map(function(col) {
939 blob[col.name] = col.sort < 0 ? 'desc' : 'asc';
945 // builds a sort expression using a single column,
946 // toggling between ascending and descending sort.
947 $scope.quickSort = function(col_name) {
948 var sort = grid.dataProvider.sort;
949 if (sort && sort.length &&
950 sort[0] == col_name) {
952 blob[col_name] = 'desc';
953 grid.dataProvider.sort = [blob];
955 grid.dataProvider.sort = [col_name];
962 // show / hide the grid configuration row
963 $scope.toggleConfDisplay = function() {
964 if ($scope.showGridConf) {
965 $scope.showGridConf = false;
966 if (grid.columnsProvider.hasSortableColumn()) {
967 // only refresh the grid if the user has the
968 // ability to modify the sort priorities.
974 $scope.showGridConf = true;
977 delete $scope.lastModColumn;
978 $scope.gridColumnPickerIsOpen = false;
981 // called when a dragged column is dropped onto itself
982 // or any other column
983 grid.onColumnDrop = function(target) {
984 if (angular.isUndefined(target)) return;
985 if (target == grid.dragColumn) return;
986 var srcIdx, targetIdx, srcCol;
987 angular.forEach(grid.columnsProvider.columns,
989 if (col.name == grid.dragColumn) {
992 } else if (col.name == target) {
998 if (srcIdx < targetIdx) targetIdx--;
1000 // move src column from old location to new location in
1001 // the columns array, then force a page refresh
1002 grid.columnsProvider.columns.splice(srcIdx, 1);
1003 grid.columnsProvider.columns.splice(targetIdx, 0, srcCol);
1007 // prepares a string for inclusion within a CSV document
1008 // by escaping commas and quotes and removing newlines.
1009 grid.csvDatum = function(str) {
1011 if (!str) return '';
1012 str = str.replace(/\n/g, '');
1013 if (str.match(/\,/) || str.match(/"/)) {
1014 str = str.replace(/"/g, '""');
1015 str = '"' + str + '"';
1020 /** Export the full data set as CSV.
1022 * 1. User clicks the 'download csv' link
1023 * 2. All grid data is retrieved asychronously
1024 * 3. Once all data is all present and CSV-ized, the download
1025 * attributes are linked to the href.
1026 * 4. The href .click() action is prgrammatically fired again,
1027 * telling the browser to download the data, now that the
1028 * data is available for download.
1029 * 5 Once downloaded, the href attributes are reset.
1031 grid.csvExportInProgress = false;
1032 $scope.generateCSVExportURL = function($event) {
1034 if (grid.csvExportInProgress) {
1035 // This is secondary href click handler. Give the
1036 // browser a moment to start the download, then reset
1037 // the CSV download attributes / state.
1040 $scope.csvExportURL = '';
1041 $scope.csvExportFileName = '';
1042 grid.csvExportInProgress = false;
1048 grid.csvExportInProgress = true;
1049 $scope.gridColumnPickerIsOpen = false;
1051 // let the file name describe the grid
1052 $scope.csvExportFileName =
1053 ($scope.mainLabel || grid.persistKey || 'eg_grid_data')
1054 .replace(/\s+/g, '_') + '_' + $scope.page();
1056 // toss the CSV into a Blob and update the export URL
1057 grid.generateCSV().then(function(csv) {
1058 var blob = new Blob([csv], {type : 'text/plain'});
1059 $scope.csvExportURL =
1060 ($window.URL || $window.webkitURL).createObjectURL(blob);
1062 // Fire the 2nd click event now that the browser has
1063 // information on how to download the CSV file.
1064 $timeout(function() {$event.target.click()});
1069 * TODO: does this serve any purpose given we can
1070 * print formatted HTML? If so, generateCSV() now
1071 * returns a promise, needs light refactoring...
1072 $scope.printCSV = function() {
1073 $scope.gridColumnPickerIsOpen = false;
1074 egCore.print.print({
1075 context : 'default',
1076 content : grid.generateCSV(),
1077 content_type : 'text/plain'
1082 // Given a row item and column definition, extract the
1083 // text content for printing. Templated columns must be
1084 // processed and parsed as HTML, then boiled down to their
1086 grid.getItemTextContent = function(item, col) {
1089 val = $scope.translateCellTemplate(col, item);
1091 var node = new DOMParser()
1092 .parseFromString(val, 'text/html');
1093 val = $(node).text();
1096 val = grid.dataProvider.itemFieldValue(item, col);
1097 val = $filter('egGridValueFilter')(val, col, item);
1103 * Fetches all grid data and transates each item into a simple
1104 * key-value pair of column name => text-value.
1105 * Included in the response for convenience is the list of
1106 * currently visible column definitions.
1107 * TODO: currently fetches a maximum of 10k rows. Does this
1108 * need to be configurable?
1110 grid.getAllItemsAsText = function() {
1111 var text_items = [];
1113 // we don't know the total number of rows we're about
1114 // to retrieve, but we can indicate the number retrieved
1115 // so far as each item arrives.
1116 egProgressDialog.open({value : 0});
1118 var visible_cols = grid.columnsProvider.columns.filter(
1119 function(c) { return c.visible });
1121 return grid.dataProvider.get(0, 10000).then(
1123 return {items : text_items, columns : visible_cols};
1127 egProgressDialog.increment();
1129 angular.forEach(visible_cols, function(col) {
1130 text_item[col.name] =
1131 grid.getItemTextContent(item, col);
1133 text_items.push(text_item);
1135 ).finally(egProgressDialog.close);
1138 // Fetch "all" of the grid data, translate it into print-friendly
1139 // text, and send it to the printer service.
1140 $scope.printHTML = function() {
1141 $scope.gridColumnPickerIsOpen = false;
1142 return grid.getAllItemsAsText().then(function(text_items) {
1143 return egCore.print.print({
1144 template : 'grid_html',
1150 $scope.showColumnDialog = function() {
1151 return $uibModal.open({
1152 templateUrl: './share/t_grid_columns',
1155 controller: ['$scope', '$uibModalInstance',
1156 function($dialogScope, $uibModalInstance) {
1157 $dialogScope.modifyColumnPos = $scope.modifyColumnPos;
1158 $dialogScope.disableMultiSort = $scope.disableMultiSort;
1159 $dialogScope.columns = $scope.columns;
1161 // Push visible columns to the top of the list
1162 $dialogScope.elevateVisible = function() {
1164 angular.forEach($dialogScope.columns, function(col) {
1165 if (col.visible) new_cols.push(col);
1167 angular.forEach($dialogScope.columns, function(col) {
1168 if (!col.visible) new_cols.push(col);
1171 // Update all references to the list of columns
1172 $dialogScope.columns =
1174 grid.columnsProvider.columns =
1178 $dialogScope.toggle = function(col) {
1179 col.visible = !Boolean(col.visible);
1181 $dialogScope.ok = $dialogScope.cancel = function() {
1182 delete $scope.lastModColumn;
1183 $uibModalInstance.close()
1190 // generates CSV for the currently visible grid contents
1191 grid.generateCSV = function() {
1192 return grid.getAllItemsAsText().then(function(text_items) {
1193 var columns = text_items.columns;
1194 var items = text_items.items;
1198 angular.forEach(columns, function(col) {
1199 csvStr += grid.csvDatum(col.label);
1203 csvStr = csvStr.replace(/,$/,'\n');
1206 angular.forEach(items, function(item) {
1207 angular.forEach(columns, function(col) {
1208 csvStr += grid.csvDatum(item[col.name]);
1211 csvStr = csvStr.replace(/,$/,'\n');
1218 // Interpolate the value for column.linkpath within the context
1219 // of the row item to generate the final link URL.
1220 $scope.generateLinkPath = function(col, item) {
1221 return egCore.strings.$replace(col.linkpath, {item : item});
1224 // If a column provides its own HTML template, translate it,
1225 // using the current item for the template scope.
1226 // note: $sce is required to avoid security restrictions and
1227 // is OK here, since the template comes directly from a
1228 // local HTML template (not user input).
1229 $scope.translateCellTemplate = function(col, item) {
1230 var html = egCore.strings.$replace(col.template, {item : item});
1231 return $sce.trustAsHtml(html);
1234 $scope.collect = function() { grid.collect() }
1237 $scope.confirmAllowAllAndCollect = function(){
1238 egConfirmDialog.open(egStrings.CONFIRM_LONG_RUNNING_ACTION_ALL_ROWS_TITLE,
1239 egStrings.CONFIRM_LONG_RUNNING_ACTION_MSG)
1243 $scope.limit(10000);
1248 // asks the dataProvider for a page of data
1249 grid.collect = function() {
1251 // avoid firing the collect if there is nothing to collect.
1252 if (grid.selfManagedData && !grid.dataProvider.query) return;
1254 if (grid.collecting) return; // avoid parallel collect()
1255 grid.collecting = true;
1257 console.debug('egGrid.collect() offset='
1258 + grid.offset + '; limit=' + grid.limit);
1260 // ensure all of our dropdowns are closed
1261 // TODO: git rid of these and just use dropdown-toggle,
1262 // which is more reliable.
1263 $scope.gridColumnPickerIsOpen = false;
1264 $scope.gridRowCountIsOpen = false;
1265 $scope.gridPageSelectIsOpen = false;
1268 $scope.selected = {};
1270 // Inform the caller we've asked the data provider
1271 // for data. This is useful for knowing when collection
1272 // has started (e.g. to display a progress dialg) when
1273 // using the stock (flattener) data provider, where the
1274 // user is not directly defining a get() handler.
1275 if (grid.controls.collectStarted)
1276 grid.controls.collectStarted(grid.offset, grid.limit);
1278 grid.dataProvider.get(grid.offset, grid.limit).then(
1280 if (grid.controls.allItemsRetrieved)
1281 grid.controls.allItemsRetrieved();
1286 $scope.items.push(item)
1287 if (grid.controls.itemRetrieved)
1288 grid.controls.itemRetrieved(item);
1289 if ($scope.selectAll)
1290 $scope.selected[grid.indexValue(item)] = true
1292 }).finally(function() {
1293 console.debug('egGrid.collect() complete');
1294 grid.collecting = false
1295 $scope.selected = angular.copy($scope.selected);
1305 * eg-grid-field : used for collecting custom field data from the templates.
1306 * This directive does not direct display, it just passes data up to the
1309 .directive('egGridField', function() {
1311 require : '^egGrid',
1314 flesher: '=', // optional; function that can flesh a linked field, given the value
1315 comparator: '=', // optional; function that can sort the thing at the end of 'path'
1316 name : '@', // required; unique name
1317 path : '@', // optional; flesh path
1318 ignore: '@', // optional; fields to ignore when path is a wildcard
1319 label : '@', // optional; display label
1320 flex : '@', // optional; default flex width
1321 align : '@', // optional; default alignment, left/center/right
1322 dateformat : '@', // optional: passed down to egGridValueFilter
1323 datecontext: '@', // optional: passed down to egGridValueFilter to choose TZ
1324 datefilter: '@', // optional: passed down to egGridValueFilter to choose specialized date filters
1325 dateonlyinterval: '@', // optional: passed down to egGridValueFilter to choose a "better" format
1327 // if a field is part of an IDL object, but we are unable to
1328 // determine the class, because it's nested within a hash
1329 // (i.e. we can't navigate directly to the object via the IDL),
1330 // idlClass lets us specify the class. This is particularly
1331 // useful for nested wildcard fields.
1332 parentIdlClass : '@',
1334 // optional: for non-IDL columns, specifying a datatype
1335 // lets the caller control which display filter is used.
1336 // datatype should match the standard IDL datatypes.
1339 // optional hash of functions that can be imported into
1340 // the directive's scope; meant for cases where the "compiled"
1344 link : function(scope, element, attrs, egGridCtrl) {
1346 // boolean fields are presented as value-less attributes
1356 'required' // if set, always fetch data for this column
1359 if (angular.isDefined(attrs[field]))
1360 scope[field] = true;
1364 // any HTML content within the field is its custom template
1365 var tmpl = element.html();
1366 if (tmpl && !tmpl.match(/^\s*$/))
1367 scope.template = tmpl
1369 egGridCtrl.columnsProvider.add(scope);
1376 * eg-grid-action : used for specifying actions which may be applied
1377 * to items within the grid.
1379 .directive('egGridAction', function() {
1381 require : '^egGrid',
1385 group : '@', // Action group, ungrouped if not set
1386 label : '@', // Action label
1387 handler : '=', // Action function handler
1389 disabled : '=', // function
1392 link : function(scope, element, attrs, egGridCtrl) {
1393 egGridCtrl.addAction({
1395 group : scope.group,
1396 label : scope.label,
1397 divider : scope.divider,
1398 handler : scope.handler,
1399 disabled : scope.disabled,
1406 .factory('egGridColumnsProvider', ['egCore', function(egCore) {
1408 function ColumnsProvider(args) {
1411 cols.stockVisible = [];
1412 cols.idlClass = args.idlClass;
1413 cols.clientSort = args.clientSort;
1414 cols.defaultToHidden = args.defaultToHidden;
1415 cols.defaultToNoSort = args.defaultToNoSort;
1416 cols.defaultToNoMultiSort = args.defaultToNoMultiSort;
1417 cols.defaultDateFormat = args.defaultDateFormat;
1418 cols.defaultDateContext = args.defaultDateContext;
1420 // resets column width, visibility, and sort behavior
1421 // Visibility resets to the visibility settings defined in the
1422 // template (i.e. the original egGridField values).
1423 cols.reset = function() {
1424 angular.forEach(cols.columns, function(col) {
1428 if (cols.stockVisible.indexOf(col.name) > -1) {
1431 col.visible = false;
1436 // returns true if any columns are sortable
1437 cols.hasSortableColumn = function() {
1438 return cols.columns.filter(
1440 return col.sortable || col.multisortable;
1445 cols.showAllColumns = function() {
1446 angular.forEach(cols.columns, function(column) {
1447 column.visible = true;
1451 cols.hideAllColumns = function() {
1452 angular.forEach(cols.columns, function(col) {
1457 cols.indexOf = function(name) {
1458 for (var i = 0; i < cols.columns.length; i++) {
1459 if (cols.columns[i].name == name)
1465 cols.findColumn = function(name) {
1466 return cols.columns[cols.indexOf(name)];
1469 cols.compileAutoColumns = function() {
1470 var idl_class = egCore.idl.classes[cols.idlClass];
1475 if (field.virtual) return;
1476 if (field.datatype == 'link' || field.datatype == 'org_unit') {
1477 // if the field is a link and the linked class has a
1478 // "selector" field specified, use the selector field
1479 // as the display field for the columns.
1480 // flattener will take care of the fleshing.
1481 if (field['class']) {
1482 var selector_field = egCore.idl.classes[field['class']].fields
1483 .filter(function(f) { return Boolean(f.selector) })[0];
1484 if (selector_field) {
1485 field.path = field.name + '.' + selector_field.selector;
1489 cols.add(field, true);
1494 // if a column definition has a path with a wildcard, create
1495 // columns for all non-virtual fields at the specified
1496 // position in the path.
1497 cols.expandPath = function(colSpec) {
1499 var ignoreList = [];
1501 ignoreList = colSpec.ignore.split(' ');
1503 var dotpath = colSpec.path.replace(/\.?\*$/,'');
1507 if (colSpec.parentIdlClass) {
1508 class_obj = egCore.idl.classes[colSpec.parentIdlClass];
1510 class_obj = egCore.idl.classes[cols.idlClass];
1512 var idl_parent = class_obj;
1513 var old_field_label = '';
1515 if (!class_obj) return;
1517 //console.debug('egGrid: auto dotpath is: ' + dotpath);
1518 var path_parts = dotpath.split(/\./);
1520 // find the IDL class definition for the last element in the
1521 // path before the .*
1522 // an empty path_parts means expand the root class
1525 for (var path_idx in path_parts) {
1526 old_field = idl_field;
1528 var part = path_parts[path_idx];
1529 idl_field = class_obj.field_map[part];
1531 // unless we're at the end of the list, this field should
1532 // link to another class.
1533 if (idl_field && idl_field['class'] && (
1534 idl_field.datatype == 'link' ||
1535 idl_field.datatype == 'org_unit')) {
1536 if (old_field_label) old_field_label += ' : ';
1537 old_field_label += idl_field.label;
1538 class_obj = egCore.idl.classes[idl_field['class']];
1539 if (old_field) idl_parent = old_field;
1541 if (path_idx < (path_parts.length - 1)) {
1542 // we ran out of classes to hop through before
1543 // we ran out of path components
1544 console.error("egGrid: invalid IDL path: " + dotpath);
1551 angular.forEach(class_obj.fields, function(field) {
1553 // Only show wildcard fields where we have data to show
1554 // Virtual and un-fleshed links will not have any data.
1555 if (field.virtual ||
1556 (field.datatype == 'link' || field.datatype == 'org_unit') ||
1557 ignoreList.indexOf(field.name) > -1
1561 var col = cols.cloneFromScope(colSpec);
1562 col.path = (dotpath ? dotpath + '.' + field.name : field.name);
1564 // log line below is very chatty. disable until needed.
1565 // console.debug('egGrid: field: ' +field.name + '; parent field: ' + js2JSON(idl_parent));
1566 cols.add(col, false, true,
1567 {idl_parent : idl_parent, idl_field : field, idl_class : class_obj, field_parent_label : old_field_label });
1570 cols.columns = cols.columns.sort(
1572 if (a.explicit) return -1;
1573 if (b.explicit) return 1;
1575 if (a.idlclass && b.idlclass) {
1576 if (a.idlclass < b.idlclass) return -1;
1577 if (b.idlclass < a.idlclass) return 1;
1580 if (a.path && b.path && a.path.lastIndexOf('.') && b.path.lastIndexOf('.')) {
1581 if (a.path.substring(0, a.path.lastIndexOf('.')) < b.path.substring(0, b.path.lastIndexOf('.'))) return -1;
1582 if (b.path.substring(0, b.path.lastIndexOf('.')) < a.path.substring(0, a.path.lastIndexOf('.'))) return 1;
1585 if (a.label && b.label) {
1586 if (a.label < b.label) return -1;
1587 if (b.label < a.label) return 1;
1590 return a.name < b.name ? -1 : 1;
1597 "egGrid: wildcard path does not resolve to an object: "
1602 // angular.clone(scopeObject) is not permittable. Manually copy
1603 // the fields over that we need (so the scope object can go away).
1604 cols.cloneFromScope = function(colSpec) {
1606 flesher : colSpec.flesher,
1607 comparator : colSpec.comparator,
1608 name : colSpec.name,
1609 label : colSpec.label,
1610 path : colSpec.path,
1611 align : colSpec.align || 'left',
1612 flex : Number(colSpec.flex) || 2,
1613 sort : Number(colSpec.sort) || 0,
1614 required : colSpec.required,
1615 linkpath : colSpec.linkpath,
1616 template : colSpec.template,
1617 visible : colSpec.visible,
1618 compiled : colSpec.compiled,
1619 handlers : colSpec.handlers,
1620 hidden : colSpec.hidden,
1621 datatype : colSpec.datatype,
1622 sortable : colSpec.sortable,
1623 nonsortable : colSpec.nonsortable,
1624 multisortable : colSpec.multisortable,
1625 nonmultisortable : colSpec.nonmultisortable,
1626 dateformat : colSpec.dateformat,
1627 datecontext : colSpec.datecontext,
1628 datefilter : colSpec.datefilter,
1629 dateonlyinterval : colSpec.dateonlyinterval,
1630 parentIdlClass : colSpec.parentIdlClass
1635 // Add a column to the columns collection.
1636 // Columns may come from a slim eg-columns-field or
1637 // directly from the IDL.
1638 cols.add = function(colSpec, fromIDL, fromExpand, idl_info) {
1640 // First added column with the specified path takes precedence.
1641 // This allows for specific definitions followed by wildcard
1642 // definitions. If a match is found, back out.
1643 if (cols.columns.filter(function(c) {
1644 return (c.path == colSpec.path) })[0]) {
1645 console.debug('skipping pre-existing column ' + colSpec.path);
1649 var column = fromExpand ? colSpec : cols.cloneFromScope(colSpec);
1651 if (column.path && column.path.match(/\*$/))
1652 return cols.expandPath(colSpec);
1654 if (!fromExpand) column.explicit = true;
1656 if (!column.name) column.name = column.path;
1657 if (!column.path) column.path = column.name;
1659 if (column.visible || (!cols.defaultToHidden && !column.hidden))
1660 column.visible = true;
1662 if (column.sortable || (!cols.defaultToNoSort && !column.nonsortable))
1663 column.sortable = true;
1665 if (column.multisortable ||
1666 (!cols.defaultToNoMultiSort && !column.nonmultisortable))
1667 column.multisortable = true;
1669 if (cols.defaultDateFormat && ! column.dateformat) {
1670 column.dateformat = cols.defaultDateFormat;
1673 if (cols.defaultDateOnlyInterval && ! column.dateonlyinterval) {
1674 column.dateonlyinterval = cols.defaultDateOnlyInterval;
1677 if (cols.defaultDateContext && ! column.datecontext) {
1678 column.datecontext = cols.defaultDateContext;
1681 if (cols.defaultDateFilter && ! column.datefilter) {
1682 column.datefilter = cols.defaultDateFilter;
1685 cols.columns.push(column);
1687 // Track which columns are visible by default in case we
1688 // need to reset column visibility
1690 cols.stockVisible.push(column.name);
1692 if (fromIDL) return; // directly from egIDL. nothing left to do.
1694 // lookup the matching IDL field
1695 if (!idl_info && cols.idlClass)
1696 idl_info = cols.idlFieldFromPath(column.path);
1699 // column is not represented within the IDL
1700 column.adhoc = true;
1704 column.datatype = idl_info.idl_field.datatype;
1706 if (!column.label) {
1707 column.label = idl_info.idl_field.label || column.name;
1710 if (fromExpand && idl_info.idl_class) {
1711 column.idlclass = '';
1712 if (idl_info.field_parent_label && idl_info.idl_parent.label != idl_info.idl_class.label) {
1713 column.idlclass = (idl_info.field_parent_label || idl_info.idl_parent.label || idl_info.idl_parent.name);
1715 column.idlclass += idl_info.idl_class.label || idl_info.idl_class.name;
1720 // finds the IDL field from the dotpath, using the columns
1721 // idlClass as the base.
1722 cols.idlFieldFromPath = function(dotpath) {
1723 var class_obj = egCore.idl.classes[cols.idlClass];
1724 if (!dotpath) return null;
1726 var path_parts = dotpath.split(/\./);
1730 for (var path_idx in path_parts) {
1731 var part = path_parts[path_idx];
1732 idl_parent = idl_field;
1733 idl_field = class_obj.field_map[part];
1736 if (idl_field['class'] && (
1737 idl_field.datatype == 'link' ||
1738 idl_field.datatype == 'org_unit')) {
1739 class_obj = egCore.idl.classes[idl_field['class']];
1747 idl_parent: idl_parent,
1748 idl_field : idl_field,
1749 idl_class : class_obj
1755 instance : function(args) { return new ColumnsProvider(args) }
1761 * Generic data provider template class. This is basically an abstract
1762 * class factory service whose instances can be locally modified to
1763 * meet the needs of each individual grid.
1765 .factory('egGridDataProvider',
1766 ['$q','$timeout','$filter','egCore',
1767 function($q , $timeout , $filter , egCore) {
1769 function GridDataProvider(args) {
1770 var gridData = this;
1771 if (!args) args = {};
1774 gridData.get = args.get;
1775 gridData.query = args.query;
1776 gridData.idlClass = args.idlClass;
1777 gridData.columnsProvider = args.columnsProvider;
1779 // Delivers a stream of array data via promise.notify()
1780 // Useful for passing an array of data to egGrid.get()
1781 // If a count is provided, the array will be trimmed to
1782 // the range defined by count and offset
1783 gridData.arrayNotifier = function(arr, offset, count) {
1784 if (!arr || arr.length == 0) return $q.when();
1786 if (gridData.columnsProvider.clientSort
1788 && gridData.sort.length > 0
1790 var sorter_cache = [];
1791 arr.sort(function(a,b) {
1792 for (var si = 0; si < gridData.sort.length; si++) {
1793 if (!sorter_cache[si]) { // Build sort structure on first comparison, reuse thereafter
1794 var field = gridData.sort[si];
1797 if (angular.isObject(field)) {
1798 dir = Object.values(field)[0];
1799 field = Object.keys(field)[0];
1802 var path = gridData.columnsProvider.findColumn(field).path || field;
1803 var comparator = gridData.columnsProvider.findColumn(field).comparator ||
1804 function (x,y) { if (x < y) return -1; if (x > y) return 1; return 0 };
1806 sorter_cache[si] = {
1809 comparator : comparator
1813 var sc = sorter_cache[si];
1817 if (a._isfieldmapper || angular.isFunction(a[sc.field])) {
1818 try {af = a[sc.field](); bf = b[sc.field]() } catch (e) {};
1820 af = a[sc.field]; bf = b[sc.field];
1822 if (af === undefined && sc.field.indexOf('.') > -1) { // assume an object, not flat path
1823 var parts = sc.field.split('.');
1826 angular.forEach(parts, function (p) {
1828 if (af._isfieldmapper || angular.isFunction(af[p])) af = af[p]();
1832 if (bf._isfieldmapper || angular.isFunction(bf[p])) bf = bf[p]();
1838 if (af === undefined) af = null;
1839 if (bf === undefined) bf = null;
1841 if (af === null && bf !== null) return 1;
1842 if (bf === null && af !== null) return -1;
1844 if (!(bf === null && af === null)) {
1845 var partial = sc.comparator(af,bf);
1847 if (sc.dir == 'desc') {
1848 if (partial > 0) return -1;
1860 if (count) arr = arr.slice(offset, offset + count);
1861 var def = $q.defer();
1862 // promise notifications are only witnessed when delivered
1863 // after the caller has his hands on the promise object
1864 $timeout(function() {
1865 angular.forEach(arr, def.notify);
1871 // Calls the grid refresh function. Once instantiated, the
1872 // grid will replace this function with it's own refresh()
1873 gridData.refresh = function(noReset) { }
1875 if (!gridData.get) {
1876 // returns a promise whose notify() delivers items
1877 gridData.get = function(index, count) {
1878 console.error("egGridDataProvider.get() not implemented");
1882 // attempts a flat field lookup first. If the column is not
1883 // found on the top-level object, attempts a nested lookup
1884 // TODO: consider a caching layer to speed up template
1885 // rendering, particularly for nested objects?
1886 gridData.itemFieldValue = function(item, column) {
1888 if (column.name in item) {
1889 if (typeof item[column.name] == 'function') {
1890 val = item[column.name]();
1892 val = item[column.name];
1895 val = gridData.nestedItemFieldValue(item, column);
1901 // TODO: deprecate me
1902 gridData.flatItemFieldValue = function(item, column) {
1903 console.warn('gridData.flatItemFieldValue deprecated; '
1904 + 'leave provider.itemFieldValue unset');
1905 return item[column.name];
1908 // given an object and a dot-separated path to a field,
1909 // extract the value of the field. The path can refer
1910 // to function names or object attributes. If the final
1911 // value is an IDL field, run the value through its
1912 // corresponding output filter.
1913 gridData.nestedItemFieldValue = function(obj, column) {
1914 item = obj; // keep a copy around
1916 if (obj === null || obj === undefined || obj === '') return '';
1917 if (!column.path) return obj;
1920 var parts = column.path.split('.');
1922 angular.forEach(parts, function(step, idx) {
1923 // object is not fleshed to the expected extent
1924 if (typeof obj != 'object') {
1925 if (typeof obj != 'undefined' && column.flesher) {
1926 obj = column.flesher(obj, column, item);
1933 if (!obj) return '';
1935 var cls = obj.classname;
1936 if (cls && (class_obj = egCore.idl.classes[cls])) {
1937 idl_field = class_obj.field_map[step];
1938 obj = obj[step] ? obj[step]() : '';
1940 if (angular.isFunction(obj[step])) {
1948 // We found a nested IDL object which may or may not have
1949 // been configured as a top-level column. Grab the datatype.
1950 if (idl_field && !column.datatype)
1951 column.datatype = idl_field.datatype;
1953 if (obj === null || obj === undefined || obj === '') return '';
1959 instance : function(args) {
1960 return new GridDataProvider(args);
1967 // Factory service for egGridDataManager instances, which are
1968 // responsible for collecting flattened grid data.
1969 .factory('egGridFlatDataProvider',
1970 ['$q','egCore','egGridDataProvider',
1971 function($q , egCore , egGridDataProvider) {
1974 instance : function(args) {
1975 var provider = egGridDataProvider.instance(args);
1977 provider.get = function(offset, count) {
1979 // no query means no call
1980 if (!provider.query ||
1981 angular.equals(provider.query, {}))
1984 // find all of the currently visible columns
1985 var queryFields = {}
1986 angular.forEach(provider.columnsProvider.columns,
1988 // only query IDL-tracked columns
1989 if (!col.adhoc && col.name && col.path && (col.required || col.visible))
1990 queryFields[col.name] = col.path;
1994 return egCore.net.request(
1996 'open-ils.fielder.flattened_search',
1997 egCore.auth.token(), provider.idlClass,
1998 queryFields, provider.query,
1999 { sort : provider.sort,
2005 //provider.itemFieldValue = provider.flatItemFieldValue;
2012 .directive('egGridColumnDragSource', function() {
2015 require : '^egGrid',
2016 link : function(scope, element, attrs, egGridCtrl) {
2017 angular.element(element).attr('draggable', 'true');
2019 element.bind('dragstart', function(e) {
2020 egGridCtrl.dragColumn = attrs.column;
2021 egGridCtrl.dragType = attrs.dragType || 'move'; // or resize
2022 egGridCtrl.colResizeDir = 0;
2024 if (egGridCtrl.dragType == 'move') {
2025 // style the column getting moved
2026 angular.element(e.target).addClass(
2027 'eg-grid-column-move-handle-active');
2031 element.bind('dragend', function(e) {
2032 if (egGridCtrl.dragType == 'move') {
2033 angular.element(e.target).removeClass(
2034 'eg-grid-column-move-handle-active');
2041 .directive('egGridColumnDragDest', function() {
2044 require : '^egGrid',
2045 link : function(scope, element, attrs, egGridCtrl) {
2047 element.bind('dragover', function(e) { // required for drop
2048 e.stopPropagation();
2050 e.dataTransfer.dropEffect = 'move';
2052 if (egGridCtrl.colResizeDir == 0) return; // move
2054 var cols = egGridCtrl.columnsProvider;
2055 var srcCol = egGridCtrl.dragColumn;
2056 var srcColIdx = cols.indexOf(srcCol);
2058 if (egGridCtrl.colResizeDir == -1) {
2059 if (cols.indexOf(attrs.column) <= srcColIdx) {
2060 egGridCtrl.modifyColumnFlex(
2061 egGridCtrl.columnsProvider.findColumn(
2062 egGridCtrl.dragColumn), -1);
2063 if (cols.columns[srcColIdx+1]) {
2064 // source column shrinks by one, column to the
2065 // right grows by one.
2066 egGridCtrl.modifyColumnFlex(
2067 cols.columns[srcColIdx+1], 1);
2072 if (cols.indexOf(attrs.column) > srcColIdx) {
2073 egGridCtrl.modifyColumnFlex(
2074 egGridCtrl.columnsProvider.findColumn(
2075 egGridCtrl.dragColumn), 1);
2076 if (cols.columns[srcColIdx+1]) {
2077 // source column grows by one, column to the
2078 // right grows by one.
2079 egGridCtrl.modifyColumnFlex(
2080 cols.columns[srcColIdx+1], -1);
2088 element.bind('dragenter', function(e) {
2089 e.stopPropagation();
2091 if (egGridCtrl.dragType == 'move') {
2092 angular.element(e.target).addClass('eg-grid-col-hover');
2094 // resize grips are on the right side of each column.
2095 // dragenter will either occur on the source column
2096 // (dragging left) or the column to the right.
2097 if (egGridCtrl.colResizeDir == 0) {
2098 if (egGridCtrl.dragColumn == attrs.column) {
2099 egGridCtrl.colResizeDir = -1; // west
2101 egGridCtrl.colResizeDir = 1; // east
2107 element.bind('dragleave', function(e) {
2108 e.stopPropagation();
2110 if (egGridCtrl.dragType == 'move') {
2111 angular.element(e.target).removeClass('eg-grid-col-hover');
2115 element.bind('drop', function(e) {
2116 e.stopPropagation();
2118 egGridCtrl.colResizeDir = 0;
2119 if (egGridCtrl.dragType == 'move') {
2120 angular.element(e.target).removeClass('eg-grid-col-hover');
2121 egGridCtrl.onColumnDrop(attrs.column); // move the column
2128 .directive('egGridMenuItem', function() {
2131 require : '^egGrid',
2137 handler : '=', // onclick handler function
2138 divider : '=', // if true, show a divider only
2139 handlerData : '=', // if set, passed as second argument to handler
2140 disabled : '=', // function
2141 hidden : '=' // function
2143 link : function(scope, element, attrs, egGridCtrl) {
2144 egGridCtrl.addMenuItem({
2145 checkbox : scope.checkbox,
2146 checked : scope.checked ? true : false,
2147 label : scope.label,
2148 standalone : scope.standalone ? true : false,
2149 handler : scope.handler,
2150 divider : scope.divider,
2151 disabled : scope.disabled,
2152 hidden : scope.hidden,
2153 handlerData : scope.handlerData
2160 /* https://stackoverflow.com/questions/17343696/adding-an-ng-click-event-inside-a-filter/17344875#17344875 */
2161 .directive('compile', ['$compile', function ($compile) {
2162 return function(scope, element, attrs) {
2163 // pass through column defs from grid cell's scope
2164 scope.col = scope.$parent.col;
2167 // watch the 'compile' expression for changes
2168 return scope.$eval(attrs.compile);
2171 // when the 'compile' expression changes
2172 // assign it into the current DOM
2173 element.html(value);
2175 // compile the new DOM and link it to the current
2177 // NOTE: we only compile .childNodes so that
2178 // we don't get into infinite loop compiling ourselves
2179 $compile(element.contents())(scope);
2188 * Translates bare IDL object values into display values.
2189 * 1. Passes dates through the angular date filter
2190 * 2. Translates bools to Booleans so the browser can display translated
2191 * value. (Though we could manually translate instead..)
2192 * Others likely to follow...
2194 .filter('egGridValueFilter', ['$filter','egCore', function($filter,egCore) {
2195 function traversePath(obj,path) {
2196 var list = path.split('.');
2197 for (var part in path) {
2198 if (obj[path]) obj = obj[path]
2204 var GVF = function(value, column, item) {
2205 switch(column.datatype) {
2208 // Browser will translate true/false for us
2210 case '1' : // legacy
2214 case '0' : // legacy
2217 // value may be null, '', etc.
2218 default : return '';
2221 var interval = angular.isFunction(item[column.dateonlyinterval])
2222 ? item[column.dateonlyinterval]()
2223 : item[column.dateonlyinterval];
2225 if (column.dateonlyinterval && !interval) // try it as a dotted path
2226 interval = traversePath(item, column.dateonlyinterval);
2228 var context = angular.isFunction(item[column.datecontext])
2229 ? item[column.datecontext]()
2230 : item[column.datecontext];
2232 if (column.datecontext && !context) // try it as a dotted path
2233 context = traversePath(item, column.datecontext);
2235 var date_filter = column.datefilter || 'egOrgDateInContext';
2237 return $filter(date_filter)(value, column.dateformat, context, interval);
2239 return $filter('currency')(value);
2245 GVF.$stateful = true;