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',
131 function($scope, $q , egCore, egGridFlatDataProvider , $location,
132 egGridColumnsProvider , $filter , $window , $sce , $timeout,
133 egProgressDialog , $uibModal) {
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 if (grid.persistKey) {
175 var stored_limit = Number(
176 egCore.hatch.getLocalItem('eg.grid.' + grid.persistKey + '.limit')
180 stored_limit = 10000; // maybe support "Inf"?
183 grid.limit = Number(stored_limit) || Number($scope.pageSize) || 25;
185 grid.indexField = $scope.idField;
186 delete $scope.idField;
188 grid.dataProvider = $scope.itemsProvider;
190 if (!grid.indexField && grid.idlClass)
191 grid.indexField = egCore.idl.classes[grid.idlClass].pkey;
193 grid.columnsProvider = egGridColumnsProvider.instance({
194 idlClass : grid.idlClass,
195 clientSort : (features.indexOf('clientsort') > -1 && features.indexOf('-clientsort') == -1),
196 defaultToHidden : (features.indexOf('-display') > -1),
197 defaultToNoSort : (features.indexOf('-sort') > -1),
198 defaultToNoMultiSort : (features.indexOf('-multisort') > -1),
199 defaultDateFormat : $scope.dateformat,
200 defaultDateContext : $scope.datecontext,
201 defaultDateFilter : $scope.datefilter,
202 defaultDateOnlyInterval : $scope.dateonlyinterval
204 $scope.canMultiSelect = (features.indexOf('-multiselect') == -1);
206 $scope.handleAutoFields = function() {
207 if ($scope.autoFields) {
208 if (grid.autoLabel) {
210 egCore.idl.classes[grid.idlClass].label;
212 grid.columnsProvider.compileAutoColumns();
213 delete $scope.autoFields;
217 if (!grid.dataProvider) {
218 // no provider, um, provided.
219 // Use a flat data provider
221 grid.selfManagedData = true;
222 grid.dataProvider = egGridFlatDataProvider.instance({
223 indexField : grid.indexField,
224 idlClass : grid.idlClass,
225 columnsProvider : grid.columnsProvider,
230 // make grid ref available in get() to set totalCount, if known.
231 // this allows us disable the 'next' paging button correctly
232 grid.dataProvider.grid = grid;
234 grid.dataProvider.columnsProvider = grid.columnsProvider;
236 $scope.itemFieldValue = grid.dataProvider.itemFieldValue;
237 $scope.indexValue = function(item) {
238 return grid.indexValue(item)
241 grid.applyControlFunctions();
243 grid.loadConfig().then(function() {
244 // link columns to scope after loadConfig(), since it
245 // replaces the columns array.
246 $scope.columns = grid.columnsProvider.columns;
249 // NOTE: grid.collect() is first called from link(), not here.
252 // link our control functions into the gridControls
253 // scope object so the caller can access them.
254 grid.applyControlFunctions = function() {
256 // we use some of these controls internally, so sett
257 // them up even if the caller doesn't request them.
258 var controls = $scope.gridControls || {};
260 controls.columnMap = function() {
262 angular.forEach(grid.columnsProvider.columns, function (c) {
268 controls.columnsProvider = function() {
269 return grid.columnsProvider;
272 // link in the control functions
273 controls.selectedItems = function() {
274 return grid.getSelectedItems()
277 controls.allItems = function() {
281 controls.selectItems = function(ids) {
283 $scope.selected = {};
284 angular.forEach(ids, function(i) {
285 $scope.selected[''+i] = true;
289 // if the caller provided a functional setQuery,
290 // extract the value before replacing it
291 if (controls.setQuery) {
292 grid.dataProvider.query =
296 controls.setQuery = function(query) {
297 grid.dataProvider.query = query;
301 if (controls.watchQuery) {
302 // capture the initial query value
303 grid.dataProvider.query = controls.watchQuery();
306 $scope.gridWatchQuery = controls.watchQuery;
307 $scope.$watch('gridWatchQuery()', function(newv) {
308 controls.setQuery(newv);
312 // if the caller provided a functional setSort
313 // extract the value before replacing it
314 grid.dataProvider.sort =
315 controls.setSort ? controls.setSort() : [];
317 controls.setSort = function(sort) {
321 controls.refresh = function(noReset) {
322 if (!noReset) grid.offset = 0;
326 controls.setLimit = function(limit,forget) {
327 if (!forget && grid.persistKey)
328 egCore.hatch.setLocalItem('eg.grid.' + grid.persistKey + '.limit', limit);
331 controls.getLimit = function() {
334 controls.setOffset = function(offset) {
335 grid.offset = offset;
337 controls.getOffset = function() {
341 controls.saveConfig = function () {
342 return $scope.saveConfig();
345 grid.dataProvider.refresh = controls.refresh;
346 grid.controls = controls;
349 // If a menu item provides its own HTML template, translate it,
350 // using the menu item for the template scope.
351 // note: $sce is required to avoid security restrictions and
352 // is OK here, since the template comes directly from a
353 // local HTML template (not user input).
354 $scope.translateMenuItemTemplate = function(item) {
355 var html = egCore.strings.$replace(item.template, {item : item});
356 return $sce.trustAsHtml(html);
359 // add a new (global) grid menu item
360 grid.addMenuItem = function(item) {
361 $scope.menuItems.push(item);
362 var handler = item.handler;
363 item.handler = function() {
364 $scope.gridMenuIsOpen = false; // close menu
367 item.handlerData, grid.getSelectedItems());
372 // add a selected-items action
373 grid.addAction = function(act) {
375 $scope.actionGroups.forEach(function(g){
376 if (g.label === act.group) {
382 $scope.actionGroups.push({
389 // remove the stored column configuration preferenc, then recover
390 // the column visibility information from the initial page load.
391 $scope.resetColumns = function() {
392 $scope.gridColumnPickerIsOpen = false;
393 egCore.hatch.removeItem('eg.grid.' + grid.persistKey)
395 grid.columnsProvider.reset();
396 if (grid.selfManagedData) grid.collect();
400 $scope.showAllColumns = function() {
401 $scope.gridColumnPickerIsOpen = false;
402 grid.columnsProvider.showAllColumns();
403 if (grid.selfManagedData) grid.collect();
406 $scope.hideAllColumns = function() {
407 $scope.gridColumnPickerIsOpen = false;
408 grid.columnsProvider.hideAllColumns();
409 // note: no need to fetch new data if no columns are visible
412 $scope.toggleColumnVisibility = function(col) {
413 $scope.gridColumnPickerIsOpen = false;
414 col.visible = !col.visible;
416 // egGridFlatDataProvider only retrieves data to be
417 // displayed. When column visibility changes, it's
418 // necessary to fetch the newly visible column data.
419 if (grid.selfManagedData) grid.collect();
422 // save the columns configuration (position, sort, width) to
423 // eg.grid.<persist-key>
424 $scope.saveConfig = function() {
425 $scope.gridColumnPickerIsOpen = false;
427 if (!grid.persistKey) {
429 "Cannot save settings without a grid persist-key");
433 // only store information about visible columns.
434 var conf = grid.columnsProvider.columns.filter(
435 function(col) {return Boolean(col.visible) });
437 // now scrunch the data down to just the needed info
438 conf = conf.map(function(col) {
439 var c = {name : col.name}
440 // Apart from the name, only store non-default values.
441 // No need to store col.visible, since that's implicit
442 if (col.align != 'left') c.align = col.align;
443 if (col.flex != 2) c.flex = col.flex;
444 if (Number(col.sort)) c.sort = Number(c.sort);
448 egCore.hatch.setItem('eg.grid.' + grid.persistKey, conf)
450 // Save operation performed from the grid configuration UI.
451 // Hide the configuration UI and re-draw w/ sort applied
452 if ($scope.showGridConf)
453 $scope.toggleConfDisplay();
458 // load the columns configuration (position, sort, width) from
459 // eg.grid.<persist-key> and apply the loaded settings to the
460 // columns on our columnsProvider
461 grid.loadConfig = function() {
462 if (!grid.persistKey) return $q.when();
464 return egCore.hatch.getItem('eg.grid.' + grid.persistKey)
465 .then(function(conf) {
468 var columns = grid.columnsProvider.columns;
471 angular.forEach(conf, function(col) {
472 var grid_col = columns.filter(
473 function(c) {return c.name == col.name})[0];
476 // saved column does not match a column in the
477 // current grid. skip it.
481 grid_col.align = col.align || 'left';
482 grid_col.flex = col.flex || 2;
483 grid_col.sort = col.sort || 0;
484 // all saved columns are assumed to be true
485 grid_col.visible = true;
487 .filter(function (c) {
488 return c.name == grid_col.name;
491 new_cols.push(grid_col);
494 // columns which are not expressed within the saved
495 // configuration are marked as non-visible and
496 // appended to the end of the new list of columns.
497 angular.forEach(columns, function(col) {
498 var found = conf.filter(
499 function(c) {return (c.name == col.name)})[0];
506 grid.columnsProvider.columns = new_cols;
512 $scope.onContextMenu = function($event) {
513 var col = angular.element($event.target).attr('column');
514 console.log('selected column ' + col);
517 $scope.page = function() {
518 return (grid.offset / grid.limit) + 1;
521 $scope.goToPage = function(page) {
523 if (angular.isNumber(page) && page > 0) {
524 grid.offset = (page - 1) * grid.limit;
529 $scope.offset = function(o) {
530 if (angular.isNumber(o))
535 $scope.limit = function(l) {
536 if (angular.isNumber(l)) {
538 egCore.hatch.setLocalItem('eg.grid.' + grid.persistKey + '.limit', l);
544 $scope.onFirstPage = function() {
545 return grid.offset == 0;
548 $scope.hasNextPage = function() {
549 // we have less data than requested, there must
550 // not be any more pages
551 if (grid.count() < grid.limit) return false;
553 // if the total count is not known, assume that a full
554 // page of data implies more pages are available.
555 if (grid.totalCount == -1) return true;
557 // we have a full page of data, but is there more?
558 return grid.totalCount > (grid.offset + grid.count());
561 $scope.incrementPage = function() {
562 grid.offset += grid.limit;
566 $scope.decrementPage = function() {
567 if (grid.offset < grid.limit) {
570 grid.offset -= grid.limit;
575 // number of items loaded for the current page of results
576 grid.count = function() {
577 return $scope.items.length;
580 // returns the unique identifier value for the provided item
581 // for internal consistency, indexValue is always coerced
583 grid.indexValue = function(item) {
584 if (angular.isObject(item)) {
586 if (angular.isFunction(item[grid.indexField]))
587 return ''+item[grid.indexField]();
588 return ''+item[grid.indexField]; // flat data
591 // passed a non-object; assume it's an index
595 // fires the hide handler function for a context action
596 $scope.actionHide = function(action) {
597 if (typeof action.hide == 'undefined') {
600 if (angular.isFunction(action.hide))
601 return action.hide(action);
605 // fires the disable handler function for a context action
606 $scope.actionDisable = function(action) {
607 if (typeof action.disabled == 'undefined') {
610 if (angular.isFunction(action.disabled))
611 return action.disabled(action);
612 return action.disabled;
615 // fires the action handler function for a context action
616 $scope.actionLauncher = function(action) {
617 if (!action.handler) {
619 'No handler specified for "' + action.label + '"');
623 action.handler(grid.getSelectedItems());
625 console.error('Error executing handler for "'
626 + action.label + '" => ' + E + "\n" + E.stack);
629 if ($scope.action_context_showing) $scope.hideActionContextMenu();
634 $scope.hideActionContextMenu = function () {
635 $($scope.menu_dom).css({
637 width: $scope.action_context_width,
638 top: $scope.action_context_y,
639 left: $scope.action_context_x
641 $($scope.action_context_parent).append($scope.menu_dom);
642 $scope.action_context_oldy = $scope.action_context_oldx = 0;
643 $('body').unbind('click.remove_context_menu_'+$scope.action_context_index);
644 $scope.action_context_showing = false;
647 $scope.action_context_showing = false;
648 $scope.showActionContextMenu = function ($event) {
650 // Have to gather these here, instead of inside link()
651 if (!$scope.menu_dom) $scope.menu_dom = $($scope.grid_element).find('.grid-action-dropdown')[0];
652 if (!$scope.action_context_parent) $scope.action_context_parent = $($scope.menu_dom).parent();
654 if (!grid.getSelectedItems().length) // Nothing selected, fire the click event
655 $event.target.click();
657 if (!$scope.action_context_showing) {
658 $scope.action_context_width = $($scope.menu_dom).css('width');
659 $scope.action_context_y = $($scope.menu_dom).css('top');
660 $scope.action_context_x = $($scope.menu_dom).css('left');
661 $scope.action_context_showing = true;
662 $scope.action_context_index = Math.floor((Math.random() * 1000) + 1);
664 $('body').append($($scope.menu_dom));
665 $('body').bind('click.remove_context_menu_'+$scope.action_context_index, $scope.hideActionContextMenu);
668 $($scope.menu_dom).css({
670 width: $scope.action_context_width,
678 // returns the list of selected item objects
679 grid.getSelectedItems = function() {
680 return $scope.items.filter(
682 return Boolean($scope.selected[grid.indexValue(item)]);
687 grid.getItemByIndex = function(index) {
688 for (var i = 0; i < $scope.items.length; i++) {
689 var item = $scope.items[i];
690 if (grid.indexValue(item) == index)
695 // selects one row after deselecting all of the others
696 grid.selectOneItem = function(index) {
697 $scope.selected = {};
698 $scope.selected[index] = true;
701 // selects or deselects an item, without affecting the others.
702 // returns true if the item is selected; false if de-selected.
703 // we overwrite the object so that we can watch $scope.selected
704 grid.toggleSelectOneItem = function(index) {
705 if ($scope.selected[index]) {
706 delete $scope.selected[index];
707 $scope.selected = angular.copy($scope.selected);
710 $scope.selected[index] = true;
711 $scope.selected = angular.copy($scope.selected);
716 $scope.updateSelected = function () {
717 return $scope.selected = angular.copy($scope.selected);
720 grid.selectAllItems = function() {
721 angular.forEach($scope.items, function(item) {
722 $scope.selected[grid.indexValue(item)] = true
724 $scope.selected = angular.copy($scope.selected);
727 $scope.$watch('selectAll', function(newVal) {
729 grid.selectAllItems();
731 $scope.selected = {};
735 if ($scope.onSelect) {
736 $scope.$watch('selected', function(newVal) {
737 $scope.onSelect(grid.getSelectedItems());
738 if ($scope.afterSelect) $scope.afterSelect();
742 // returns true if item1 appears in the list before item2;
743 // false otherwise. this is slightly more efficient that
744 // finding the position of each then comparing them.
745 // item1 / item2 may be an item or an item index
746 grid.itemComesBefore = function(itemOrIndex1, itemOrIndex2) {
747 var idx1 = grid.indexValue(itemOrIndex1);
748 var idx2 = grid.indexValue(itemOrIndex2);
750 // use for() for early exit
751 for (var i = 0; i < $scope.items.length; i++) {
752 var idx = grid.indexValue($scope.items[i]);
753 if (idx == idx1) return true;
754 if (idx == idx2) return false;
759 // 0-based position of item in the current data set
760 grid.indexOf = function(item) {
761 var idx = grid.indexValue(item);
762 for (var i = 0; i < $scope.items.length; i++) {
763 if (grid.indexValue($scope.items[i]) == idx)
769 grid.modifyColumnFlex = function(column, val) {
771 // prevent flex:0; use hiding instead
775 $scope.modifyColumnFlex = function(col, val) {
776 $scope.lastModColumn = col;
777 grid.modifyColumnFlex(col, val);
780 $scope.isLastModifiedColumn = function(col) {
781 if ($scope.lastModColumn)
782 return $scope.lastModColumn === col;
786 grid.modifyColumnPos = function(col, diff) {
787 var srcIdx, targetIdx;
788 angular.forEach(grid.columnsProvider.columns,
789 function(c, i) { if (c.name == col.name) srcIdx = i });
791 targetIdx = srcIdx + diff;
794 } else if (targetIdx >= grid.columnsProvider.columns.length) {
795 // Target index follows the last visible column.
797 angular.forEach(grid.columnsProvider.columns,
798 function(column, idx) {
799 if (column.visible) lastVisible = idx;
803 // When moving a column (down) causes one or more
804 // visible columns to shuffle forward, our column
805 // moves into the slot of the last visible column.
806 // Otherwise, put it into the slot directly following
807 // the last visible column.
809 srcIdx <= lastVisible ? lastVisible : lastVisible + 1;
812 // Splice column out of old position, insert at new position.
813 grid.columnsProvider.columns.splice(srcIdx, 1);
814 grid.columnsProvider.columns.splice(targetIdx, 0, col);
817 $scope.modifyColumnPos = function(col, diff) {
818 $scope.lastModColumn = col;
819 return grid.modifyColumnPos(col, diff);
823 // handles click, control-click, and shift-click
824 $scope.handleRowClick = function($event, item) {
825 var index = grid.indexValue(item);
827 var origSelected = Object.keys($scope.selected);
829 if (!$scope.canMultiSelect) {
830 grid.selectOneItem(index);
831 grid.lastSelectedItemIndex = index;
835 if ($event.ctrlKey || $event.metaKey /* mac command */) {
837 if (grid.toggleSelectOneItem(index))
838 grid.lastSelectedItemIndex = index;
840 } else if ($event.shiftKey) {
843 if (!grid.lastSelectedItemIndex ||
844 index == grid.lastSelectedItemIndex) {
845 grid.selectOneItem(index);
846 grid.lastSelectedItemIndex = index;
850 var selecting = false;
851 var ascending = grid.itemComesBefore(
852 grid.lastSelectedItemIndex, item);
854 grid.indexOf(grid.lastSelectedItemIndex);
856 // update to new last-selected
857 grid.lastSelectedItemIndex = index;
859 // select each row between the last selected and
860 // currently selected items
862 startPos += ascending ? 1 : -1;
863 var curItem = $scope.items[startPos];
865 var curIdx = grid.indexValue(curItem);
866 $scope.selected[curIdx] = true;
867 if (curIdx == index) break; // all done
869 $scope.selected = angular.copy($scope.selected);
873 grid.selectOneItem(index);
874 grid.lastSelectedItemIndex = index;
878 // Builds a sort expression from column sort priorities.
879 // called on page load and any time the priorities are modified.
880 grid.compileSort = function() {
881 var sortList = grid.columnsProvider.columns.filter(
882 function(col) { return Number(col.sort) != 0 }
885 if (Math.abs(a.sort) < Math.abs(b.sort))
891 if (sortList.length) {
892 grid.dataProvider.sort = sortList.map(function(col) {
894 blob[col.name] = col.sort < 0 ? 'desc' : 'asc';
900 // builds a sort expression using a single column,
901 // toggling between ascending and descending sort.
902 $scope.quickSort = function(col_name) {
903 var sort = grid.dataProvider.sort;
904 if (sort && sort.length &&
905 sort[0] == col_name) {
907 blob[col_name] = 'desc';
908 grid.dataProvider.sort = [blob];
910 grid.dataProvider.sort = [col_name];
917 // show / hide the grid configuration row
918 $scope.toggleConfDisplay = function() {
919 if ($scope.showGridConf) {
920 $scope.showGridConf = false;
921 if (grid.columnsProvider.hasSortableColumn()) {
922 // only refresh the grid if the user has the
923 // ability to modify the sort priorities.
929 $scope.showGridConf = true;
932 delete $scope.lastModColumn;
933 $scope.gridColumnPickerIsOpen = false;
936 // called when a dragged column is dropped onto itself
937 // or any other column
938 grid.onColumnDrop = function(target) {
939 if (angular.isUndefined(target)) return;
940 if (target == grid.dragColumn) return;
941 var srcIdx, targetIdx, srcCol;
942 angular.forEach(grid.columnsProvider.columns,
944 if (col.name == grid.dragColumn) {
947 } else if (col.name == target) {
953 if (srcIdx < targetIdx) targetIdx--;
955 // move src column from old location to new location in
956 // the columns array, then force a page refresh
957 grid.columnsProvider.columns.splice(srcIdx, 1);
958 grid.columnsProvider.columns.splice(targetIdx, 0, srcCol);
962 // prepares a string for inclusion within a CSV document
963 // by escaping commas and quotes and removing newlines.
964 grid.csvDatum = function(str) {
967 str = str.replace(/\n/g, '');
968 if (str.match(/\,/) || str.match(/"/)) {
969 str = str.replace(/"/g, '""');
970 str = '"' + str + '"';
975 /** Export the full data set as CSV.
977 * 1. User clicks the 'download csv' link
978 * 2. All grid data is retrieved asychronously
979 * 3. Once all data is all present and CSV-ized, the download
980 * attributes are linked to the href.
981 * 4. The href .click() action is prgrammatically fired again,
982 * telling the browser to download the data, now that the
983 * data is available for download.
984 * 5 Once downloaded, the href attributes are reset.
986 grid.csvExportInProgress = false;
987 $scope.generateCSVExportURL = function($event) {
989 if (grid.csvExportInProgress) {
990 // This is secondary href click handler. Give the
991 // browser a moment to start the download, then reset
992 // the CSV download attributes / state.
995 $scope.csvExportURL = '';
996 $scope.csvExportFileName = '';
997 grid.csvExportInProgress = false;
1003 grid.csvExportInProgress = true;
1004 $scope.gridColumnPickerIsOpen = false;
1006 // let the file name describe the grid
1007 $scope.csvExportFileName =
1008 ($scope.mainLabel || grid.persistKey || 'eg_grid_data')
1009 .replace(/\s+/g, '_') + '_' + $scope.page();
1011 // toss the CSV into a Blob and update the export URL
1012 grid.generateCSV().then(function(csv) {
1013 var blob = new Blob([csv], {type : 'text/plain'});
1014 $scope.csvExportURL =
1015 ($window.URL || $window.webkitURL).createObjectURL(blob);
1017 // Fire the 2nd click event now that the browser has
1018 // information on how to download the CSV file.
1019 $timeout(function() {$event.target.click()});
1024 * TODO: does this serve any purpose given we can
1025 * print formatted HTML? If so, generateCSV() now
1026 * returns a promise, needs light refactoring...
1027 $scope.printCSV = function() {
1028 $scope.gridColumnPickerIsOpen = false;
1029 egCore.print.print({
1030 context : 'default',
1031 content : grid.generateCSV(),
1032 content_type : 'text/plain'
1037 // Given a row item and column definition, extract the
1038 // text content for printing. Templated columns must be
1039 // processed and parsed as HTML, then boiled down to their
1041 grid.getItemTextContent = function(item, col) {
1044 val = $scope.translateCellTemplate(col, item);
1046 var node = new DOMParser()
1047 .parseFromString(val, 'text/html');
1048 val = $(node).text();
1051 val = grid.dataProvider.itemFieldValue(item, col);
1052 val = $filter('egGridValueFilter')(val, col, item);
1058 * Fetches all grid data and transates each item into a simple
1059 * key-value pair of column name => text-value.
1060 * Included in the response for convenience is the list of
1061 * currently visible column definitions.
1062 * TODO: currently fetches a maximum of 10k rows. Does this
1063 * need to be configurable?
1065 grid.getAllItemsAsText = function() {
1066 var text_items = [];
1068 // we don't know the total number of rows we're about
1069 // to retrieve, but we can indicate the number retrieved
1070 // so far as each item arrives.
1071 egProgressDialog.open({value : 0});
1073 var visible_cols = grid.columnsProvider.columns.filter(
1074 function(c) { return c.visible });
1076 return grid.dataProvider.get(0, 10000).then(
1078 return {items : text_items, columns : visible_cols};
1082 egProgressDialog.increment();
1084 angular.forEach(visible_cols, function(col) {
1085 text_item[col.name] =
1086 grid.getItemTextContent(item, col);
1088 text_items.push(text_item);
1090 ).finally(egProgressDialog.close);
1093 // Fetch "all" of the grid data, translate it into print-friendly
1094 // text, and send it to the printer service.
1095 $scope.printHTML = function() {
1096 $scope.gridColumnPickerIsOpen = false;
1097 return grid.getAllItemsAsText().then(function(text_items) {
1098 return egCore.print.print({
1099 template : 'grid_html',
1105 $scope.showColumnDialog = function() {
1106 return $uibModal.open({
1107 templateUrl: './share/t_grid_columns',
1110 controller: ['$scope', '$uibModalInstance',
1111 function($dialogScope, $uibModalInstance) {
1112 $dialogScope.modifyColumnPos = $scope.modifyColumnPos;
1113 $dialogScope.disableMultiSort = $scope.disableMultiSort;
1114 $dialogScope.columns = $scope.columns;
1116 // Push visible columns to the top of the list
1117 $dialogScope.elevateVisible = function() {
1119 angular.forEach($dialogScope.columns, function(col) {
1120 if (col.visible) new_cols.push(col);
1122 angular.forEach($dialogScope.columns, function(col) {
1123 if (!col.visible) new_cols.push(col);
1126 // Update all references to the list of columns
1127 $dialogScope.columns =
1129 grid.columnsProvider.columns =
1133 $dialogScope.toggle = function(col) {
1134 col.visible = !Boolean(col.visible);
1136 $dialogScope.ok = $dialogScope.cancel = function() {
1137 delete $scope.lastModColumn;
1138 $uibModalInstance.close()
1145 // generates CSV for the currently visible grid contents
1146 grid.generateCSV = function() {
1147 return grid.getAllItemsAsText().then(function(text_items) {
1148 var columns = text_items.columns;
1149 var items = text_items.items;
1153 angular.forEach(columns, function(col) {
1154 csvStr += grid.csvDatum(col.label);
1158 csvStr = csvStr.replace(/,$/,'\n');
1161 angular.forEach(items, function(item) {
1162 angular.forEach(columns, function(col) {
1163 csvStr += grid.csvDatum(item[col.name]);
1166 csvStr = csvStr.replace(/,$/,'\n');
1173 // Interpolate the value for column.linkpath within the context
1174 // of the row item to generate the final link URL.
1175 $scope.generateLinkPath = function(col, item) {
1176 return egCore.strings.$replace(col.linkpath, {item : item});
1179 // If a column provides its own HTML template, translate it,
1180 // using the current item for the template scope.
1181 // note: $sce is required to avoid security restrictions and
1182 // is OK here, since the template comes directly from a
1183 // local HTML template (not user input).
1184 $scope.translateCellTemplate = function(col, item) {
1185 var html = egCore.strings.$replace(col.template, {item : item});
1186 return $sce.trustAsHtml(html);
1189 $scope.collect = function() { grid.collect() }
1191 // asks the dataProvider for a page of data
1192 grid.collect = function() {
1194 // avoid firing the collect if there is nothing to collect.
1195 if (grid.selfManagedData && !grid.dataProvider.query) return;
1197 if (grid.collecting) return; // avoid parallel collect()
1198 grid.collecting = true;
1200 console.debug('egGrid.collect() offset='
1201 + grid.offset + '; limit=' + grid.limit);
1203 // ensure all of our dropdowns are closed
1204 // TODO: git rid of these and just use dropdown-toggle,
1205 // which is more reliable.
1206 $scope.gridColumnPickerIsOpen = false;
1207 $scope.gridRowCountIsOpen = false;
1208 $scope.gridPageSelectIsOpen = false;
1211 $scope.selected = {};
1213 // Inform the caller we've asked the data provider
1214 // for data. This is useful for knowing when collection
1215 // has started (e.g. to display a progress dialg) when
1216 // using the stock (flattener) data provider, where the
1217 // user is not directly defining a get() handler.
1218 if (grid.controls.collectStarted)
1219 grid.controls.collectStarted(grid.offset, grid.limit);
1221 grid.dataProvider.get(grid.offset, grid.limit).then(
1223 if (grid.controls.allItemsRetrieved)
1224 grid.controls.allItemsRetrieved();
1229 $scope.items.push(item)
1230 if (grid.controls.itemRetrieved)
1231 grid.controls.itemRetrieved(item);
1232 if ($scope.selectAll)
1233 $scope.selected[grid.indexValue(item)] = true
1235 }).finally(function() {
1236 console.debug('egGrid.collect() complete');
1237 grid.collecting = false
1238 $scope.selected = angular.copy($scope.selected);
1248 * eg-grid-field : used for collecting custom field data from the templates.
1249 * This directive does not direct display, it just passes data up to the
1252 .directive('egGridField', function() {
1254 require : '^egGrid',
1257 flesher: '=', // optional; function that can flesh a linked field, given the value
1258 comparator: '=', // optional; function that can sort the thing at the end of 'path'
1259 name : '@', // required; unique name
1260 path : '@', // optional; flesh path
1261 ignore: '@', // optional; fields to ignore when path is a wildcard
1262 label : '@', // optional; display label
1263 flex : '@', // optional; default flex width
1264 align : '@', // optional; default alignment, left/center/right
1265 dateformat : '@', // optional: passed down to egGridValueFilter
1266 datecontext: '@', // optional: passed down to egGridValueFilter to choose TZ
1267 datefilter: '@', // optional: passed down to egGridValueFilter to choose specialized date filters
1268 dateonlyinterval: '@', // optional: passed down to egGridValueFilter to choose a "better" format
1270 // if a field is part of an IDL object, but we are unable to
1271 // determine the class, because it's nested within a hash
1272 // (i.e. we can't navigate directly to the object via the IDL),
1273 // idlClass lets us specify the class. This is particularly
1274 // useful for nested wildcard fields.
1275 parentIdlClass : '@',
1277 // optional: for non-IDL columns, specifying a datatype
1278 // lets the caller control which display filter is used.
1279 // datatype should match the standard IDL datatypes.
1282 // optional hash of functions that can be imported into
1283 // the directive's scope; meant for cases where the "compiled"
1287 link : function(scope, element, attrs, egGridCtrl) {
1289 // boolean fields are presented as value-less attributes
1299 'required' // if set, always fetch data for this column
1302 if (angular.isDefined(attrs[field]))
1303 scope[field] = true;
1307 // any HTML content within the field is its custom template
1308 var tmpl = element.html();
1309 if (tmpl && !tmpl.match(/^\s*$/))
1310 scope.template = tmpl
1312 egGridCtrl.columnsProvider.add(scope);
1319 * eg-grid-action : used for specifying actions which may be applied
1320 * to items within the grid.
1322 .directive('egGridAction', function() {
1324 require : '^egGrid',
1328 group : '@', // Action group, ungrouped if not set
1329 label : '@', // Action label
1330 handler : '=', // Action function handler
1332 disabled : '=', // function
1335 link : function(scope, element, attrs, egGridCtrl) {
1336 egGridCtrl.addAction({
1338 group : scope.group,
1339 label : scope.label,
1340 divider : scope.divider,
1341 handler : scope.handler,
1342 disabled : scope.disabled,
1349 .factory('egGridColumnsProvider', ['egCore', function(egCore) {
1351 function ColumnsProvider(args) {
1354 cols.stockVisible = [];
1355 cols.idlClass = args.idlClass;
1356 cols.clientSort = args.clientSort;
1357 cols.defaultToHidden = args.defaultToHidden;
1358 cols.defaultToNoSort = args.defaultToNoSort;
1359 cols.defaultToNoMultiSort = args.defaultToNoMultiSort;
1360 cols.defaultDateFormat = args.defaultDateFormat;
1361 cols.defaultDateContext = args.defaultDateContext;
1363 // resets column width, visibility, and sort behavior
1364 // Visibility resets to the visibility settings defined in the
1365 // template (i.e. the original egGridField values).
1366 cols.reset = function() {
1367 angular.forEach(cols.columns, function(col) {
1371 if (cols.stockVisible.indexOf(col.name) > -1) {
1374 col.visible = false;
1379 // returns true if any columns are sortable
1380 cols.hasSortableColumn = function() {
1381 return cols.columns.filter(
1383 return col.sortable || col.multisortable;
1388 cols.showAllColumns = function() {
1389 angular.forEach(cols.columns, function(column) {
1390 column.visible = true;
1394 cols.hideAllColumns = function() {
1395 angular.forEach(cols.columns, function(col) {
1400 cols.indexOf = function(name) {
1401 for (var i = 0; i < cols.columns.length; i++) {
1402 if (cols.columns[i].name == name)
1408 cols.findColumn = function(name) {
1409 return cols.columns[cols.indexOf(name)];
1412 cols.compileAutoColumns = function() {
1413 var idl_class = egCore.idl.classes[cols.idlClass];
1418 if (field.virtual) return;
1419 if (field.datatype == 'link' || field.datatype == 'org_unit') {
1420 // if the field is a link and the linked class has a
1421 // "selector" field specified, use the selector field
1422 // as the display field for the columns.
1423 // flattener will take care of the fleshing.
1424 if (field['class']) {
1425 var selector_field = egCore.idl.classes[field['class']].fields
1426 .filter(function(f) { return Boolean(f.selector) })[0];
1427 if (selector_field) {
1428 field.path = field.name + '.' + selector_field.selector;
1432 cols.add(field, true);
1437 // if a column definition has a path with a wildcard, create
1438 // columns for all non-virtual fields at the specified
1439 // position in the path.
1440 cols.expandPath = function(colSpec) {
1442 var ignoreList = [];
1444 ignoreList = colSpec.ignore.split(' ');
1446 var dotpath = colSpec.path.replace(/\.?\*$/,'');
1450 if (colSpec.parentIdlClass) {
1451 class_obj = egCore.idl.classes[colSpec.parentIdlClass];
1453 class_obj = egCore.idl.classes[cols.idlClass];
1455 var idl_parent = class_obj;
1456 var old_field_label = '';
1458 if (!class_obj) return;
1460 //console.debug('egGrid: auto dotpath is: ' + dotpath);
1461 var path_parts = dotpath.split(/\./);
1463 // find the IDL class definition for the last element in the
1464 // path before the .*
1465 // an empty path_parts means expand the root class
1468 for (var path_idx in path_parts) {
1469 old_field = idl_field;
1471 var part = path_parts[path_idx];
1472 idl_field = class_obj.field_map[part];
1474 // unless we're at the end of the list, this field should
1475 // link to another class.
1476 if (idl_field && idl_field['class'] && (
1477 idl_field.datatype == 'link' ||
1478 idl_field.datatype == 'org_unit')) {
1479 if (old_field_label) old_field_label += ' : ';
1480 old_field_label += idl_field.label;
1481 class_obj = egCore.idl.classes[idl_field['class']];
1482 if (old_field) idl_parent = old_field;
1484 if (path_idx < (path_parts.length - 1)) {
1485 // we ran out of classes to hop through before
1486 // we ran out of path components
1487 console.error("egGrid: invalid IDL path: " + dotpath);
1494 angular.forEach(class_obj.fields, function(field) {
1496 // Only show wildcard fields where we have data to show
1497 // Virtual and un-fleshed links will not have any data.
1498 if (field.virtual ||
1499 (field.datatype == 'link' || field.datatype == 'org_unit') ||
1500 ignoreList.indexOf(field.name) > -1
1504 var col = cols.cloneFromScope(colSpec);
1505 col.path = (dotpath ? dotpath + '.' + field.name : field.name);
1507 // log line below is very chatty. disable until needed.
1508 // console.debug('egGrid: field: ' +field.name + '; parent field: ' + js2JSON(idl_parent));
1509 cols.add(col, false, true,
1510 {idl_parent : idl_parent, idl_field : field, idl_class : class_obj, field_parent_label : old_field_label });
1513 cols.columns = cols.columns.sort(
1515 if (a.explicit) return -1;
1516 if (b.explicit) return 1;
1518 if (a.idlclass && b.idlclass) {
1519 if (a.idlclass < b.idlclass) return -1;
1520 if (b.idlclass < a.idlclass) return 1;
1523 if (a.path && b.path && a.path.lastIndexOf('.') && b.path.lastIndexOf('.')) {
1524 if (a.path.substring(0, a.path.lastIndexOf('.')) < b.path.substring(0, b.path.lastIndexOf('.'))) return -1;
1525 if (b.path.substring(0, b.path.lastIndexOf('.')) < a.path.substring(0, a.path.lastIndexOf('.'))) return 1;
1528 if (a.label && b.label) {
1529 if (a.label < b.label) return -1;
1530 if (b.label < a.label) return 1;
1533 return a.name < b.name ? -1 : 1;
1540 "egGrid: wildcard path does not resolve to an object: "
1545 // angular.clone(scopeObject) is not permittable. Manually copy
1546 // the fields over that we need (so the scope object can go away).
1547 cols.cloneFromScope = function(colSpec) {
1549 flesher : colSpec.flesher,
1550 comparator : colSpec.comparator,
1551 name : colSpec.name,
1552 label : colSpec.label,
1553 path : colSpec.path,
1554 align : colSpec.align || 'left',
1555 flex : Number(colSpec.flex) || 2,
1556 sort : Number(colSpec.sort) || 0,
1557 required : colSpec.required,
1558 linkpath : colSpec.linkpath,
1559 template : colSpec.template,
1560 visible : colSpec.visible,
1561 compiled : colSpec.compiled,
1562 handlers : colSpec.handlers,
1563 hidden : colSpec.hidden,
1564 datatype : colSpec.datatype,
1565 sortable : colSpec.sortable,
1566 nonsortable : colSpec.nonsortable,
1567 multisortable : colSpec.multisortable,
1568 nonmultisortable : colSpec.nonmultisortable,
1569 dateformat : colSpec.dateformat,
1570 datecontext : colSpec.datecontext,
1571 datefilter : colSpec.datefilter,
1572 dateonlyinterval : colSpec.dateonlyinterval,
1573 parentIdlClass : colSpec.parentIdlClass
1578 // Add a column to the columns collection.
1579 // Columns may come from a slim eg-columns-field or
1580 // directly from the IDL.
1581 cols.add = function(colSpec, fromIDL, fromExpand, idl_info) {
1583 // First added column with the specified path takes precedence.
1584 // This allows for specific definitions followed by wildcard
1585 // definitions. If a match is found, back out.
1586 if (cols.columns.filter(function(c) {
1587 return (c.path == colSpec.path) })[0]) {
1588 console.debug('skipping pre-existing column ' + colSpec.path);
1592 var column = fromExpand ? colSpec : cols.cloneFromScope(colSpec);
1594 if (column.path && column.path.match(/\*$/))
1595 return cols.expandPath(colSpec);
1597 if (!fromExpand) column.explicit = true;
1599 if (!column.name) column.name = column.path;
1600 if (!column.path) column.path = column.name;
1602 if (column.visible || (!cols.defaultToHidden && !column.hidden))
1603 column.visible = true;
1605 if (column.sortable || (!cols.defaultToNoSort && !column.nonsortable))
1606 column.sortable = true;
1608 if (column.multisortable ||
1609 (!cols.defaultToNoMultiSort && !column.nonmultisortable))
1610 column.multisortable = true;
1612 if (cols.defaultDateFormat && ! column.dateformat) {
1613 column.dateformat = cols.defaultDateFormat;
1616 if (cols.defaultDateOnlyInterval && ! column.dateonlyinterval) {
1617 column.dateonlyinterval = cols.defaultDateOnlyInterval;
1620 if (cols.defaultDateContext && ! column.datecontext) {
1621 column.datecontext = cols.defaultDateContext;
1624 if (cols.defaultDateFilter && ! column.datefilter) {
1625 column.datefilter = cols.defaultDateFilter;
1628 cols.columns.push(column);
1630 // Track which columns are visible by default in case we
1631 // need to reset column visibility
1633 cols.stockVisible.push(column.name);
1635 if (fromIDL) return; // directly from egIDL. nothing left to do.
1637 // lookup the matching IDL field
1638 if (!idl_info && cols.idlClass)
1639 idl_info = cols.idlFieldFromPath(column.path);
1642 // column is not represented within the IDL
1643 column.adhoc = true;
1647 column.datatype = idl_info.idl_field.datatype;
1649 if (!column.label) {
1650 column.label = idl_info.idl_field.label || column.name;
1653 if (fromExpand && idl_info.idl_class) {
1654 column.idlclass = '';
1655 if (idl_info.field_parent_label && idl_info.idl_parent.label != idl_info.idl_class.label) {
1656 column.idlclass = (idl_info.field_parent_label || idl_info.idl_parent.label || idl_info.idl_parent.name);
1658 column.idlclass += idl_info.idl_class.label || idl_info.idl_class.name;
1663 // finds the IDL field from the dotpath, using the columns
1664 // idlClass as the base.
1665 cols.idlFieldFromPath = function(dotpath) {
1666 var class_obj = egCore.idl.classes[cols.idlClass];
1667 if (!dotpath) return null;
1669 var path_parts = dotpath.split(/\./);
1673 for (var path_idx in path_parts) {
1674 var part = path_parts[path_idx];
1675 idl_parent = idl_field;
1676 idl_field = class_obj.field_map[part];
1679 if (idl_field['class'] && (
1680 idl_field.datatype == 'link' ||
1681 idl_field.datatype == 'org_unit')) {
1682 class_obj = egCore.idl.classes[idl_field['class']];
1690 idl_parent: idl_parent,
1691 idl_field : idl_field,
1692 idl_class : class_obj
1698 instance : function(args) { return new ColumnsProvider(args) }
1704 * Generic data provider template class. This is basically an abstract
1705 * class factory service whose instances can be locally modified to
1706 * meet the needs of each individual grid.
1708 .factory('egGridDataProvider',
1709 ['$q','$timeout','$filter','egCore',
1710 function($q , $timeout , $filter , egCore) {
1712 function GridDataProvider(args) {
1713 var gridData = this;
1714 if (!args) args = {};
1717 gridData.get = args.get;
1718 gridData.query = args.query;
1719 gridData.idlClass = args.idlClass;
1720 gridData.columnsProvider = args.columnsProvider;
1722 // Delivers a stream of array data via promise.notify()
1723 // Useful for passing an array of data to egGrid.get()
1724 // If a count is provided, the array will be trimmed to
1725 // the range defined by count and offset
1726 gridData.arrayNotifier = function(arr, offset, count) {
1727 if (!arr || arr.length == 0) return $q.when();
1729 if (gridData.columnsProvider.clientSort
1731 && gridData.sort.length > 0
1733 var sorter_cache = [];
1734 arr.sort(function(a,b) {
1735 for (var si = 0; si < gridData.sort.length; si++) {
1736 if (!sorter_cache[si]) { // Build sort structure on first comparison, reuse thereafter
1737 var field = gridData.sort[si];
1740 if (angular.isObject(field)) {
1741 dir = Object.values(field)[0];
1742 field = Object.keys(field)[0];
1745 var path = gridData.columnsProvider.findColumn(field).path || field;
1746 var comparator = gridData.columnsProvider.findColumn(field).comparator ||
1747 function (x,y) { if (x < y) return -1; if (x > y) return 1; return 0 };
1749 sorter_cache[si] = {
1752 comparator : comparator
1756 var sc = sorter_cache[si];
1760 if (a._isfieldmapper || angular.isFunction(a[sc.field])) {
1761 try {af = a[sc.field](); bf = b[sc.field]() } catch (e) {};
1763 af = a[sc.field]; bf = b[sc.field];
1765 if (af === undefined && sc.field.indexOf('.') > -1) { // assume an object, not flat path
1766 var parts = sc.field.split('.');
1769 angular.forEach(parts, function (p) {
1771 if (af._isfieldmapper || angular.isFunction(af[p])) af = af[p]();
1775 if (bf._isfieldmapper || angular.isFunction(bf[p])) bf = bf[p]();
1781 if (af === undefined) af = null;
1782 if (bf === undefined) bf = null;
1784 if (af === null && bf !== null) return 1;
1785 if (bf === null && af !== null) return -1;
1787 if (!(bf === null && af === null)) {
1788 var partial = sc.comparator(af,bf);
1790 if (sc.dir == 'desc') {
1791 if (partial > 0) return -1;
1803 if (count) arr = arr.slice(offset, offset + count);
1804 var def = $q.defer();
1805 // promise notifications are only witnessed when delivered
1806 // after the caller has his hands on the promise object
1807 $timeout(function() {
1808 angular.forEach(arr, def.notify);
1814 // Calls the grid refresh function. Once instantiated, the
1815 // grid will replace this function with it's own refresh()
1816 gridData.refresh = function(noReset) { }
1818 if (!gridData.get) {
1819 // returns a promise whose notify() delivers items
1820 gridData.get = function(index, count) {
1821 console.error("egGridDataProvider.get() not implemented");
1825 // attempts a flat field lookup first. If the column is not
1826 // found on the top-level object, attempts a nested lookup
1827 // TODO: consider a caching layer to speed up template
1828 // rendering, particularly for nested objects?
1829 gridData.itemFieldValue = function(item, column) {
1831 if (column.name in item) {
1832 if (typeof item[column.name] == 'function') {
1833 val = item[column.name]();
1835 val = item[column.name];
1838 val = gridData.nestedItemFieldValue(item, column);
1844 // TODO: deprecate me
1845 gridData.flatItemFieldValue = function(item, column) {
1846 console.warn('gridData.flatItemFieldValue deprecated; '
1847 + 'leave provider.itemFieldValue unset');
1848 return item[column.name];
1851 // given an object and a dot-separated path to a field,
1852 // extract the value of the field. The path can refer
1853 // to function names or object attributes. If the final
1854 // value is an IDL field, run the value through its
1855 // corresponding output filter.
1856 gridData.nestedItemFieldValue = function(obj, column) {
1857 item = obj; // keep a copy around
1859 if (obj === null || obj === undefined || obj === '') return '';
1860 if (!column.path) return obj;
1863 var parts = column.path.split('.');
1865 angular.forEach(parts, function(step, idx) {
1866 // object is not fleshed to the expected extent
1867 if (typeof obj != 'object') {
1868 if (typeof obj != 'undefined' && column.flesher) {
1869 obj = column.flesher(obj, column, item);
1876 if (!obj) return '';
1878 var cls = obj.classname;
1879 if (cls && (class_obj = egCore.idl.classes[cls])) {
1880 idl_field = class_obj.field_map[step];
1881 obj = obj[step] ? obj[step]() : '';
1883 if (angular.isFunction(obj[step])) {
1891 // We found a nested IDL object which may or may not have
1892 // been configured as a top-level column. Grab the datatype.
1893 if (idl_field && !column.datatype)
1894 column.datatype = idl_field.datatype;
1896 if (obj === null || obj === undefined || obj === '') return '';
1902 instance : function(args) {
1903 return new GridDataProvider(args);
1910 // Factory service for egGridDataManager instances, which are
1911 // responsible for collecting flattened grid data.
1912 .factory('egGridFlatDataProvider',
1913 ['$q','egCore','egGridDataProvider',
1914 function($q , egCore , egGridDataProvider) {
1917 instance : function(args) {
1918 var provider = egGridDataProvider.instance(args);
1920 provider.get = function(offset, count) {
1922 // no query means no call
1923 if (!provider.query ||
1924 angular.equals(provider.query, {}))
1927 // find all of the currently visible columns
1928 var queryFields = {}
1929 angular.forEach(provider.columnsProvider.columns,
1931 // only query IDL-tracked columns
1932 if (!col.adhoc && col.name && col.path && (col.required || col.visible))
1933 queryFields[col.name] = col.path;
1937 return egCore.net.request(
1939 'open-ils.fielder.flattened_search',
1940 egCore.auth.token(), provider.idlClass,
1941 queryFields, provider.query,
1942 { sort : provider.sort,
1948 //provider.itemFieldValue = provider.flatItemFieldValue;
1955 .directive('egGridColumnDragSource', function() {
1958 require : '^egGrid',
1959 link : function(scope, element, attrs, egGridCtrl) {
1960 angular.element(element).attr('draggable', 'true');
1962 element.bind('dragstart', function(e) {
1963 egGridCtrl.dragColumn = attrs.column;
1964 egGridCtrl.dragType = attrs.dragType || 'move'; // or resize
1965 egGridCtrl.colResizeDir = 0;
1967 if (egGridCtrl.dragType == 'move') {
1968 // style the column getting moved
1969 angular.element(e.target).addClass(
1970 'eg-grid-column-move-handle-active');
1974 element.bind('dragend', function(e) {
1975 if (egGridCtrl.dragType == 'move') {
1976 angular.element(e.target).removeClass(
1977 'eg-grid-column-move-handle-active');
1984 .directive('egGridColumnDragDest', function() {
1987 require : '^egGrid',
1988 link : function(scope, element, attrs, egGridCtrl) {
1990 element.bind('dragover', function(e) { // required for drop
1991 e.stopPropagation();
1993 e.dataTransfer.dropEffect = 'move';
1995 if (egGridCtrl.colResizeDir == 0) return; // move
1997 var cols = egGridCtrl.columnsProvider;
1998 var srcCol = egGridCtrl.dragColumn;
1999 var srcColIdx = cols.indexOf(srcCol);
2001 if (egGridCtrl.colResizeDir == -1) {
2002 if (cols.indexOf(attrs.column) <= srcColIdx) {
2003 egGridCtrl.modifyColumnFlex(
2004 egGridCtrl.columnsProvider.findColumn(
2005 egGridCtrl.dragColumn), -1);
2006 if (cols.columns[srcColIdx+1]) {
2007 // source column shrinks by one, column to the
2008 // right grows by one.
2009 egGridCtrl.modifyColumnFlex(
2010 cols.columns[srcColIdx+1], 1);
2015 if (cols.indexOf(attrs.column) > srcColIdx) {
2016 egGridCtrl.modifyColumnFlex(
2017 egGridCtrl.columnsProvider.findColumn(
2018 egGridCtrl.dragColumn), 1);
2019 if (cols.columns[srcColIdx+1]) {
2020 // source column grows by one, column to the
2021 // right grows by one.
2022 egGridCtrl.modifyColumnFlex(
2023 cols.columns[srcColIdx+1], -1);
2031 element.bind('dragenter', function(e) {
2032 e.stopPropagation();
2034 if (egGridCtrl.dragType == 'move') {
2035 angular.element(e.target).addClass('eg-grid-col-hover');
2037 // resize grips are on the right side of each column.
2038 // dragenter will either occur on the source column
2039 // (dragging left) or the column to the right.
2040 if (egGridCtrl.colResizeDir == 0) {
2041 if (egGridCtrl.dragColumn == attrs.column) {
2042 egGridCtrl.colResizeDir = -1; // west
2044 egGridCtrl.colResizeDir = 1; // east
2050 element.bind('dragleave', function(e) {
2051 e.stopPropagation();
2053 if (egGridCtrl.dragType == 'move') {
2054 angular.element(e.target).removeClass('eg-grid-col-hover');
2058 element.bind('drop', function(e) {
2059 e.stopPropagation();
2061 egGridCtrl.colResizeDir = 0;
2062 if (egGridCtrl.dragType == 'move') {
2063 angular.element(e.target).removeClass('eg-grid-col-hover');
2064 egGridCtrl.onColumnDrop(attrs.column); // move the column
2071 .directive('egGridMenuItem', function() {
2074 require : '^egGrid',
2080 handler : '=', // onclick handler function
2081 divider : '=', // if true, show a divider only
2082 handlerData : '=', // if set, passed as second argument to handler
2083 disabled : '=', // function
2084 hidden : '=' // function
2086 link : function(scope, element, attrs, egGridCtrl) {
2087 egGridCtrl.addMenuItem({
2088 checkbox : scope.checkbox,
2089 checked : scope.checked ? true : false,
2090 label : scope.label,
2091 standalone : scope.standalone ? true : false,
2092 handler : scope.handler,
2093 divider : scope.divider,
2094 disabled : scope.disabled,
2095 hidden : scope.hidden,
2096 handlerData : scope.handlerData
2103 /* https://stackoverflow.com/questions/17343696/adding-an-ng-click-event-inside-a-filter/17344875#17344875 */
2104 .directive('compile', ['$compile', function ($compile) {
2105 return function(scope, element, attrs) {
2106 // pass through column defs from grid cell's scope
2107 scope.col = scope.$parent.col;
2110 // watch the 'compile' expression for changes
2111 return scope.$eval(attrs.compile);
2114 // when the 'compile' expression changes
2115 // assign it into the current DOM
2116 element.html(value);
2118 // compile the new DOM and link it to the current
2120 // NOTE: we only compile .childNodes so that
2121 // we don't get into infinite loop compiling ourselves
2122 $compile(element.contents())(scope);
2131 * Translates bare IDL object values into display values.
2132 * 1. Passes dates through the angular date filter
2133 * 2. Translates bools to Booleans so the browser can display translated
2134 * value. (Though we could manually translate instead..)
2135 * Others likely to follow...
2137 .filter('egGridValueFilter', ['$filter','egCore', function($filter,egCore) {
2138 function traversePath(obj,path) {
2139 var list = path.split('.');
2140 for (var part in path) {
2141 if (obj[path]) obj = obj[path]
2147 var GVF = function(value, column, item) {
2148 switch(column.datatype) {
2151 // Browser will translate true/false for us
2153 case '1' : // legacy
2157 case '0' : // legacy
2160 // value may be null, '', etc.
2161 default : return '';
2164 var interval = angular.isFunction(item[column.dateonlyinterval])
2165 ? item[column.dateonlyinterval]()
2166 : item[column.dateonlyinterval];
2168 if (column.dateonlyinterval && !interval) // try it as a dotted path
2169 interval = traversePath(item, column.dateonlyinterval);
2171 var context = angular.isFunction(item[column.datecontext])
2172 ? item[column.datecontext]()
2173 : item[column.datecontext];
2175 if (column.datecontext && !context) // try it as a dotted path
2176 context = traversePath(item, column.datecontext);
2178 var date_filter = column.datefilter || 'egOrgDateInContext';
2180 return $filter(date_filter)(value, column.dateformat, context, interval);
2182 return $filter('currency')(value);
2188 GVF.$stateful = true;