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;
124 $(element).attr('id', attrs.persistKey);
128 .find('.eg-grid-content-body')
129 .bind('contextmenu', scope.showActionContextMenu);
133 '$scope','$q','egCore','egGridFlatDataProvider','$location',
134 'egGridColumnsProvider','$filter','$window','$sce','$timeout',
135 'egProgressDialog','$uibModal','egConfirmDialog','egStrings',
136 function($scope, $q , egCore, egGridFlatDataProvider , $location,
137 egGridColumnsProvider , $filter , $window , $sce , $timeout,
138 egProgressDialog, $uibModal , egConfirmDialog , egStrings) {
142 grid.init = function() {
145 $scope.showGridConf = false;
146 grid.totalCount = -1;
147 $scope.selected = {};
148 $scope.actionGroups = [{actions:[]}]; // Grouped actions for selected items
149 $scope.menuItems = []; // global actions
151 // returns true if any rows are selected.
152 $scope.hasSelected = function() {
153 return grid.getSelectedItems().length > 0 };
155 var features = ($scope.features) ?
156 $scope.features.split(',') : [];
157 delete $scope.features;
159 $scope.showIndex = (features.indexOf('-index') == -1);
161 $scope.allowAll = (features.indexOf('allowAll') > -1);
162 $scope.startSelected = $scope.selectAll = (features.indexOf('startSelected') > -1);
163 $scope.showActions = (features.indexOf('-actions') == -1);
164 $scope.showPagination = (features.indexOf('-pagination') == -1);
165 $scope.showPicker = (features.indexOf('-picker') == -1);
167 $scope.showMenu = (features.indexOf('-menu') == -1);
169 // remove some unneeded values from the scope to reduce bloat
171 grid.idlClass = $scope.idlClass;
172 delete $scope.idlClass;
174 grid.persistKey = $scope.persistKey;
175 delete $scope.persistKey;
177 var stored_limit = 0;
178 if ($scope.showPagination) {
179 // localStorage of grid limits is deprecated. Limits
180 // are now stored along with the columns configuration.
181 // Values found in localStorage will be migrated upon
183 if (grid.persistKey) {
184 var stored_limit = Number(
185 egCore.hatch.getLocalItem('eg.grid.' + grid.persistKey + '.limit')
189 stored_limit = 10000; // maybe support "Inf"?
192 grid.limit = Number(stored_limit) || Number($scope.pageSize) || 25;
194 grid.indexField = $scope.idField;
195 delete $scope.idField;
197 grid.dataProvider = $scope.itemsProvider;
199 if (!grid.indexField && grid.idlClass)
200 grid.indexField = egCore.idl.classes[grid.idlClass].pkey;
202 grid.columnsProvider = egGridColumnsProvider.instance({
203 idlClass : grid.idlClass,
204 clientSort : (features.indexOf('clientsort') > -1 && features.indexOf('-clientsort') == -1),
205 defaultToHidden : (features.indexOf('-display') > -1),
206 defaultToNoSort : (features.indexOf('-sort') > -1),
207 defaultToNoMultiSort : (features.indexOf('-multisort') > -1),
208 defaultDateFormat : $scope.dateformat,
209 defaultDateContext : $scope.datecontext,
210 defaultDateFilter : $scope.datefilter,
211 defaultDateOnlyInterval : $scope.dateonlyinterval
213 $scope.canMultiSelect = (features.indexOf('-multiselect') == -1);
215 $scope.handleAutoFields = function() {
216 if ($scope.autoFields) {
217 if (grid.autoLabel) {
219 egCore.idl.classes[grid.idlClass].label;
221 grid.columnsProvider.compileAutoColumns();
222 delete $scope.autoFields;
226 if (!grid.dataProvider) {
227 // no provider, um, provided.
228 // Use a flat data provider
230 grid.selfManagedData = true;
231 grid.dataProvider = egGridFlatDataProvider.instance({
232 indexField : grid.indexField,
233 idlClass : grid.idlClass,
234 columnsProvider : grid.columnsProvider,
239 // make grid ref available in get() to set totalCount, if known.
240 // this allows us disable the 'next' paging button correctly
241 grid.dataProvider.grid = grid;
243 grid.dataProvider.columnsProvider = grid.columnsProvider;
245 $scope.itemFieldValue = grid.dataProvider.itemFieldValue;
246 $scope.indexValue = function(item) {
247 return grid.indexValue(item)
250 grid.applyControlFunctions();
252 grid.loadConfig().then(function() {
253 // link columns to scope after loadConfig(), since it
254 // replaces the columns array.
255 $scope.columns = grid.columnsProvider.columns;
258 // NOTE: grid.collect() is first called from link(), not here.
261 // link our control functions into the gridControls
262 // scope object so the caller can access them.
263 grid.applyControlFunctions = function() {
265 // we use some of these controls internally, so sett
266 // them up even if the caller doesn't request them.
267 var controls = $scope.gridControls || {};
269 controls.columnMap = function() {
271 angular.forEach(grid.columnsProvider.columns, function (c) {
277 controls.columnsProvider = function() {
278 return grid.columnsProvider;
281 // link in the control functions
282 controls.selectedItems = function() {
283 return grid.getSelectedItems()
286 controls.selectItemsByValue = function(c,v) {
287 return grid.selectItemsByValue(c,v)
290 controls.allItems = function() {
294 controls.selectItems = function(ids) {
296 $scope.selected = {};
297 angular.forEach(ids, function(i) {
298 $scope.selected[''+i] = true;
302 // if the caller provided a functional setQuery,
303 // extract the value before replacing it
304 if (controls.setQuery) {
305 grid.dataProvider.query =
309 controls.setQuery = function(query) {
310 grid.dataProvider.query = query;
314 if (controls.watchQuery) {
315 // capture the initial query value
316 grid.dataProvider.query = controls.watchQuery();
319 $scope.gridWatchQuery = controls.watchQuery;
320 $scope.$watch('gridWatchQuery()', function(newv) {
321 controls.setQuery(newv);
325 // if the caller provided a functional setSort
326 // extract the value before replacing it
327 grid.dataProvider.sort =
328 controls.setSort ? controls.setSort() : [];
330 controls.setSort = function(sort) {
334 controls.refresh = function(noReset) {
335 if (!noReset) grid.offset = 0;
339 controls.setLimit = function(limit,forget) {
341 if (!forget && grid.persistKey) {
345 controls.getLimit = function() {
348 controls.setOffset = function(offset) {
349 grid.offset = offset;
351 controls.getOffset = function() {
355 controls.saveConfig = function () {
356 return $scope.saveConfig();
359 grid.dataProvider.refresh = controls.refresh;
360 grid.controls = controls;
363 // If a menu item provides its own HTML template, translate it,
364 // using the menu item for the template scope.
365 // note: $sce is required to avoid security restrictions and
366 // is OK here, since the template comes directly from a
367 // local HTML template (not user input).
368 $scope.translateMenuItemTemplate = function(item) {
369 var html = egCore.strings.$replace(item.template, {item : item});
370 return $sce.trustAsHtml(html);
373 // add a new (global) grid menu item
374 grid.addMenuItem = function(item) {
375 $scope.menuItems.push(item);
376 var handler = item.handler;
377 item.handler = function() {
378 $scope.gridMenuIsOpen = false; // close menu
381 item.handlerData, grid.getSelectedItems());
386 // add a selected-items action
387 grid.addAction = function(act) {
389 $scope.actionGroups.forEach(function(g){
390 if (g.label === act.group) {
396 $scope.actionGroups.push({
403 // remove the stored column configuration preferenc, then recover
404 // the column visibility information from the initial page load.
405 $scope.resetColumns = function() {
406 $scope.gridColumnPickerIsOpen = false;
407 egCore.hatch.removeItem('eg.grid.' + grid.persistKey)
409 grid.columnsProvider.reset();
410 if (grid.selfManagedData) grid.collect();
414 $scope.showAllColumns = function() {
415 $scope.gridColumnPickerIsOpen = false;
416 grid.columnsProvider.showAllColumns();
417 if (grid.selfManagedData) grid.collect();
420 $scope.hideAllColumns = function() {
421 $scope.gridColumnPickerIsOpen = false;
422 grid.columnsProvider.hideAllColumns();
423 // note: no need to fetch new data if no columns are visible
426 $scope.toggleColumnVisibility = function(col) {
427 $scope.gridColumnPickerIsOpen = false;
428 col.visible = !col.visible;
430 // egGridFlatDataProvider only retrieves data to be
431 // displayed. When column visibility changes, it's
432 // necessary to fetch the newly visible column data.
433 if (grid.selfManagedData) grid.collect();
436 // save the columns configuration (position, sort, width) to
437 // eg.grid.<persist-key>
438 $scope.saveConfig = function() {
439 $scope.gridColumnPickerIsOpen = false;
441 if (!grid.persistKey) {
443 "Cannot save settings without a grid persist-key");
447 // only store information about visible columns.
448 var cols = grid.columnsProvider.columns.filter(
449 function(col) {return Boolean(col.visible) });
451 // now scrunch the data down to just the needed info
452 cols = cols.map(function(col) {
453 var c = {name : col.name}
454 // Apart from the name, only store non-default values.
455 // No need to store col.visible, since that's implicit
456 if (col.align != 'left') c.align = col.align;
457 if (col.flex != 2) c.flex = col.flex;
458 if (Number(col.sort)) c.sort = Number(c.sort);
468 egCore.hatch.setItem('eg.grid.' + grid.persistKey, conf)
470 // Save operation performed from the grid configuration UI.
471 // Hide the configuration UI and re-draw w/ sort applied
472 if ($scope.showGridConf)
473 $scope.toggleConfDisplay();
475 // Once a version-2 grid config is saved (with limit
476 // included) we can remove the local limit pref.
477 egCore.hatch.removeLocalItem(
478 'eg.grid.' + grid.persistKey + '.limit');
483 // load the columns configuration (position, sort, width) from
484 // eg.grid.<persist-key> and apply the loaded settings to the
485 // columns on our columnsProvider
486 grid.loadConfig = function() {
487 if (!grid.persistKey) return $q.when();
489 return egCore.hatch.getItem('eg.grid.' + grid.persistKey)
490 .then(function(conf) {
493 var columns = grid.columnsProvider.columns;
496 if (Array.isArray(conf)) {
498 'upgrading version 1 grid config to version 2');
506 grid.limit = Number(conf.limit);
509 angular.forEach(conf.columns, function(col) {
510 var grid_col = columns.filter(
511 function(c) {return c.name == col.name})[0];
514 // saved column does not match a column in the
515 // current grid. skip it.
519 grid_col.align = col.align || 'left';
520 grid_col.flex = col.flex || 2;
521 grid_col.sort = col.sort || 0;
522 // all saved columns are assumed to be true
523 grid_col.visible = true;
525 .filter(function (c) {
526 return c.name == grid_col.name;
529 new_cols.push(grid_col);
532 // columns which are not expressed within the saved
533 // configuration are marked as non-visible and
534 // appended to the end of the new list of columns.
535 angular.forEach(columns, function(col) {
536 var found = conf.columns.filter(
537 function(c) {return (c.name == col.name)})[0];
544 grid.columnsProvider.columns = new_cols;
550 $scope.onContextMenu = function($event) {
551 var col = angular.element($event.target).attr('column');
552 console.log('selected column ' + col);
555 $scope.page = function() {
556 return (grid.offset / grid.limit) + 1;
559 $scope.goToPage = function(page) {
561 if (angular.isNumber(page) && page > 0) {
562 grid.offset = (page - 1) * grid.limit;
567 $scope.offset = function(o) {
568 if (angular.isNumber(o))
573 $scope.limit = function(l) {
574 if (angular.isNumber(l)) {
576 if (grid.persistKey) {
583 $scope.onFirstPage = function() {
584 return grid.offset == 0;
587 $scope.hasNextPage = function() {
588 // we have less data than requested, there must
589 // not be any more pages
590 if (grid.count() < grid.limit) return false;
592 // if the total count is not known, assume that a full
593 // page of data implies more pages are available.
594 if (grid.totalCount == -1) return true;
596 // we have a full page of data, but is there more?
597 return grid.totalCount > (grid.offset + grid.count());
600 $scope.incrementPage = function() {
601 grid.offset += grid.limit;
605 $scope.decrementPage = function() {
606 if (grid.offset < grid.limit) {
609 grid.offset -= grid.limit;
614 // number of items loaded for the current page of results
615 grid.count = function() {
616 return $scope.items.length;
619 // returns the unique identifier value for the provided item
620 // for internal consistency, indexValue is always coerced
622 grid.indexValue = function(item) {
623 if (angular.isObject(item)) {
625 if (angular.isFunction(item[grid.indexField]))
626 return ''+item[grid.indexField]();
627 return ''+item[grid.indexField]; // flat data
630 // passed a non-object; assume it's an index
634 // fires the hide handler function for a context action
635 $scope.actionHide = function(action) {
636 if (typeof action.hide == 'undefined') {
639 if (angular.isFunction(action.hide))
640 return action.hide(action);
644 // fires the disable handler function for a context action
645 $scope.actionDisable = function(action) {
646 if (typeof action.disabled == 'undefined') {
649 if (angular.isFunction(action.disabled))
650 return action.disabled(action);
651 return action.disabled;
654 // fires the action handler function for a context action
655 $scope.actionLauncher = function(action) {
656 if (!action.handler) {
658 'No handler specified for "' + action.label + '"');
662 action.handler(grid.getSelectedItems());
664 console.error('Error executing handler for "'
665 + action.label + '" => ' + E + "\n" + E.stack);
668 if ($scope.action_context_showing) $scope.hideActionContextMenu();
673 $scope.hideActionContextMenu = function () {
674 $($scope.menu_dom).css({
676 width: $scope.action_context_width,
677 top: $scope.action_context_y,
678 left: $scope.action_context_x
680 $($scope.action_context_parent).append($scope.menu_dom);
681 $scope.action_context_oldy = $scope.action_context_oldx = 0;
682 $('body').unbind('click.remove_context_menu_'+$scope.action_context_index);
683 $scope.action_context_showing = false;
686 $scope.action_context_showing = false;
687 $scope.showActionContextMenu = function ($event) {
689 // Have to gather these here, instead of inside link()
690 if (!$scope.menu_dom) $scope.menu_dom = $($scope.grid_element).find('.grid-action-dropdown')[0];
691 if (!$scope.action_context_parent) $scope.action_context_parent = $($scope.menu_dom).parent();
693 // we need the the row that got right-clicked...
694 var e = $event.target; // the DOM element
695 var s = undefined; // the angular scope for that element
696 while(e){ // searching for the row
697 // abort & use the browser default context menu for links (lp1669856):
698 if(e.tagName.toLowerCase() === 'a' && e.href){ return true; }
699 s = angular.element(e).scope();
700 if(s.hasOwnProperty('item')){ break; }
703 // select the right-clicked row if it is not already selected (lp1776557):
704 if(!$scope.selected[grid.indexValue(s.item)]){ $event.target.click(); }
706 if (!$scope.action_context_showing) {
707 $scope.action_context_width = $($scope.menu_dom).css('width');
708 $scope.action_context_y = $($scope.menu_dom).css('top');
709 $scope.action_context_x = $($scope.menu_dom).css('left');
710 $scope.action_context_showing = true;
711 $scope.action_context_index = Math.floor((Math.random() * 1000) + 1);
713 $('body').append($($scope.menu_dom));
714 $('body').bind('click.remove_context_menu_'+$scope.action_context_index, $scope.hideActionContextMenu);
717 $($scope.menu_dom).css({
719 width: $scope.action_context_width,
727 // returns the list of selected item objects
728 grid.getSelectedItems = function() {
729 return $scope.items.filter(
731 return Boolean($scope.selected[grid.indexValue(item)]);
736 grid.getItemByIndex = function(index) {
737 for (var i = 0; i < $scope.items.length; i++) {
738 var item = $scope.items[i];
739 if (grid.indexValue(item) == index)
744 // selects one row after deselecting all of the others
745 grid.selectOneItem = function(index) {
746 $scope.selected = {};
747 $scope.selected[index] = true;
750 // selects items by a column value, first clearing selected list.
751 // we overwrite the object so that we can watch $scope.selected
752 grid.selectItemsByValue = function(column, value) {
753 $scope.selected = {};
754 angular.forEach($scope.items, function(item) {
756 if (angular.isFunction(item[column]))
757 col_value = item[column]();
759 col_value = item[column];
761 if (value == col_value) $scope.selected[grid.indexValue(item)] = true
765 // selects or deselects an item, without affecting the others.
766 // returns true if the item is selected; false if de-selected.
767 // we overwrite the object so that we can watch $scope.selected
768 grid.toggleSelectOneItem = function(index) {
769 if ($scope.selected[index]) {
770 delete $scope.selected[index];
771 $scope.selected = angular.copy($scope.selected);
774 $scope.selected[index] = true;
775 $scope.selected = angular.copy($scope.selected);
780 $scope.updateSelected = function () {
781 return $scope.selected = angular.copy($scope.selected);
784 grid.selectAllItems = function() {
785 angular.forEach($scope.items, function(item) {
786 $scope.selected[grid.indexValue(item)] = true
788 $scope.selected = angular.copy($scope.selected);
791 $scope.$watch('selectAll', function(newVal) {
793 grid.selectAllItems();
795 $scope.selected = {};
799 if ($scope.onSelect) {
800 $scope.$watch('selected', function(newVal) {
801 $scope.onSelect(grid.getSelectedItems());
802 if ($scope.afterSelect) $scope.afterSelect();
806 // returns true if item1 appears in the list before item2;
807 // false otherwise. this is slightly more efficient that
808 // finding the position of each then comparing them.
809 // item1 / item2 may be an item or an item index
810 grid.itemComesBefore = function(itemOrIndex1, itemOrIndex2) {
811 var idx1 = grid.indexValue(itemOrIndex1);
812 var idx2 = grid.indexValue(itemOrIndex2);
814 // use for() for early exit
815 for (var i = 0; i < $scope.items.length; i++) {
816 var idx = grid.indexValue($scope.items[i]);
817 if (idx == idx1) return true;
818 if (idx == idx2) return false;
823 // 0-based position of item in the current data set
824 grid.indexOf = function(item) {
825 var idx = grid.indexValue(item);
826 for (var i = 0; i < $scope.items.length; i++) {
827 if (grid.indexValue($scope.items[i]) == idx)
833 grid.modifyColumnFlex = function(column, val) {
835 // prevent flex:0; use hiding instead
839 $scope.modifyColumnFlex = function(col, val) {
840 $scope.lastModColumn = col;
841 grid.modifyColumnFlex(col, val);
844 $scope.isLastModifiedColumn = function(col) {
845 if ($scope.lastModColumn)
846 return $scope.lastModColumn === col;
850 grid.modifyColumnPos = function(col, diff) {
851 var srcIdx, targetIdx;
852 angular.forEach(grid.columnsProvider.columns,
853 function(c, i) { if (c.name == col.name) srcIdx = i });
855 targetIdx = srcIdx + diff;
858 } else if (targetIdx >= grid.columnsProvider.columns.length) {
859 // Target index follows the last visible column.
861 angular.forEach(grid.columnsProvider.columns,
862 function(column, idx) {
863 if (column.visible) lastVisible = idx;
867 // When moving a column (down) causes one or more
868 // visible columns to shuffle forward, our column
869 // moves into the slot of the last visible column.
870 // Otherwise, put it into the slot directly following
871 // the last visible column.
873 srcIdx <= lastVisible ? lastVisible : lastVisible + 1;
876 // Splice column out of old position, insert at new position.
877 grid.columnsProvider.columns.splice(srcIdx, 1);
878 grid.columnsProvider.columns.splice(targetIdx, 0, col);
881 $scope.modifyColumnPos = function(col, diff) {
882 $scope.lastModColumn = col;
883 return grid.modifyColumnPos(col, diff);
886 // Returns true of the contents of the cell overflow its container.
887 // parentDepth tells the code how far up the DOM tree to traverse
888 // via parentNode before stopping to inspect the value.
889 // There's no way to pass a reference to a DOM node directly via
890 // a scope function (except ng-click, etc.) so pass the
891 // DOM id instead and get the node from there.
892 $scope.cellOverflowed = function(id, parentDepth) {
893 var node = document.getElementById(id);
895 for (var i = 0; i < parentDepth; i++) {
896 node = node.parentNode;
898 return node.scrollHeight > node.clientHeight
899 || node.scrollWidth > node.clientWidth;
902 // Generates a unique identifier per cell per grid.
903 $scope.cellId = function(col, item) {
904 if (!col || !item) return '';
905 return 'grid-cell-span-'
906 // differentiate grids
907 + ($scope.persistKey || $scope.idlClass || $scope.grid_element.id)
908 // differentiate rows and columns.
909 + '-' + col.name + '-' + $scope.indexValue(item);
913 // handles click, control-click, and shift-click
914 $scope.handleRowClick = function($event, item) {
915 var index = grid.indexValue(item);
917 var origSelected = Object.keys($scope.selected);
919 if (!$scope.canMultiSelect) {
920 grid.selectOneItem(index);
921 grid.lastSelectedItemIndex = index;
925 if ($event.ctrlKey || $event.metaKey /* mac command */) {
927 if (grid.toggleSelectOneItem(index))
928 grid.lastSelectedItemIndex = index;
930 } else if ($event.shiftKey) {
933 if (!grid.lastSelectedItemIndex ||
934 index == grid.lastSelectedItemIndex) {
935 grid.selectOneItem(index);
936 grid.lastSelectedItemIndex = index;
940 var selecting = false;
941 var ascending = grid.itemComesBefore(
942 grid.lastSelectedItemIndex, item);
944 grid.indexOf(grid.lastSelectedItemIndex);
946 // update to new last-selected
947 grid.lastSelectedItemIndex = index;
949 // select each row between the last selected and
950 // currently selected items
952 startPos += ascending ? 1 : -1;
953 var curItem = $scope.items[startPos];
955 var curIdx = grid.indexValue(curItem);
956 $scope.selected[curIdx] = true;
957 if (curIdx == index) break; // all done
959 $scope.selected = angular.copy($scope.selected);
963 grid.selectOneItem(index);
964 grid.lastSelectedItemIndex = index;
968 // Builds a sort expression from column sort priorities.
969 // called on page load and any time the priorities are modified.
970 grid.compileSort = function() {
971 var sortList = grid.columnsProvider.columns.filter(
972 function(col) { return Number(col.sort) != 0 }
975 if (Math.abs(a.sort) < Math.abs(b.sort))
981 if (sortList.length) {
982 grid.dataProvider.sort = sortList.map(function(col) {
984 blob[col.name] = col.sort < 0 ? 'desc' : 'asc';
990 // builds a sort expression using a single column,
991 // toggling between ascending and descending sort.
992 $scope.quickSort = function(col_name) {
993 var sort = grid.dataProvider.sort;
994 if (sort && sort.length &&
995 sort[0] == col_name) {
997 blob[col_name] = 'desc';
998 grid.dataProvider.sort = [blob];
1000 grid.dataProvider.sort = [col_name];
1007 // show / hide the grid configuration row
1008 $scope.toggleConfDisplay = function() {
1009 if ($scope.showGridConf) {
1010 $scope.showGridConf = false;
1011 if (grid.columnsProvider.hasSortableColumn()) {
1012 // only refresh the grid if the user has the
1013 // ability to modify the sort priorities.
1019 $scope.showGridConf = true;
1022 delete $scope.lastModColumn;
1023 $scope.gridColumnPickerIsOpen = false;
1026 // called when a dragged column is dropped onto itself
1027 // or any other column
1028 grid.onColumnDrop = function(target) {
1029 if (angular.isUndefined(target)) return;
1030 if (target == grid.dragColumn) return;
1031 var srcIdx, targetIdx, srcCol;
1032 angular.forEach(grid.columnsProvider.columns,
1033 function(col, idx) {
1034 if (col.name == grid.dragColumn) {
1037 } else if (col.name == target) {
1043 if (srcIdx < targetIdx) targetIdx--;
1045 // move src column from old location to new location in
1046 // the columns array, then force a page refresh
1047 grid.columnsProvider.columns.splice(srcIdx, 1);
1048 grid.columnsProvider.columns.splice(targetIdx, 0, srcCol);
1052 // prepares a string for inclusion within a CSV document
1053 // by escaping commas and quotes and removing newlines.
1054 grid.csvDatum = function(str) {
1056 if (!str) return '';
1057 str = str.replace(/\n/g, '');
1058 if (str.match(/\,/) || str.match(/"/)) {
1059 str = str.replace(/"/g, '""');
1060 str = '"' + str + '"';
1065 /** Export the full data set as CSV.
1067 * 1. User clicks the 'download csv' link
1068 * 2. All grid data is retrieved asychronously
1069 * 3. Once all data is all present and CSV-ized, the download
1070 * attributes are linked to the href.
1071 * 4. The href .click() action is prgrammatically fired again,
1072 * telling the browser to download the data, now that the
1073 * data is available for download.
1074 * 5 Once downloaded, the href attributes are reset.
1076 grid.csvExportInProgress = false;
1077 $scope.generateCSVExportURL = function($event) {
1079 if (grid.csvExportInProgress) {
1080 // This is secondary href click handler. Give the
1081 // browser a moment to start the download, then reset
1082 // the CSV download attributes / state.
1085 $scope.csvExportURL = '';
1086 $scope.csvExportFileName = '';
1087 grid.csvExportInProgress = false;
1093 grid.csvExportInProgress = true;
1094 $scope.gridColumnPickerIsOpen = false;
1096 // let the file name describe the grid
1097 $scope.csvExportFileName =
1098 ($scope.mainLabel || grid.persistKey || 'eg_grid_data')
1099 .replace(/\s+/g, '_') + '_' + $scope.page();
1101 // toss the CSV into a Blob and update the export URL
1102 grid.generateCSV().then(function(csv) {
1103 var blob = new Blob([csv], {type : 'text/plain'});
1104 $scope.csvExportURL =
1105 ($window.URL || $window.webkitURL).createObjectURL(blob);
1107 // Fire the 2nd click event now that the browser has
1108 // information on how to download the CSV file.
1109 $timeout(function() {$event.target.click()});
1114 * TODO: does this serve any purpose given we can
1115 * print formatted HTML? If so, generateCSV() now
1116 * returns a promise, needs light refactoring...
1117 $scope.printCSV = function() {
1118 $scope.gridColumnPickerIsOpen = false;
1119 egCore.print.print({
1120 context : 'default',
1121 content : grid.generateCSV(),
1122 content_type : 'text/plain'
1127 // Given a row item and column definition, extract the
1128 // text content for printing. Templated columns must be
1129 // processed and parsed as HTML, then boiled down to their
1131 grid.getItemTextContent = function(item, col) {
1134 val = $scope.translateCellTemplate(col, item);
1136 var node = new DOMParser()
1137 .parseFromString(val, 'text/html');
1138 val = $(node).text();
1141 val = grid.dataProvider.itemFieldValue(item, col);
1142 val = $filter('egGridValueFilter')(val, col, item);
1147 $scope.getHtmlTooltip = function(col, item) {
1148 if ($scope.cellOverflowed($scope.cellId(col, item), 1)) {
1149 return grid.getItemTextContent(item, col);
1155 * Fetches all grid data and transates each item into a simple
1156 * key-value pair of column name => text-value.
1157 * Included in the response for convenience is the list of
1158 * currently visible column definitions.
1159 * TODO: currently fetches a maximum of 10k rows. Does this
1160 * need to be configurable?
1162 grid.getAllItemsAsText = function() {
1163 var text_items = [];
1165 // we don't know the total number of rows we're about
1166 // to retrieve, but we can indicate the number retrieved
1167 // so far as each item arrives.
1168 egProgressDialog.open({value : 0});
1170 var visible_cols = grid.columnsProvider.columns.filter(
1171 function(c) { return c.visible });
1173 return grid.dataProvider.get(0, 10000).then(
1175 return {items : text_items, columns : visible_cols};
1179 egProgressDialog.increment();
1181 angular.forEach(visible_cols, function(col) {
1182 text_item[col.name] =
1183 grid.getItemTextContent(item, col);
1185 text_items.push(text_item);
1187 ).finally(egProgressDialog.close);
1190 // Fetch "all" of the grid data, translate it into print-friendly
1191 // text, and send it to the printer service.
1192 $scope.printHTML = function() {
1193 $scope.gridColumnPickerIsOpen = false;
1194 return grid.getAllItemsAsText().then(function(text_items) {
1195 return egCore.print.print({
1196 template : 'grid_html',
1202 $scope.showColumnDialog = function() {
1203 return $uibModal.open({
1204 templateUrl: './share/t_grid_columns',
1207 controller: ['$scope', '$uibModalInstance',
1208 function($dialogScope, $uibModalInstance) {
1209 $dialogScope.modifyColumnPos = $scope.modifyColumnPos;
1210 $dialogScope.disableMultiSort = $scope.disableMultiSort;
1211 $dialogScope.columns = $scope.columns;
1213 // Push visible columns to the top of the list
1214 $dialogScope.elevateVisible = function() {
1216 angular.forEach($dialogScope.columns, function(col) {
1217 if (col.visible) new_cols.push(col);
1219 angular.forEach($dialogScope.columns, function(col) {
1220 if (!col.visible) new_cols.push(col);
1223 // Update all references to the list of columns
1224 $dialogScope.columns =
1226 grid.columnsProvider.columns =
1230 $dialogScope.toggle = function(col) {
1231 col.visible = !Boolean(col.visible);
1233 $dialogScope.ok = $dialogScope.cancel = function() {
1234 delete $scope.lastModColumn;
1235 $uibModalInstance.close()
1242 // generates CSV for the currently visible grid contents
1243 grid.generateCSV = function() {
1244 return grid.getAllItemsAsText().then(function(text_items) {
1245 var columns = text_items.columns;
1246 var items = text_items.items;
1250 angular.forEach(columns, function(col) {
1251 csvStr += grid.csvDatum(col.label);
1255 csvStr = csvStr.replace(/,$/,'\n');
1258 angular.forEach(items, function(item) {
1259 angular.forEach(columns, function(col) {
1260 csvStr += grid.csvDatum(item[col.name]);
1263 csvStr = csvStr.replace(/,$/,'\n');
1270 // Interpolate the value for column.linkpath within the context
1271 // of the row item to generate the final link URL.
1272 $scope.generateLinkPath = function(col, item) {
1273 return egCore.strings.$replace(col.linkpath, {item : item});
1276 // If a column provides its own HTML template, translate it,
1277 // using the current item for the template scope.
1278 // note: $sce is required to avoid security restrictions and
1279 // is OK here, since the template comes directly from a
1280 // local HTML template (not user input).
1281 $scope.translateCellTemplate = function(col, item) {
1282 var html = egCore.strings.$replace(col.template, {item : item});
1283 return $sce.trustAsHtml(html);
1286 $scope.collect = function() { grid.collect() }
1289 $scope.confirmAllowAllAndCollect = function(){
1290 egConfirmDialog.open(egStrings.CONFIRM_LONG_RUNNING_ACTION_ALL_ROWS_TITLE,
1291 egStrings.CONFIRM_LONG_RUNNING_ACTION_MSG)
1295 $scope.limit(10000);
1300 // asks the dataProvider for a page of data
1301 grid.collect = function() {
1303 // avoid firing the collect if there is nothing to collect.
1304 if (grid.selfManagedData && !grid.dataProvider.query) return;
1306 if (grid.collecting) return; // avoid parallel collect()
1307 grid.collecting = true;
1309 console.debug('egGrid.collect() offset='
1310 + grid.offset + '; limit=' + grid.limit);
1312 // ensure all of our dropdowns are closed
1313 // TODO: git rid of these and just use dropdown-toggle,
1314 // which is more reliable.
1315 $scope.gridColumnPickerIsOpen = false;
1316 $scope.gridRowCountIsOpen = false;
1317 $scope.gridPageSelectIsOpen = false;
1320 $scope.selected = {};
1322 // Inform the caller we've asked the data provider
1323 // for data. This is useful for knowing when collection
1324 // has started (e.g. to display a progress dialg) when
1325 // using the stock (flattener) data provider, where the
1326 // user is not directly defining a get() handler.
1327 if (grid.controls.collectStarted)
1328 grid.controls.collectStarted(grid.offset, grid.limit);
1330 grid.dataProvider.get(grid.offset, grid.limit).then(
1332 if (grid.controls.allItemsRetrieved)
1333 grid.controls.allItemsRetrieved();
1338 $scope.items.push(item)
1339 if (grid.controls.itemRetrieved)
1340 grid.controls.itemRetrieved(item);
1341 if ($scope.selectAll)
1342 $scope.selected[grid.indexValue(item)] = true
1344 }).finally(function() {
1345 console.debug('egGrid.collect() complete');
1346 grid.collecting = false
1347 $scope.selected = angular.copy($scope.selected);
1357 * eg-grid-field : used for collecting custom field data from the templates.
1358 * This directive does not direct display, it just passes data up to the
1361 .directive('egGridField', function() {
1363 require : '^egGrid',
1366 flesher: '=', // optional; function that can flesh a linked field, given the value
1367 comparator: '=', // optional; function that can sort the thing at the end of 'path'
1368 name : '@', // required; unique name
1369 path : '@', // optional; flesh path
1370 ignore: '@', // optional; fields to ignore when path is a wildcard
1371 label : '@', // optional; display label
1372 flex : '@', // optional; default flex width
1373 align : '@', // optional; default alignment, left/center/right
1374 dateformat : '@', // optional: passed down to egGridValueFilter
1375 datecontext: '@', // optional: passed down to egGridValueFilter to choose TZ
1376 datefilter: '@', // optional: passed down to egGridValueFilter to choose specialized date filters
1377 dateonlyinterval: '@', // optional: passed down to egGridValueFilter to choose a "better" format
1379 // if a field is part of an IDL object, but we are unable to
1380 // determine the class, because it's nested within a hash
1381 // (i.e. we can't navigate directly to the object via the IDL),
1382 // idlClass lets us specify the class. This is particularly
1383 // useful for nested wildcard fields.
1384 parentIdlClass : '@',
1386 // optional: for non-IDL columns, specifying a datatype
1387 // lets the caller control which display filter is used.
1388 // datatype should match the standard IDL datatypes.
1391 // optional hash of functions that can be imported into
1392 // the directive's scope; meant for cases where the "compiled"
1396 // optional: CSS class name that we want to have for this field.
1397 // Auto generated from path if nothing is passed in via eg-grid-field declaration
1400 link : function(scope, element, attrs, egGridCtrl) {
1402 // boolean fields are presented as value-less attributes
1412 'required' // if set, always fetch data for this column
1415 if (angular.isDefined(attrs[field]))
1416 scope[field] = true;
1420 scope.cssSelector = attrs['cssSelector'] ? attrs['cssSelector'] : "";
1422 // auto-generate CSS selector name for field if none declared in tt2 and there's a path
1423 if (scope.path && !scope.cssSelector){
1424 var cssClass = 'grid' + "." + scope.path;
1425 cssClass = cssClass.replace(/\./g,'-');
1426 element.addClass(cssClass);
1427 scope.cssSelector = cssClass;
1430 // any HTML content within the field is its custom template
1431 var tmpl = element.html();
1432 if (tmpl && !tmpl.match(/^\s*$/))
1433 scope.template = tmpl
1435 egGridCtrl.columnsProvider.add(scope);
1442 * eg-grid-action : used for specifying actions which may be applied
1443 * to items within the grid.
1445 .directive('egGridAction', function() {
1447 require : '^egGrid',
1451 group : '@', // Action group, ungrouped if not set
1452 label : '@', // Action label
1453 handler : '=', // Action function handler
1455 disabled : '=', // function
1458 link : function(scope, element, attrs, egGridCtrl) {
1459 egGridCtrl.addAction({
1461 group : scope.group,
1462 label : scope.label,
1463 divider : scope.divider,
1464 handler : scope.handler,
1465 disabled : scope.disabled,
1472 .factory('egGridColumnsProvider', ['egCore', function(egCore) {
1474 function ColumnsProvider(args) {
1477 cols.stockVisible = [];
1478 cols.idlClass = args.idlClass;
1479 cols.clientSort = args.clientSort;
1480 cols.defaultToHidden = args.defaultToHidden;
1481 cols.defaultToNoSort = args.defaultToNoSort;
1482 cols.defaultToNoMultiSort = args.defaultToNoMultiSort;
1483 cols.defaultDateFormat = args.defaultDateFormat;
1484 cols.defaultDateContext = args.defaultDateContext;
1486 // resets column width, visibility, and sort behavior
1487 // Visibility resets to the visibility settings defined in the
1488 // template (i.e. the original egGridField values).
1489 cols.reset = function() {
1490 angular.forEach(cols.columns, function(col) {
1494 if (cols.stockVisible.indexOf(col.name) > -1) {
1497 col.visible = false;
1502 // returns true if any columns are sortable
1503 cols.hasSortableColumn = function() {
1504 return cols.columns.filter(
1506 return col.sortable || col.multisortable;
1511 cols.showAllColumns = function() {
1512 angular.forEach(cols.columns, function(column) {
1513 column.visible = true;
1517 cols.hideAllColumns = function() {
1518 angular.forEach(cols.columns, function(col) {
1523 cols.indexOf = function(name) {
1524 for (var i = 0; i < cols.columns.length; i++) {
1525 if (cols.columns[i].name == name)
1531 cols.findColumn = function(name) {
1532 return cols.columns[cols.indexOf(name)];
1535 cols.compileAutoColumns = function() {
1536 var idl_class = egCore.idl.classes[cols.idlClass];
1541 if (field.virtual) return;
1542 if (field.datatype == 'link' || field.datatype == 'org_unit') {
1543 // if the field is a link and the linked class has a
1544 // "selector" field specified, use the selector field
1545 // as the display field for the columns.
1546 // flattener will take care of the fleshing.
1547 if (field['class']) {
1548 var selector_field = egCore.idl.classes[field['class']].fields
1549 .filter(function(f) { return Boolean(f.selector) })[0];
1550 if (selector_field) {
1551 field.path = field.name + '.' + selector_field.selector;
1555 cols.add(field, true);
1560 // if a column definition has a path with a wildcard, create
1561 // columns for all non-virtual fields at the specified
1562 // position in the path.
1563 cols.expandPath = function(colSpec) {
1565 var ignoreList = [];
1567 ignoreList = colSpec.ignore.split(' ');
1569 var dotpath = colSpec.path.replace(/\.?\*$/,'');
1573 if (colSpec.parentIdlClass) {
1574 class_obj = egCore.idl.classes[colSpec.parentIdlClass];
1576 class_obj = egCore.idl.classes[cols.idlClass];
1578 var idl_parent = class_obj;
1579 var old_field_label = '';
1581 if (!class_obj) return;
1583 //console.debug('egGrid: auto dotpath is: ' + dotpath);
1584 var path_parts = dotpath.split(/\./);
1586 // find the IDL class definition for the last element in the
1587 // path before the .*
1588 // an empty path_parts means expand the root class
1591 for (var path_idx in path_parts) {
1592 old_field = idl_field;
1594 var part = path_parts[path_idx];
1595 idl_field = class_obj.field_map[part];
1597 // unless we're at the end of the list, this field should
1598 // link to another class.
1599 if (idl_field && idl_field['class'] && (
1600 idl_field.datatype == 'link' ||
1601 idl_field.datatype == 'org_unit')) {
1602 if (old_field_label) old_field_label += ' : ';
1603 old_field_label += idl_field.label;
1604 class_obj = egCore.idl.classes[idl_field['class']];
1605 if (old_field) idl_parent = old_field;
1607 if (path_idx < (path_parts.length - 1)) {
1608 // we ran out of classes to hop through before
1609 // we ran out of path components
1610 console.error("egGrid: invalid IDL path: " + dotpath);
1617 angular.forEach(class_obj.fields, function(field) {
1619 // Only show wildcard fields where we have data to show
1620 // Virtual and un-fleshed links will not have any data.
1621 if (field.virtual ||
1622 (field.datatype == 'link' || field.datatype == 'org_unit') ||
1623 ignoreList.indexOf(field.name) > -1
1627 var col = cols.cloneFromScope(colSpec);
1628 col.path = (dotpath ? dotpath + '.' + field.name : field.name);
1630 // log line below is very chatty. disable until needed.
1631 // console.debug('egGrid: field: ' +field.name + '; parent field: ' + js2JSON(idl_parent));
1632 cols.add(col, false, true,
1633 {idl_parent : idl_parent, idl_field : field, idl_class : class_obj, field_parent_label : old_field_label });
1636 cols.columns = cols.columns.sort(
1638 if (a.explicit) return -1;
1639 if (b.explicit) return 1;
1641 if (a.idlclass && b.idlclass) {
1642 if (a.idlclass < b.idlclass) return -1;
1643 if (b.idlclass < a.idlclass) return 1;
1646 if (a.path && b.path && a.path.lastIndexOf('.') && b.path.lastIndexOf('.')) {
1647 if (a.path.substring(0, a.path.lastIndexOf('.')) < b.path.substring(0, b.path.lastIndexOf('.'))) return -1;
1648 if (b.path.substring(0, b.path.lastIndexOf('.')) < a.path.substring(0, a.path.lastIndexOf('.'))) return 1;
1651 if (a.label && b.label) {
1652 if (a.label < b.label) return -1;
1653 if (b.label < a.label) return 1;
1656 return a.name < b.name ? -1 : 1;
1663 "egGrid: wildcard path does not resolve to an object: "
1668 // angular.clone(scopeObject) is not permittable. Manually copy
1669 // the fields over that we need (so the scope object can go away).
1670 cols.cloneFromScope = function(colSpec) {
1672 flesher : colSpec.flesher,
1673 comparator : colSpec.comparator,
1674 name : colSpec.name,
1675 label : colSpec.label,
1676 path : colSpec.path,
1677 align : colSpec.align || 'left',
1678 flex : Number(colSpec.flex) || 2,
1679 sort : Number(colSpec.sort) || 0,
1680 required : colSpec.required,
1681 linkpath : colSpec.linkpath,
1682 template : colSpec.template,
1683 visible : colSpec.visible,
1684 compiled : colSpec.compiled,
1685 handlers : colSpec.handlers,
1686 hidden : colSpec.hidden,
1687 datatype : colSpec.datatype,
1688 sortable : colSpec.sortable,
1689 nonsortable : colSpec.nonsortable,
1690 multisortable : colSpec.multisortable,
1691 nonmultisortable : colSpec.nonmultisortable,
1692 dateformat : colSpec.dateformat,
1693 datecontext : colSpec.datecontext,
1694 datefilter : colSpec.datefilter,
1695 dateonlyinterval : colSpec.dateonlyinterval,
1696 parentIdlClass : colSpec.parentIdlClass,
1697 cssSelector : colSpec.cssSelector
1702 // Add a column to the columns collection.
1703 // Columns may come from a slim eg-columns-field or
1704 // directly from the IDL.
1705 cols.add = function(colSpec, fromIDL, fromExpand, idl_info) {
1707 // First added column with the specified path takes precedence.
1708 // This allows for specific definitions followed by wildcard
1709 // definitions. If a match is found, back out.
1710 if (cols.columns.filter(function(c) {
1711 return (c.path == colSpec.path) })[0]) {
1712 console.debug('skipping pre-existing column ' + colSpec.path);
1716 var column = fromExpand ? colSpec : cols.cloneFromScope(colSpec);
1718 if (column.path && column.path.match(/\*$/))
1719 return cols.expandPath(colSpec);
1721 if (!fromExpand) column.explicit = true;
1723 if (!column.name) column.name = column.path;
1724 if (!column.path) column.path = column.name;
1726 if (column.visible || (!cols.defaultToHidden && !column.hidden))
1727 column.visible = true;
1729 if (column.sortable || (!cols.defaultToNoSort && !column.nonsortable))
1730 column.sortable = true;
1732 if (column.multisortable ||
1733 (!cols.defaultToNoMultiSort && !column.nonmultisortable))
1734 column.multisortable = true;
1736 if (cols.defaultDateFormat && ! column.dateformat) {
1737 column.dateformat = cols.defaultDateFormat;
1740 if (cols.defaultDateOnlyInterval && ! column.dateonlyinterval) {
1741 column.dateonlyinterval = cols.defaultDateOnlyInterval;
1744 if (cols.defaultDateContext && ! column.datecontext) {
1745 column.datecontext = cols.defaultDateContext;
1748 if (cols.defaultDateFilter && ! column.datefilter) {
1749 column.datefilter = cols.defaultDateFilter;
1752 cols.columns.push(column);
1754 // Track which columns are visible by default in case we
1755 // need to reset column visibility
1757 cols.stockVisible.push(column.name);
1759 if (fromIDL) return; // directly from egIDL. nothing left to do.
1761 // lookup the matching IDL field
1762 if (!idl_info && cols.idlClass)
1763 idl_info = cols.idlFieldFromPath(column.path);
1766 // column is not represented within the IDL
1767 column.adhoc = true;
1771 column.datatype = idl_info.idl_field.datatype;
1773 if (!column.label) {
1774 column.label = idl_info.idl_field.label || column.name;
1777 if (fromExpand && idl_info.idl_class) {
1778 column.idlclass = '';
1779 if (idl_info.field_parent_label && idl_info.idl_parent.label != idl_info.idl_class.label) {
1780 column.idlclass = (idl_info.field_parent_label || idl_info.idl_parent.label || idl_info.idl_parent.name);
1782 column.idlclass += idl_info.idl_class.label || idl_info.idl_class.name;
1787 // finds the IDL field from the dotpath, using the columns
1788 // idlClass as the base.
1789 cols.idlFieldFromPath = function(dotpath) {
1790 var class_obj = egCore.idl.classes[cols.idlClass];
1791 if (!dotpath) return null;
1793 var path_parts = dotpath.split(/\./);
1797 for (var path_idx in path_parts) {
1798 var part = path_parts[path_idx];
1799 idl_parent = idl_field;
1800 idl_field = class_obj.field_map[part];
1803 if (idl_field['class'] && (
1804 idl_field.datatype == 'link' ||
1805 idl_field.datatype == 'org_unit')) {
1806 class_obj = egCore.idl.classes[idl_field['class']];
1814 idl_parent: idl_parent,
1815 idl_field : idl_field,
1816 idl_class : class_obj
1822 instance : function(args) { return new ColumnsProvider(args) }
1828 * Generic data provider template class. This is basically an abstract
1829 * class factory service whose instances can be locally modified to
1830 * meet the needs of each individual grid.
1832 .factory('egGridDataProvider',
1833 ['$q','$timeout','$filter','egCore',
1834 function($q , $timeout , $filter , egCore) {
1836 function GridDataProvider(args) {
1837 var gridData = this;
1838 if (!args) args = {};
1841 gridData.get = args.get;
1842 gridData.query = args.query;
1843 gridData.idlClass = args.idlClass;
1844 gridData.columnsProvider = args.columnsProvider;
1846 // Delivers a stream of array data via promise.notify()
1847 // Useful for passing an array of data to egGrid.get()
1848 // If a count is provided, the array will be trimmed to
1849 // the range defined by count and offset
1850 gridData.arrayNotifier = function(arr, offset, count) {
1851 if (!arr || arr.length == 0) return $q.when();
1853 if (gridData.columnsProvider.clientSort
1855 && gridData.sort.length > 0
1857 var sorter_cache = [];
1858 arr.sort(function(a,b) {
1859 for (var si = 0; si < gridData.sort.length; si++) {
1860 if (!sorter_cache[si]) { // Build sort structure on first comparison, reuse thereafter
1861 var field = gridData.sort[si];
1864 if (angular.isObject(field)) {
1865 dir = Object.values(field)[0];
1866 field = Object.keys(field)[0];
1869 var path = gridData.columnsProvider.findColumn(field).path || field;
1870 var comparator = gridData.columnsProvider.findColumn(field).comparator ||
1871 function (x,y) { if (x < y) return -1; if (x > y) return 1; return 0 };
1873 sorter_cache[si] = {
1876 comparator : comparator
1880 var sc = sorter_cache[si];
1884 if (a._isfieldmapper || angular.isFunction(a[sc.field])) {
1885 try {af = a[sc.field](); bf = b[sc.field]() } catch (e) {};
1887 af = a[sc.field]; bf = b[sc.field];
1889 if (af === undefined && sc.field.indexOf('.') > -1) { // assume an object, not flat path
1890 var parts = sc.field.split('.');
1893 angular.forEach(parts, function (p) {
1895 if (af._isfieldmapper || angular.isFunction(af[p])) af = af[p]();
1899 if (bf._isfieldmapper || angular.isFunction(bf[p])) bf = bf[p]();
1905 if (af === undefined) af = null;
1906 if (bf === undefined) bf = null;
1908 if (af === null && bf !== null) return 1;
1909 if (bf === null && af !== null) return -1;
1911 if (!(bf === null && af === null)) {
1912 var partial = sc.comparator(af,bf);
1914 if (sc.dir == 'desc') {
1915 if (partial > 0) return -1;
1927 if (count) arr = arr.slice(offset, offset + count);
1928 var def = $q.defer();
1929 // promise notifications are only witnessed when delivered
1930 // after the caller has his hands on the promise object
1931 $timeout(function() {
1932 angular.forEach(arr, def.notify);
1938 // Calls the grid refresh function. Once instantiated, the
1939 // grid will replace this function with it's own refresh()
1940 gridData.refresh = function(noReset) { }
1942 if (!gridData.get) {
1943 // returns a promise whose notify() delivers items
1944 gridData.get = function(index, count) {
1945 console.error("egGridDataProvider.get() not implemented");
1949 // attempts a flat field lookup first. If the column is not
1950 // found on the top-level object, attempts a nested lookup
1951 // TODO: consider a caching layer to speed up template
1952 // rendering, particularly for nested objects?
1953 gridData.itemFieldValue = function(item, column) {
1955 if (column.name in item) {
1956 if (typeof item[column.name] == 'function') {
1957 val = item[column.name]();
1959 val = item[column.name];
1962 val = gridData.nestedItemFieldValue(item, column);
1968 // TODO: deprecate me
1969 gridData.flatItemFieldValue = function(item, column) {
1970 console.warn('gridData.flatItemFieldValue deprecated; '
1971 + 'leave provider.itemFieldValue unset');
1972 return item[column.name];
1975 // given an object and a dot-separated path to a field,
1976 // extract the value of the field. The path can refer
1977 // to function names or object attributes. If the final
1978 // value is an IDL field, run the value through its
1979 // corresponding output filter.
1980 gridData.nestedItemFieldValue = function(obj, column) {
1981 item = obj; // keep a copy around
1983 if (obj === null || obj === undefined || obj === '') return '';
1984 if (!column.path) return obj;
1987 var parts = column.path.split('.');
1989 angular.forEach(parts, function(step, idx) {
1990 // object is not fleshed to the expected extent
1991 if (typeof obj != 'object') {
1992 if (typeof obj != 'undefined' && column.flesher) {
1993 obj = column.flesher(obj, column, item);
2000 if (!obj) return '';
2002 var cls = obj.classname;
2003 if (cls && (class_obj = egCore.idl.classes[cls])) {
2004 idl_field = class_obj.field_map[step];
2005 obj = obj[step] ? obj[step]() : '';
2007 if (angular.isFunction(obj[step])) {
2015 // We found a nested IDL object which may or may not have
2016 // been configured as a top-level column. Grab the datatype.
2017 if (idl_field && !column.datatype)
2018 column.datatype = idl_field.datatype;
2020 if (obj === null || obj === undefined || obj === '') return '';
2026 instance : function(args) {
2027 return new GridDataProvider(args);
2034 // Factory service for egGridDataManager instances, which are
2035 // responsible for collecting flattened grid data.
2036 .factory('egGridFlatDataProvider',
2037 ['$q','egCore','egGridDataProvider',
2038 function($q , egCore , egGridDataProvider) {
2041 instance : function(args) {
2042 var provider = egGridDataProvider.instance(args);
2044 provider.get = function(offset, count) {
2046 // no query means no call
2047 if (!provider.query ||
2048 angular.equals(provider.query, {}))
2051 // find all of the currently visible columns
2052 var queryFields = {}
2053 angular.forEach(provider.columnsProvider.columns,
2055 // only query IDL-tracked columns
2056 if (!col.adhoc && col.name && col.path && (col.required || col.visible))
2057 queryFields[col.name] = col.path;
2061 return egCore.net.request(
2063 'open-ils.fielder.flattened_search',
2064 egCore.auth.token(), provider.idlClass,
2065 queryFields, provider.query,
2066 { sort : provider.sort,
2072 //provider.itemFieldValue = provider.flatItemFieldValue;
2079 .directive('egGridColumnDragSource', function() {
2082 require : '^egGrid',
2083 link : function(scope, element, attrs, egGridCtrl) {
2084 angular.element(element).attr('draggable', 'true');
2086 element.bind('dragstart', function(e) {
2087 egGridCtrl.dragColumn = attrs.column;
2088 egGridCtrl.dragType = attrs.dragType || 'move'; // or resize
2089 egGridCtrl.colResizeDir = 0;
2091 if (egGridCtrl.dragType == 'move') {
2092 // style the column getting moved
2093 angular.element(e.target).addClass(
2094 'eg-grid-column-move-handle-active');
2098 element.bind('dragend', function(e) {
2099 if (egGridCtrl.dragType == 'move') {
2100 angular.element(e.target).removeClass(
2101 'eg-grid-column-move-handle-active');
2108 .directive('egGridColumnDragDest', function() {
2111 require : '^egGrid',
2112 link : function(scope, element, attrs, egGridCtrl) {
2114 element.bind('dragover', function(e) { // required for drop
2115 e.stopPropagation();
2117 e.dataTransfer.dropEffect = 'move';
2119 if (egGridCtrl.colResizeDir == 0) return; // move
2121 var cols = egGridCtrl.columnsProvider;
2122 var srcCol = egGridCtrl.dragColumn;
2123 var srcColIdx = cols.indexOf(srcCol);
2125 if (egGridCtrl.colResizeDir == -1) {
2126 if (cols.indexOf(attrs.column) <= srcColIdx) {
2127 egGridCtrl.modifyColumnFlex(
2128 egGridCtrl.columnsProvider.findColumn(
2129 egGridCtrl.dragColumn), -1);
2130 if (cols.columns[srcColIdx+1]) {
2131 // source column shrinks by one, column to the
2132 // right grows by one.
2133 egGridCtrl.modifyColumnFlex(
2134 cols.columns[srcColIdx+1], 1);
2139 if (cols.indexOf(attrs.column) > srcColIdx) {
2140 egGridCtrl.modifyColumnFlex(
2141 egGridCtrl.columnsProvider.findColumn(
2142 egGridCtrl.dragColumn), 1);
2143 if (cols.columns[srcColIdx+1]) {
2144 // source column grows by one, column to the
2145 // right grows by one.
2146 egGridCtrl.modifyColumnFlex(
2147 cols.columns[srcColIdx+1], -1);
2155 element.bind('dragenter', function(e) {
2156 e.stopPropagation();
2158 if (egGridCtrl.dragType == 'move') {
2159 angular.element(e.target).addClass('eg-grid-col-hover');
2161 // resize grips are on the right side of each column.
2162 // dragenter will either occur on the source column
2163 // (dragging left) or the column to the right.
2164 if (egGridCtrl.colResizeDir == 0) {
2165 if (egGridCtrl.dragColumn == attrs.column) {
2166 egGridCtrl.colResizeDir = -1; // west
2168 egGridCtrl.colResizeDir = 1; // east
2174 element.bind('dragleave', function(e) {
2175 e.stopPropagation();
2177 if (egGridCtrl.dragType == 'move') {
2178 angular.element(e.target).removeClass('eg-grid-col-hover');
2182 element.bind('drop', function(e) {
2183 e.stopPropagation();
2185 egGridCtrl.colResizeDir = 0;
2186 if (egGridCtrl.dragType == 'move') {
2187 angular.element(e.target).removeClass('eg-grid-col-hover');
2188 egGridCtrl.onColumnDrop(attrs.column); // move the column
2195 .directive('egGridMenuItem', function() {
2198 require : '^egGrid',
2204 handler : '=', // onclick handler function
2205 divider : '=', // if true, show a divider only
2206 handlerData : '=', // if set, passed as second argument to handler
2207 disabled : '=', // function
2208 hidden : '=' // function
2210 link : function(scope, element, attrs, egGridCtrl) {
2211 egGridCtrl.addMenuItem({
2212 checkbox : scope.checkbox,
2213 checked : scope.checked ? true : false,
2214 label : scope.label,
2215 standalone : scope.standalone ? true : false,
2216 handler : scope.handler,
2217 divider : scope.divider,
2218 disabled : scope.disabled,
2219 hidden : scope.hidden,
2220 handlerData : scope.handlerData
2227 /* https://stackoverflow.com/questions/17343696/adding-an-ng-click-event-inside-a-filter/17344875#17344875 */
2228 .directive('compile', ['$compile', function ($compile) {
2229 return function(scope, element, attrs) {
2230 // pass through column defs from grid cell's scope
2231 scope.col = scope.$parent.col;
2234 // watch the 'compile' expression for changes
2235 return scope.$eval(attrs.compile);
2238 // when the 'compile' expression changes
2239 // assign it into the current DOM
2240 element.html(value);
2242 // compile the new DOM and link it to the current
2244 // NOTE: we only compile .childNodes so that
2245 // we don't get into infinite loop compiling ourselves
2246 $compile(element.contents())(scope);
2255 * Translates bare IDL object values into display values.
2256 * 1. Passes dates through the angular date filter
2257 * 2. Converts bools to translated Yes/No strings
2258 * Others likely to follow...
2260 .filter('egGridValueFilter', ['$filter','egCore', 'egStrings', function($filter,egCore,egStrings) {
2261 function traversePath(obj,path) {
2262 var list = path.split('.');
2263 for (var part in path) {
2264 if (obj[path]) obj = obj[path]
2270 var GVF = function(value, column, item) {
2271 switch(column.datatype) {
2274 // Browser will translate true/false for us
2276 case '1' : // legacy
2278 return egStrings.YES;
2280 case '0' : // legacy
2282 return egStrings.NO;
2283 // value may be null, '', etc.
2284 default : return '';
2287 var interval = angular.isFunction(item[column.dateonlyinterval])
2288 ? item[column.dateonlyinterval]()
2289 : item[column.dateonlyinterval];
2291 if (column.dateonlyinterval && !interval) // try it as a dotted path
2292 interval = traversePath(item, column.dateonlyinterval);
2294 var context = angular.isFunction(item[column.datecontext])
2295 ? item[column.datecontext]()
2296 : item[column.datecontext];
2298 if (column.datecontext && !context) // try it as a dotted path
2299 context = traversePath(item, column.datecontext);
2301 var date_filter = column.datefilter || 'egOrgDateInContext';
2303 return $filter(date_filter)(value, column.dateformat, context, interval);
2305 return $filter('currency')(value);
2311 GVF.$stateful = true;