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 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
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 // select the right-clicked row if it is not already selected (lp1776557):
695 if(!$scope.selected[grid.indexValue(s.item)]){ $event.target.click(); }
697 if (!$scope.action_context_showing) {
698 $scope.action_context_width = $($scope.menu_dom).css('width');
699 $scope.action_context_y = $($scope.menu_dom).css('top');
700 $scope.action_context_x = $($scope.menu_dom).css('left');
701 $scope.action_context_showing = true;
702 $scope.action_context_index = Math.floor((Math.random() * 1000) + 1);
704 $('body').append($($scope.menu_dom));
705 $('body').bind('click.remove_context_menu_'+$scope.action_context_index, $scope.hideActionContextMenu);
708 $($scope.menu_dom).css({
710 width: $scope.action_context_width,
718 // returns the list of selected item objects
719 grid.getSelectedItems = function() {
720 return $scope.items.filter(
722 return Boolean($scope.selected[grid.indexValue(item)]);
727 grid.getItemByIndex = function(index) {
728 for (var i = 0; i < $scope.items.length; i++) {
729 var item = $scope.items[i];
730 if (grid.indexValue(item) == index)
735 // selects one row after deselecting all of the others
736 grid.selectOneItem = function(index) {
737 $scope.selected = {};
738 $scope.selected[index] = true;
741 // selects or deselects an item, without affecting the others.
742 // returns true if the item is selected; false if de-selected.
743 // we overwrite the object so that we can watch $scope.selected
744 grid.toggleSelectOneItem = function(index) {
745 if ($scope.selected[index]) {
746 delete $scope.selected[index];
747 $scope.selected = angular.copy($scope.selected);
750 $scope.selected[index] = true;
751 $scope.selected = angular.copy($scope.selected);
756 $scope.updateSelected = function () {
757 return $scope.selected = angular.copy($scope.selected);
760 grid.selectAllItems = function() {
761 angular.forEach($scope.items, function(item) {
762 $scope.selected[grid.indexValue(item)] = true
764 $scope.selected = angular.copy($scope.selected);
767 $scope.$watch('selectAll', function(newVal) {
769 grid.selectAllItems();
771 $scope.selected = {};
775 if ($scope.onSelect) {
776 $scope.$watch('selected', function(newVal) {
777 $scope.onSelect(grid.getSelectedItems());
778 if ($scope.afterSelect) $scope.afterSelect();
782 // returns true if item1 appears in the list before item2;
783 // false otherwise. this is slightly more efficient that
784 // finding the position of each then comparing them.
785 // item1 / item2 may be an item or an item index
786 grid.itemComesBefore = function(itemOrIndex1, itemOrIndex2) {
787 var idx1 = grid.indexValue(itemOrIndex1);
788 var idx2 = grid.indexValue(itemOrIndex2);
790 // use for() for early exit
791 for (var i = 0; i < $scope.items.length; i++) {
792 var idx = grid.indexValue($scope.items[i]);
793 if (idx == idx1) return true;
794 if (idx == idx2) return false;
799 // 0-based position of item in the current data set
800 grid.indexOf = function(item) {
801 var idx = grid.indexValue(item);
802 for (var i = 0; i < $scope.items.length; i++) {
803 if (grid.indexValue($scope.items[i]) == idx)
809 grid.modifyColumnFlex = function(column, val) {
811 // prevent flex:0; use hiding instead
815 $scope.modifyColumnFlex = function(col, val) {
816 $scope.lastModColumn = col;
817 grid.modifyColumnFlex(col, val);
820 $scope.isLastModifiedColumn = function(col) {
821 if ($scope.lastModColumn)
822 return $scope.lastModColumn === col;
826 grid.modifyColumnPos = function(col, diff) {
827 var srcIdx, targetIdx;
828 angular.forEach(grid.columnsProvider.columns,
829 function(c, i) { if (c.name == col.name) srcIdx = i });
831 targetIdx = srcIdx + diff;
834 } else if (targetIdx >= grid.columnsProvider.columns.length) {
835 // Target index follows the last visible column.
837 angular.forEach(grid.columnsProvider.columns,
838 function(column, idx) {
839 if (column.visible) lastVisible = idx;
843 // When moving a column (down) causes one or more
844 // visible columns to shuffle forward, our column
845 // moves into the slot of the last visible column.
846 // Otherwise, put it into the slot directly following
847 // the last visible column.
849 srcIdx <= lastVisible ? lastVisible : lastVisible + 1;
852 // Splice column out of old position, insert at new position.
853 grid.columnsProvider.columns.splice(srcIdx, 1);
854 grid.columnsProvider.columns.splice(targetIdx, 0, col);
857 $scope.modifyColumnPos = function(col, diff) {
858 $scope.lastModColumn = col;
859 return grid.modifyColumnPos(col, diff);
863 // handles click, control-click, and shift-click
864 $scope.handleRowClick = function($event, item) {
865 var index = grid.indexValue(item);
867 var origSelected = Object.keys($scope.selected);
869 if (!$scope.canMultiSelect) {
870 grid.selectOneItem(index);
871 grid.lastSelectedItemIndex = index;
875 if ($event.ctrlKey || $event.metaKey /* mac command */) {
877 if (grid.toggleSelectOneItem(index))
878 grid.lastSelectedItemIndex = index;
880 } else if ($event.shiftKey) {
883 if (!grid.lastSelectedItemIndex ||
884 index == grid.lastSelectedItemIndex) {
885 grid.selectOneItem(index);
886 grid.lastSelectedItemIndex = index;
890 var selecting = false;
891 var ascending = grid.itemComesBefore(
892 grid.lastSelectedItemIndex, item);
894 grid.indexOf(grid.lastSelectedItemIndex);
896 // update to new last-selected
897 grid.lastSelectedItemIndex = index;
899 // select each row between the last selected and
900 // currently selected items
902 startPos += ascending ? 1 : -1;
903 var curItem = $scope.items[startPos];
905 var curIdx = grid.indexValue(curItem);
906 $scope.selected[curIdx] = true;
907 if (curIdx == index) break; // all done
909 $scope.selected = angular.copy($scope.selected);
913 grid.selectOneItem(index);
914 grid.lastSelectedItemIndex = index;
918 // Builds a sort expression from column sort priorities.
919 // called on page load and any time the priorities are modified.
920 grid.compileSort = function() {
921 var sortList = grid.columnsProvider.columns.filter(
922 function(col) { return Number(col.sort) != 0 }
925 if (Math.abs(a.sort) < Math.abs(b.sort))
931 if (sortList.length) {
932 grid.dataProvider.sort = sortList.map(function(col) {
934 blob[col.name] = col.sort < 0 ? 'desc' : 'asc';
940 // builds a sort expression using a single column,
941 // toggling between ascending and descending sort.
942 $scope.quickSort = function(col_name) {
943 var sort = grid.dataProvider.sort;
944 if (sort && sort.length &&
945 sort[0] == col_name) {
947 blob[col_name] = 'desc';
948 grid.dataProvider.sort = [blob];
950 grid.dataProvider.sort = [col_name];
957 // show / hide the grid configuration row
958 $scope.toggleConfDisplay = function() {
959 if ($scope.showGridConf) {
960 $scope.showGridConf = false;
961 if (grid.columnsProvider.hasSortableColumn()) {
962 // only refresh the grid if the user has the
963 // ability to modify the sort priorities.
969 $scope.showGridConf = true;
972 delete $scope.lastModColumn;
973 $scope.gridColumnPickerIsOpen = false;
976 // called when a dragged column is dropped onto itself
977 // or any other column
978 grid.onColumnDrop = function(target) {
979 if (angular.isUndefined(target)) return;
980 if (target == grid.dragColumn) return;
981 var srcIdx, targetIdx, srcCol;
982 angular.forEach(grid.columnsProvider.columns,
984 if (col.name == grid.dragColumn) {
987 } else if (col.name == target) {
993 if (srcIdx < targetIdx) targetIdx--;
995 // move src column from old location to new location in
996 // the columns array, then force a page refresh
997 grid.columnsProvider.columns.splice(srcIdx, 1);
998 grid.columnsProvider.columns.splice(targetIdx, 0, srcCol);
1002 // prepares a string for inclusion within a CSV document
1003 // by escaping commas and quotes and removing newlines.
1004 grid.csvDatum = function(str) {
1006 if (!str) return '';
1007 str = str.replace(/\n/g, '');
1008 if (str.match(/\,/) || str.match(/"/)) {
1009 str = str.replace(/"/g, '""');
1010 str = '"' + str + '"';
1015 /** Export the full data set as CSV.
1017 * 1. User clicks the 'download csv' link
1018 * 2. All grid data is retrieved asychronously
1019 * 3. Once all data is all present and CSV-ized, the download
1020 * attributes are linked to the href.
1021 * 4. The href .click() action is prgrammatically fired again,
1022 * telling the browser to download the data, now that the
1023 * data is available for download.
1024 * 5 Once downloaded, the href attributes are reset.
1026 grid.csvExportInProgress = false;
1027 $scope.generateCSVExportURL = function($event) {
1029 if (grid.csvExportInProgress) {
1030 // This is secondary href click handler. Give the
1031 // browser a moment to start the download, then reset
1032 // the CSV download attributes / state.
1035 $scope.csvExportURL = '';
1036 $scope.csvExportFileName = '';
1037 grid.csvExportInProgress = false;
1043 grid.csvExportInProgress = true;
1044 $scope.gridColumnPickerIsOpen = false;
1046 // let the file name describe the grid
1047 $scope.csvExportFileName =
1048 ($scope.mainLabel || grid.persistKey || 'eg_grid_data')
1049 .replace(/\s+/g, '_') + '_' + $scope.page();
1051 // toss the CSV into a Blob and update the export URL
1052 grid.generateCSV().then(function(csv) {
1053 var blob = new Blob([csv], {type : 'text/plain'});
1054 $scope.csvExportURL =
1055 ($window.URL || $window.webkitURL).createObjectURL(blob);
1057 // Fire the 2nd click event now that the browser has
1058 // information on how to download the CSV file.
1059 $timeout(function() {$event.target.click()});
1064 * TODO: does this serve any purpose given we can
1065 * print formatted HTML? If so, generateCSV() now
1066 * returns a promise, needs light refactoring...
1067 $scope.printCSV = function() {
1068 $scope.gridColumnPickerIsOpen = false;
1069 egCore.print.print({
1070 context : 'default',
1071 content : grid.generateCSV(),
1072 content_type : 'text/plain'
1077 // Given a row item and column definition, extract the
1078 // text content for printing. Templated columns must be
1079 // processed and parsed as HTML, then boiled down to their
1081 grid.getItemTextContent = function(item, col) {
1084 val = $scope.translateCellTemplate(col, item);
1086 var node = new DOMParser()
1087 .parseFromString(val, 'text/html');
1088 val = $(node).text();
1091 val = grid.dataProvider.itemFieldValue(item, col);
1092 val = $filter('egGridValueFilter')(val, col, item);
1098 * Fetches all grid data and transates each item into a simple
1099 * key-value pair of column name => text-value.
1100 * Included in the response for convenience is the list of
1101 * currently visible column definitions.
1102 * TODO: currently fetches a maximum of 10k rows. Does this
1103 * need to be configurable?
1105 grid.getAllItemsAsText = function() {
1106 var text_items = [];
1108 // we don't know the total number of rows we're about
1109 // to retrieve, but we can indicate the number retrieved
1110 // so far as each item arrives.
1111 egProgressDialog.open({value : 0});
1113 var visible_cols = grid.columnsProvider.columns.filter(
1114 function(c) { return c.visible });
1116 return grid.dataProvider.get(0, 10000).then(
1118 return {items : text_items, columns : visible_cols};
1122 egProgressDialog.increment();
1124 angular.forEach(visible_cols, function(col) {
1125 text_item[col.name] =
1126 grid.getItemTextContent(item, col);
1128 text_items.push(text_item);
1130 ).finally(egProgressDialog.close);
1133 // Fetch "all" of the grid data, translate it into print-friendly
1134 // text, and send it to the printer service.
1135 $scope.printHTML = function() {
1136 $scope.gridColumnPickerIsOpen = false;
1137 return grid.getAllItemsAsText().then(function(text_items) {
1138 return egCore.print.print({
1139 template : 'grid_html',
1145 $scope.showColumnDialog = function() {
1146 return $uibModal.open({
1147 templateUrl: './share/t_grid_columns',
1150 controller: ['$scope', '$uibModalInstance',
1151 function($dialogScope, $uibModalInstance) {
1152 $dialogScope.modifyColumnPos = $scope.modifyColumnPos;
1153 $dialogScope.disableMultiSort = $scope.disableMultiSort;
1154 $dialogScope.columns = $scope.columns;
1156 // Push visible columns to the top of the list
1157 $dialogScope.elevateVisible = function() {
1159 angular.forEach($dialogScope.columns, function(col) {
1160 if (col.visible) new_cols.push(col);
1162 angular.forEach($dialogScope.columns, function(col) {
1163 if (!col.visible) new_cols.push(col);
1166 // Update all references to the list of columns
1167 $dialogScope.columns =
1169 grid.columnsProvider.columns =
1173 $dialogScope.toggle = function(col) {
1174 col.visible = !Boolean(col.visible);
1176 $dialogScope.ok = $dialogScope.cancel = function() {
1177 delete $scope.lastModColumn;
1178 $uibModalInstance.close()
1185 // generates CSV for the currently visible grid contents
1186 grid.generateCSV = function() {
1187 return grid.getAllItemsAsText().then(function(text_items) {
1188 var columns = text_items.columns;
1189 var items = text_items.items;
1193 angular.forEach(columns, function(col) {
1194 csvStr += grid.csvDatum(col.label);
1198 csvStr = csvStr.replace(/,$/,'\n');
1201 angular.forEach(items, function(item) {
1202 angular.forEach(columns, function(col) {
1203 csvStr += grid.csvDatum(item[col.name]);
1206 csvStr = csvStr.replace(/,$/,'\n');
1213 // Interpolate the value for column.linkpath within the context
1214 // of the row item to generate the final link URL.
1215 $scope.generateLinkPath = function(col, item) {
1216 return egCore.strings.$replace(col.linkpath, {item : item});
1219 // If a column provides its own HTML template, translate it,
1220 // using the current item for the template scope.
1221 // note: $sce is required to avoid security restrictions and
1222 // is OK here, since the template comes directly from a
1223 // local HTML template (not user input).
1224 $scope.translateCellTemplate = function(col, item) {
1225 var html = egCore.strings.$replace(col.template, {item : item});
1226 return $sce.trustAsHtml(html);
1229 $scope.collect = function() { grid.collect() }
1232 $scope.confirmAllowAllAndCollect = function(){
1233 egConfirmDialog.open(egStrings.CONFIRM_LONG_RUNNING_ACTION_ALL_ROWS_TITLE,
1234 egStrings.CONFIRM_LONG_RUNNING_ACTION_MSG)
1238 $scope.limit(10000);
1243 // asks the dataProvider for a page of data
1244 grid.collect = function() {
1246 // avoid firing the collect if there is nothing to collect.
1247 if (grid.selfManagedData && !grid.dataProvider.query) return;
1249 if (grid.collecting) return; // avoid parallel collect()
1250 grid.collecting = true;
1252 console.debug('egGrid.collect() offset='
1253 + grid.offset + '; limit=' + grid.limit);
1255 // ensure all of our dropdowns are closed
1256 // TODO: git rid of these and just use dropdown-toggle,
1257 // which is more reliable.
1258 $scope.gridColumnPickerIsOpen = false;
1259 $scope.gridRowCountIsOpen = false;
1260 $scope.gridPageSelectIsOpen = false;
1263 $scope.selected = {};
1265 // Inform the caller we've asked the data provider
1266 // for data. This is useful for knowing when collection
1267 // has started (e.g. to display a progress dialg) when
1268 // using the stock (flattener) data provider, where the
1269 // user is not directly defining a get() handler.
1270 if (grid.controls.collectStarted)
1271 grid.controls.collectStarted(grid.offset, grid.limit);
1273 grid.dataProvider.get(grid.offset, grid.limit).then(
1275 if (grid.controls.allItemsRetrieved)
1276 grid.controls.allItemsRetrieved();
1281 $scope.items.push(item)
1282 if (grid.controls.itemRetrieved)
1283 grid.controls.itemRetrieved(item);
1284 if ($scope.selectAll)
1285 $scope.selected[grid.indexValue(item)] = true
1287 }).finally(function() {
1288 console.debug('egGrid.collect() complete');
1289 grid.collecting = false
1290 $scope.selected = angular.copy($scope.selected);
1300 * eg-grid-field : used for collecting custom field data from the templates.
1301 * This directive does not direct display, it just passes data up to the
1304 .directive('egGridField', function() {
1306 require : '^egGrid',
1309 flesher: '=', // optional; function that can flesh a linked field, given the value
1310 comparator: '=', // optional; function that can sort the thing at the end of 'path'
1311 name : '@', // required; unique name
1312 path : '@', // optional; flesh path
1313 ignore: '@', // optional; fields to ignore when path is a wildcard
1314 label : '@', // optional; display label
1315 flex : '@', // optional; default flex width
1316 align : '@', // optional; default alignment, left/center/right
1317 dateformat : '@', // optional: passed down to egGridValueFilter
1318 datecontext: '@', // optional: passed down to egGridValueFilter to choose TZ
1319 datefilter: '@', // optional: passed down to egGridValueFilter to choose specialized date filters
1320 dateonlyinterval: '@', // optional: passed down to egGridValueFilter to choose a "better" format
1322 // if a field is part of an IDL object, but we are unable to
1323 // determine the class, because it's nested within a hash
1324 // (i.e. we can't navigate directly to the object via the IDL),
1325 // idlClass lets us specify the class. This is particularly
1326 // useful for nested wildcard fields.
1327 parentIdlClass : '@',
1329 // optional: for non-IDL columns, specifying a datatype
1330 // lets the caller control which display filter is used.
1331 // datatype should match the standard IDL datatypes.
1334 // optional hash of functions that can be imported into
1335 // the directive's scope; meant for cases where the "compiled"
1339 link : function(scope, element, attrs, egGridCtrl) {
1341 // boolean fields are presented as value-less attributes
1351 'required' // if set, always fetch data for this column
1354 if (angular.isDefined(attrs[field]))
1355 scope[field] = true;
1359 // any HTML content within the field is its custom template
1360 var tmpl = element.html();
1361 if (tmpl && !tmpl.match(/^\s*$/))
1362 scope.template = tmpl
1364 egGridCtrl.columnsProvider.add(scope);
1371 * eg-grid-action : used for specifying actions which may be applied
1372 * to items within the grid.
1374 .directive('egGridAction', function() {
1376 require : '^egGrid',
1380 group : '@', // Action group, ungrouped if not set
1381 label : '@', // Action label
1382 handler : '=', // Action function handler
1384 disabled : '=', // function
1387 link : function(scope, element, attrs, egGridCtrl) {
1388 egGridCtrl.addAction({
1390 group : scope.group,
1391 label : scope.label,
1392 divider : scope.divider,
1393 handler : scope.handler,
1394 disabled : scope.disabled,
1401 .factory('egGridColumnsProvider', ['egCore', function(egCore) {
1403 function ColumnsProvider(args) {
1406 cols.stockVisible = [];
1407 cols.idlClass = args.idlClass;
1408 cols.clientSort = args.clientSort;
1409 cols.defaultToHidden = args.defaultToHidden;
1410 cols.defaultToNoSort = args.defaultToNoSort;
1411 cols.defaultToNoMultiSort = args.defaultToNoMultiSort;
1412 cols.defaultDateFormat = args.defaultDateFormat;
1413 cols.defaultDateContext = args.defaultDateContext;
1415 // resets column width, visibility, and sort behavior
1416 // Visibility resets to the visibility settings defined in the
1417 // template (i.e. the original egGridField values).
1418 cols.reset = function() {
1419 angular.forEach(cols.columns, function(col) {
1423 if (cols.stockVisible.indexOf(col.name) > -1) {
1426 col.visible = false;
1431 // returns true if any columns are sortable
1432 cols.hasSortableColumn = function() {
1433 return cols.columns.filter(
1435 return col.sortable || col.multisortable;
1440 cols.showAllColumns = function() {
1441 angular.forEach(cols.columns, function(column) {
1442 column.visible = true;
1446 cols.hideAllColumns = function() {
1447 angular.forEach(cols.columns, function(col) {
1452 cols.indexOf = function(name) {
1453 for (var i = 0; i < cols.columns.length; i++) {
1454 if (cols.columns[i].name == name)
1460 cols.findColumn = function(name) {
1461 return cols.columns[cols.indexOf(name)];
1464 cols.compileAutoColumns = function() {
1465 var idl_class = egCore.idl.classes[cols.idlClass];
1470 if (field.virtual) return;
1471 if (field.datatype == 'link' || field.datatype == 'org_unit') {
1472 // if the field is a link and the linked class has a
1473 // "selector" field specified, use the selector field
1474 // as the display field for the columns.
1475 // flattener will take care of the fleshing.
1476 if (field['class']) {
1477 var selector_field = egCore.idl.classes[field['class']].fields
1478 .filter(function(f) { return Boolean(f.selector) })[0];
1479 if (selector_field) {
1480 field.path = field.name + '.' + selector_field.selector;
1484 cols.add(field, true);
1489 // if a column definition has a path with a wildcard, create
1490 // columns for all non-virtual fields at the specified
1491 // position in the path.
1492 cols.expandPath = function(colSpec) {
1494 var ignoreList = [];
1496 ignoreList = colSpec.ignore.split(' ');
1498 var dotpath = colSpec.path.replace(/\.?\*$/,'');
1502 if (colSpec.parentIdlClass) {
1503 class_obj = egCore.idl.classes[colSpec.parentIdlClass];
1505 class_obj = egCore.idl.classes[cols.idlClass];
1507 var idl_parent = class_obj;
1508 var old_field_label = '';
1510 if (!class_obj) return;
1512 //console.debug('egGrid: auto dotpath is: ' + dotpath);
1513 var path_parts = dotpath.split(/\./);
1515 // find the IDL class definition for the last element in the
1516 // path before the .*
1517 // an empty path_parts means expand the root class
1520 for (var path_idx in path_parts) {
1521 old_field = idl_field;
1523 var part = path_parts[path_idx];
1524 idl_field = class_obj.field_map[part];
1526 // unless we're at the end of the list, this field should
1527 // link to another class.
1528 if (idl_field && idl_field['class'] && (
1529 idl_field.datatype == 'link' ||
1530 idl_field.datatype == 'org_unit')) {
1531 if (old_field_label) old_field_label += ' : ';
1532 old_field_label += idl_field.label;
1533 class_obj = egCore.idl.classes[idl_field['class']];
1534 if (old_field) idl_parent = old_field;
1536 if (path_idx < (path_parts.length - 1)) {
1537 // we ran out of classes to hop through before
1538 // we ran out of path components
1539 console.error("egGrid: invalid IDL path: " + dotpath);
1546 angular.forEach(class_obj.fields, function(field) {
1548 // Only show wildcard fields where we have data to show
1549 // Virtual and un-fleshed links will not have any data.
1550 if (field.virtual ||
1551 (field.datatype == 'link' || field.datatype == 'org_unit') ||
1552 ignoreList.indexOf(field.name) > -1
1556 var col = cols.cloneFromScope(colSpec);
1557 col.path = (dotpath ? dotpath + '.' + field.name : field.name);
1559 // log line below is very chatty. disable until needed.
1560 // console.debug('egGrid: field: ' +field.name + '; parent field: ' + js2JSON(idl_parent));
1561 cols.add(col, false, true,
1562 {idl_parent : idl_parent, idl_field : field, idl_class : class_obj, field_parent_label : old_field_label });
1565 cols.columns = cols.columns.sort(
1567 if (a.explicit) return -1;
1568 if (b.explicit) return 1;
1570 if (a.idlclass && b.idlclass) {
1571 if (a.idlclass < b.idlclass) return -1;
1572 if (b.idlclass < a.idlclass) return 1;
1575 if (a.path && b.path && a.path.lastIndexOf('.') && b.path.lastIndexOf('.')) {
1576 if (a.path.substring(0, a.path.lastIndexOf('.')) < b.path.substring(0, b.path.lastIndexOf('.'))) return -1;
1577 if (b.path.substring(0, b.path.lastIndexOf('.')) < a.path.substring(0, a.path.lastIndexOf('.'))) return 1;
1580 if (a.label && b.label) {
1581 if (a.label < b.label) return -1;
1582 if (b.label < a.label) return 1;
1585 return a.name < b.name ? -1 : 1;
1592 "egGrid: wildcard path does not resolve to an object: "
1597 // angular.clone(scopeObject) is not permittable. Manually copy
1598 // the fields over that we need (so the scope object can go away).
1599 cols.cloneFromScope = function(colSpec) {
1601 flesher : colSpec.flesher,
1602 comparator : colSpec.comparator,
1603 name : colSpec.name,
1604 label : colSpec.label,
1605 path : colSpec.path,
1606 align : colSpec.align || 'left',
1607 flex : Number(colSpec.flex) || 2,
1608 sort : Number(colSpec.sort) || 0,
1609 required : colSpec.required,
1610 linkpath : colSpec.linkpath,
1611 template : colSpec.template,
1612 visible : colSpec.visible,
1613 compiled : colSpec.compiled,
1614 handlers : colSpec.handlers,
1615 hidden : colSpec.hidden,
1616 datatype : colSpec.datatype,
1617 sortable : colSpec.sortable,
1618 nonsortable : colSpec.nonsortable,
1619 multisortable : colSpec.multisortable,
1620 nonmultisortable : colSpec.nonmultisortable,
1621 dateformat : colSpec.dateformat,
1622 datecontext : colSpec.datecontext,
1623 datefilter : colSpec.datefilter,
1624 dateonlyinterval : colSpec.dateonlyinterval,
1625 parentIdlClass : colSpec.parentIdlClass
1630 // Add a column to the columns collection.
1631 // Columns may come from a slim eg-columns-field or
1632 // directly from the IDL.
1633 cols.add = function(colSpec, fromIDL, fromExpand, idl_info) {
1635 // First added column with the specified path takes precedence.
1636 // This allows for specific definitions followed by wildcard
1637 // definitions. If a match is found, back out.
1638 if (cols.columns.filter(function(c) {
1639 return (c.path == colSpec.path) })[0]) {
1640 console.debug('skipping pre-existing column ' + colSpec.path);
1644 var column = fromExpand ? colSpec : cols.cloneFromScope(colSpec);
1646 if (column.path && column.path.match(/\*$/))
1647 return cols.expandPath(colSpec);
1649 if (!fromExpand) column.explicit = true;
1651 if (!column.name) column.name = column.path;
1652 if (!column.path) column.path = column.name;
1654 if (column.visible || (!cols.defaultToHidden && !column.hidden))
1655 column.visible = true;
1657 if (column.sortable || (!cols.defaultToNoSort && !column.nonsortable))
1658 column.sortable = true;
1660 if (column.multisortable ||
1661 (!cols.defaultToNoMultiSort && !column.nonmultisortable))
1662 column.multisortable = true;
1664 if (cols.defaultDateFormat && ! column.dateformat) {
1665 column.dateformat = cols.defaultDateFormat;
1668 if (cols.defaultDateOnlyInterval && ! column.dateonlyinterval) {
1669 column.dateonlyinterval = cols.defaultDateOnlyInterval;
1672 if (cols.defaultDateContext && ! column.datecontext) {
1673 column.datecontext = cols.defaultDateContext;
1676 if (cols.defaultDateFilter && ! column.datefilter) {
1677 column.datefilter = cols.defaultDateFilter;
1680 cols.columns.push(column);
1682 // Track which columns are visible by default in case we
1683 // need to reset column visibility
1685 cols.stockVisible.push(column.name);
1687 if (fromIDL) return; // directly from egIDL. nothing left to do.
1689 // lookup the matching IDL field
1690 if (!idl_info && cols.idlClass)
1691 idl_info = cols.idlFieldFromPath(column.path);
1694 // column is not represented within the IDL
1695 column.adhoc = true;
1699 column.datatype = idl_info.idl_field.datatype;
1701 if (!column.label) {
1702 column.label = idl_info.idl_field.label || column.name;
1705 if (fromExpand && idl_info.idl_class) {
1706 column.idlclass = '';
1707 if (idl_info.field_parent_label && idl_info.idl_parent.label != idl_info.idl_class.label) {
1708 column.idlclass = (idl_info.field_parent_label || idl_info.idl_parent.label || idl_info.idl_parent.name);
1710 column.idlclass += idl_info.idl_class.label || idl_info.idl_class.name;
1715 // finds the IDL field from the dotpath, using the columns
1716 // idlClass as the base.
1717 cols.idlFieldFromPath = function(dotpath) {
1718 var class_obj = egCore.idl.classes[cols.idlClass];
1719 if (!dotpath) return null;
1721 var path_parts = dotpath.split(/\./);
1725 for (var path_idx in path_parts) {
1726 var part = path_parts[path_idx];
1727 idl_parent = idl_field;
1728 idl_field = class_obj.field_map[part];
1731 if (idl_field['class'] && (
1732 idl_field.datatype == 'link' ||
1733 idl_field.datatype == 'org_unit')) {
1734 class_obj = egCore.idl.classes[idl_field['class']];
1742 idl_parent: idl_parent,
1743 idl_field : idl_field,
1744 idl_class : class_obj
1750 instance : function(args) { return new ColumnsProvider(args) }
1756 * Generic data provider template class. This is basically an abstract
1757 * class factory service whose instances can be locally modified to
1758 * meet the needs of each individual grid.
1760 .factory('egGridDataProvider',
1761 ['$q','$timeout','$filter','egCore',
1762 function($q , $timeout , $filter , egCore) {
1764 function GridDataProvider(args) {
1765 var gridData = this;
1766 if (!args) args = {};
1769 gridData.get = args.get;
1770 gridData.query = args.query;
1771 gridData.idlClass = args.idlClass;
1772 gridData.columnsProvider = args.columnsProvider;
1774 // Delivers a stream of array data via promise.notify()
1775 // Useful for passing an array of data to egGrid.get()
1776 // If a count is provided, the array will be trimmed to
1777 // the range defined by count and offset
1778 gridData.arrayNotifier = function(arr, offset, count) {
1779 if (!arr || arr.length == 0) return $q.when();
1781 if (gridData.columnsProvider.clientSort
1783 && gridData.sort.length > 0
1785 var sorter_cache = [];
1786 arr.sort(function(a,b) {
1787 for (var si = 0; si < gridData.sort.length; si++) {
1788 if (!sorter_cache[si]) { // Build sort structure on first comparison, reuse thereafter
1789 var field = gridData.sort[si];
1792 if (angular.isObject(field)) {
1793 dir = Object.values(field)[0];
1794 field = Object.keys(field)[0];
1797 var path = gridData.columnsProvider.findColumn(field).path || field;
1798 var comparator = gridData.columnsProvider.findColumn(field).comparator ||
1799 function (x,y) { if (x < y) return -1; if (x > y) return 1; return 0 };
1801 sorter_cache[si] = {
1804 comparator : comparator
1808 var sc = sorter_cache[si];
1812 if (a._isfieldmapper || angular.isFunction(a[sc.field])) {
1813 try {af = a[sc.field](); bf = b[sc.field]() } catch (e) {};
1815 af = a[sc.field]; bf = b[sc.field];
1817 if (af === undefined && sc.field.indexOf('.') > -1) { // assume an object, not flat path
1818 var parts = sc.field.split('.');
1821 angular.forEach(parts, function (p) {
1823 if (af._isfieldmapper || angular.isFunction(af[p])) af = af[p]();
1827 if (bf._isfieldmapper || angular.isFunction(bf[p])) bf = bf[p]();
1833 if (af === undefined) af = null;
1834 if (bf === undefined) bf = null;
1836 if (af === null && bf !== null) return 1;
1837 if (bf === null && af !== null) return -1;
1839 if (!(bf === null && af === null)) {
1840 var partial = sc.comparator(af,bf);
1842 if (sc.dir == 'desc') {
1843 if (partial > 0) return -1;
1855 if (count) arr = arr.slice(offset, offset + count);
1856 var def = $q.defer();
1857 // promise notifications are only witnessed when delivered
1858 // after the caller has his hands on the promise object
1859 $timeout(function() {
1860 angular.forEach(arr, def.notify);
1866 // Calls the grid refresh function. Once instantiated, the
1867 // grid will replace this function with it's own refresh()
1868 gridData.refresh = function(noReset) { }
1870 if (!gridData.get) {
1871 // returns a promise whose notify() delivers items
1872 gridData.get = function(index, count) {
1873 console.error("egGridDataProvider.get() not implemented");
1877 // attempts a flat field lookup first. If the column is not
1878 // found on the top-level object, attempts a nested lookup
1879 // TODO: consider a caching layer to speed up template
1880 // rendering, particularly for nested objects?
1881 gridData.itemFieldValue = function(item, column) {
1883 if (column.name in item) {
1884 if (typeof item[column.name] == 'function') {
1885 val = item[column.name]();
1887 val = item[column.name];
1890 val = gridData.nestedItemFieldValue(item, column);
1896 // TODO: deprecate me
1897 gridData.flatItemFieldValue = function(item, column) {
1898 console.warn('gridData.flatItemFieldValue deprecated; '
1899 + 'leave provider.itemFieldValue unset');
1900 return item[column.name];
1903 // given an object and a dot-separated path to a field,
1904 // extract the value of the field. The path can refer
1905 // to function names or object attributes. If the final
1906 // value is an IDL field, run the value through its
1907 // corresponding output filter.
1908 gridData.nestedItemFieldValue = function(obj, column) {
1909 item = obj; // keep a copy around
1911 if (obj === null || obj === undefined || obj === '') return '';
1912 if (!column.path) return obj;
1915 var parts = column.path.split('.');
1917 angular.forEach(parts, function(step, idx) {
1918 // object is not fleshed to the expected extent
1919 if (typeof obj != 'object') {
1920 if (typeof obj != 'undefined' && column.flesher) {
1921 obj = column.flesher(obj, column, item);
1928 if (!obj) return '';
1930 var cls = obj.classname;
1931 if (cls && (class_obj = egCore.idl.classes[cls])) {
1932 idl_field = class_obj.field_map[step];
1933 obj = obj[step] ? obj[step]() : '';
1935 if (angular.isFunction(obj[step])) {
1943 // We found a nested IDL object which may or may not have
1944 // been configured as a top-level column. Grab the datatype.
1945 if (idl_field && !column.datatype)
1946 column.datatype = idl_field.datatype;
1948 if (obj === null || obj === undefined || obj === '') return '';
1954 instance : function(args) {
1955 return new GridDataProvider(args);
1962 // Factory service for egGridDataManager instances, which are
1963 // responsible for collecting flattened grid data.
1964 .factory('egGridFlatDataProvider',
1965 ['$q','egCore','egGridDataProvider',
1966 function($q , egCore , egGridDataProvider) {
1969 instance : function(args) {
1970 var provider = egGridDataProvider.instance(args);
1972 provider.get = function(offset, count) {
1974 // no query means no call
1975 if (!provider.query ||
1976 angular.equals(provider.query, {}))
1979 // find all of the currently visible columns
1980 var queryFields = {}
1981 angular.forEach(provider.columnsProvider.columns,
1983 // only query IDL-tracked columns
1984 if (!col.adhoc && col.name && col.path && (col.required || col.visible))
1985 queryFields[col.name] = col.path;
1989 return egCore.net.request(
1991 'open-ils.fielder.flattened_search',
1992 egCore.auth.token(), provider.idlClass,
1993 queryFields, provider.query,
1994 { sort : provider.sort,
2000 //provider.itemFieldValue = provider.flatItemFieldValue;
2007 .directive('egGridColumnDragSource', function() {
2010 require : '^egGrid',
2011 link : function(scope, element, attrs, egGridCtrl) {
2012 angular.element(element).attr('draggable', 'true');
2014 element.bind('dragstart', function(e) {
2015 egGridCtrl.dragColumn = attrs.column;
2016 egGridCtrl.dragType = attrs.dragType || 'move'; // or resize
2017 egGridCtrl.colResizeDir = 0;
2019 if (egGridCtrl.dragType == 'move') {
2020 // style the column getting moved
2021 angular.element(e.target).addClass(
2022 'eg-grid-column-move-handle-active');
2026 element.bind('dragend', function(e) {
2027 if (egGridCtrl.dragType == 'move') {
2028 angular.element(e.target).removeClass(
2029 'eg-grid-column-move-handle-active');
2036 .directive('egGridColumnDragDest', function() {
2039 require : '^egGrid',
2040 link : function(scope, element, attrs, egGridCtrl) {
2042 element.bind('dragover', function(e) { // required for drop
2043 e.stopPropagation();
2045 e.dataTransfer.dropEffect = 'move';
2047 if (egGridCtrl.colResizeDir == 0) return; // move
2049 var cols = egGridCtrl.columnsProvider;
2050 var srcCol = egGridCtrl.dragColumn;
2051 var srcColIdx = cols.indexOf(srcCol);
2053 if (egGridCtrl.colResizeDir == -1) {
2054 if (cols.indexOf(attrs.column) <= srcColIdx) {
2055 egGridCtrl.modifyColumnFlex(
2056 egGridCtrl.columnsProvider.findColumn(
2057 egGridCtrl.dragColumn), -1);
2058 if (cols.columns[srcColIdx+1]) {
2059 // source column shrinks by one, column to the
2060 // right grows by one.
2061 egGridCtrl.modifyColumnFlex(
2062 cols.columns[srcColIdx+1], 1);
2067 if (cols.indexOf(attrs.column) > srcColIdx) {
2068 egGridCtrl.modifyColumnFlex(
2069 egGridCtrl.columnsProvider.findColumn(
2070 egGridCtrl.dragColumn), 1);
2071 if (cols.columns[srcColIdx+1]) {
2072 // source column grows by one, column to the
2073 // right grows by one.
2074 egGridCtrl.modifyColumnFlex(
2075 cols.columns[srcColIdx+1], -1);
2083 element.bind('dragenter', function(e) {
2084 e.stopPropagation();
2086 if (egGridCtrl.dragType == 'move') {
2087 angular.element(e.target).addClass('eg-grid-col-hover');
2089 // resize grips are on the right side of each column.
2090 // dragenter will either occur on the source column
2091 // (dragging left) or the column to the right.
2092 if (egGridCtrl.colResizeDir == 0) {
2093 if (egGridCtrl.dragColumn == attrs.column) {
2094 egGridCtrl.colResizeDir = -1; // west
2096 egGridCtrl.colResizeDir = 1; // east
2102 element.bind('dragleave', function(e) {
2103 e.stopPropagation();
2105 if (egGridCtrl.dragType == 'move') {
2106 angular.element(e.target).removeClass('eg-grid-col-hover');
2110 element.bind('drop', function(e) {
2111 e.stopPropagation();
2113 egGridCtrl.colResizeDir = 0;
2114 if (egGridCtrl.dragType == 'move') {
2115 angular.element(e.target).removeClass('eg-grid-col-hover');
2116 egGridCtrl.onColumnDrop(attrs.column); // move the column
2123 .directive('egGridMenuItem', function() {
2126 require : '^egGrid',
2132 handler : '=', // onclick handler function
2133 divider : '=', // if true, show a divider only
2134 handlerData : '=', // if set, passed as second argument to handler
2135 disabled : '=', // function
2136 hidden : '=' // function
2138 link : function(scope, element, attrs, egGridCtrl) {
2139 egGridCtrl.addMenuItem({
2140 checkbox : scope.checkbox,
2141 checked : scope.checked ? true : false,
2142 label : scope.label,
2143 standalone : scope.standalone ? true : false,
2144 handler : scope.handler,
2145 divider : scope.divider,
2146 disabled : scope.disabled,
2147 hidden : scope.hidden,
2148 handlerData : scope.handlerData
2155 /* https://stackoverflow.com/questions/17343696/adding-an-ng-click-event-inside-a-filter/17344875#17344875 */
2156 .directive('compile', ['$compile', function ($compile) {
2157 return function(scope, element, attrs) {
2158 // pass through column defs from grid cell's scope
2159 scope.col = scope.$parent.col;
2162 // watch the 'compile' expression for changes
2163 return scope.$eval(attrs.compile);
2166 // when the 'compile' expression changes
2167 // assign it into the current DOM
2168 element.html(value);
2170 // compile the new DOM and link it to the current
2172 // NOTE: we only compile .childNodes so that
2173 // we don't get into infinite loop compiling ourselves
2174 $compile(element.contents())(scope);
2183 * Translates bare IDL object values into display values.
2184 * 1. Passes dates through the angular date filter
2185 * 2. Converts bools to translated Yes/No strings
2186 * Others likely to follow...
2188 .filter('egGridValueFilter', ['$filter','egCore', 'egStrings', function($filter,egCore,egStrings) {
2189 function traversePath(obj,path) {
2190 var list = path.split('.');
2191 for (var part in path) {
2192 if (obj[path]) obj = obj[path]
2198 var GVF = function(value, column, item) {
2199 switch(column.datatype) {
2202 // Browser will translate true/false for us
2204 case '1' : // legacy
2206 return egStrings.YES;
2208 case '0' : // legacy
2210 return egStrings.NO;
2211 // value may be null, '', etc.
2212 default : return '';
2215 var interval = angular.isFunction(item[column.dateonlyinterval])
2216 ? item[column.dateonlyinterval]()
2217 : item[column.dateonlyinterval];
2219 if (column.dateonlyinterval && !interval) // try it as a dotted path
2220 interval = traversePath(item, column.dateonlyinterval);
2222 var context = angular.isFunction(item[column.datecontext])
2223 ? item[column.datecontext]()
2224 : item[column.datecontext];
2226 if (column.datecontext && !context) // try it as a dotted path
2227 context = traversePath(item, column.datecontext);
2229 var date_filter = column.datefilter || 'egOrgDateInContext';
2231 return $filter(date_filter)(value, column.dateformat, context, interval);
2233 return $filter('currency')(value);
2239 GVF.$stateful = true;