1 angular.module('egGridMod',
2 ['egCoreMod', 'egUiMod', 'ui.bootstrap'])
4 .directive('egGrid', function() {
10 // IDL class hint (e.g. "aou")
16 // if true, grid columns are derived from all non-virtual
17 // fields on the base idlClass
20 // grid preferences will be stored / retrieved with this key
23 // field whose value is unique and may be used for item
24 // reference / lookup. This will usually be someting like
25 // "id". This is not needed when using autoFields, since we
26 // can determine the primary key directly from the IDL.
29 // Reference to externally provided egGridDataProvider
32 // Reference to externally provided item-selection handler
35 // Reference to externally provided after-item-selection handler
38 // comma-separated list of supported or disabled grid features
39 // supported features:
40 // startSelected : init the grid with all rows selected by default
41 // allowAll : add an "All" option to row count (really 10000)
42 // -menu : don't show any menu buttons (or use space for them)
43 // -picker : don't show the column picker
44 // -pagination : don't show any pagination elements, and set
46 // -actions : don't show the actions dropdown
47 // -index : don't show the row index column (can't use "index"
48 // as the idField in this case)
49 // -display : columns are hidden by default
50 // -sort : columns are unsortable by default
51 // -multisort : sort priorities config disabled by default
52 // -multiselect : only one row at a time can be selected;
53 // choosing this also disables the checkbox
57 // optional primary grid label
60 // if true, use the IDL class label as the mainLabel
63 // optional context menu label
66 dateformat : '@', // optional: passed down to egGridValueFilter
67 datecontext: '@', // optional: passed down to egGridValueFilter to choose TZ
68 datefilter: '@', // optional: passed down to egGridValueFilter to choose specialized date filters
69 dateonlyinterval: '@', // optional: passed down to egGridValueFilter to choose a "better" format
71 // Hash of control functions.
73 // These functions are defined by the calling scope and
74 // invoked as-is by the grid w/ the specified parameters.
76 // collectStarted : function() {}
77 // itemRetrieved : function(item) {}
78 // allItemsRetrieved : function() {}
81 // If defined, the grid will watch the return value from
82 // the function defined at watchQuery on each digest and
83 // re-draw the grid when query changes occur.
85 // watchQuery : function() { /* return grid query */ }
88 // These functions are defined by the grid and thus
89 // replace any values defined for these attributes from the
92 // activateItem : function(item) {}
93 // allItems : function(allItems) {}
94 // selectedItems : function(selected) {}
95 // selectItems : function(ids) {}
96 // setQuery : function(queryStruct) {} // causes reload
97 // setSort : function(sortSturct) {} // causes reload
101 // TODO: avoid hard-coded url
102 templateUrl : '/eg/staff/share/t_autogrid',
104 link : function(scope, element, attrs) {
105 // link() is called after page compilation, which means our
106 // eg-grid-field's have been parsed and loaded. Now it's
107 // safe to perform our initial page load.
109 // load auto fields after eg-grid-field's so they are not clobbered
110 scope.handleAutoFields();
113 scope.grid_element = element;
115 .find('.eg-grid-content-body')
116 .bind('contextmenu', scope.showActionContextMenu);
120 '$scope','$q','egCore','egGridFlatDataProvider','$location',
121 'egGridColumnsProvider','$filter','$window','$sce','$timeout',
122 'egProgressDialog','$uibModal',
123 function($scope, $q , egCore, egGridFlatDataProvider , $location,
124 egGridColumnsProvider , $filter , $window , $sce , $timeout,
125 egProgressDialog , $uibModal) {
129 grid.init = function() {
132 $scope.showGridConf = false;
133 grid.totalCount = -1;
134 $scope.selected = {};
135 $scope.actionGroups = [{actions:[]}]; // Grouped actions for selected items
136 $scope.menuItems = []; // global actions
138 // returns true if any rows are selected.
139 $scope.hasSelected = function() {
140 return grid.getSelectedItems().length > 0 };
142 var features = ($scope.features) ?
143 $scope.features.split(',') : [];
144 delete $scope.features;
146 $scope.showIndex = (features.indexOf('-index') == -1);
148 $scope.allowAll = (features.indexOf('allowAll') > -1);
149 $scope.startSelected = $scope.selectAll = (features.indexOf('startSelected') > -1);
150 $scope.showActions = (features.indexOf('-actions') == -1);
151 $scope.showPagination = (features.indexOf('-pagination') == -1);
152 $scope.showPicker = (features.indexOf('-picker') == -1);
154 $scope.showMenu = (features.indexOf('-menu') == -1);
156 // remove some unneeded values from the scope to reduce bloat
158 grid.idlClass = $scope.idlClass;
159 delete $scope.idlClass;
161 grid.persistKey = $scope.persistKey;
162 delete $scope.persistKey;
164 var stored_limit = 0;
165 if ($scope.showPagination) {
166 if (grid.persistKey) {
167 var stored_limit = Number(
168 egCore.hatch.getLocalItem('eg.grid.' + grid.persistKey + '.limit')
172 stored_limit = 10000; // maybe support "Inf"?
175 grid.limit = Number(stored_limit) || Number($scope.pageSize) || 25;
177 grid.indexField = $scope.idField;
178 delete $scope.idField;
180 grid.dataProvider = $scope.itemsProvider;
181 // make grid ref available in get() to set totalCount, if known.
182 // this allows us disable the 'next' paging button correctly
183 grid.dataProvider.grid = grid;
185 if (!grid.indexField && grid.idlClass)
186 grid.indexField = egCore.idl.classes[grid.idlClass].pkey;
188 grid.columnsProvider = egGridColumnsProvider.instance({
189 idlClass : grid.idlClass,
190 clientSort : (features.indexOf('clientsort') > -1 && features.indexOf('-clientsort') == -1),
191 defaultToHidden : (features.indexOf('-display') > -1),
192 defaultToNoSort : (features.indexOf('-sort') > -1),
193 defaultToNoMultiSort : (features.indexOf('-multisort') > -1),
194 defaultDateFormat : $scope.dateformat,
195 defaultDateContext : $scope.datecontext,
196 defaultDateFilter : $scope.datefilter,
197 defaultDateOnlyInterval : $scope.dateonlyinterval
199 $scope.canMultiSelect = (features.indexOf('-multiselect') == -1);
201 $scope.handleAutoFields = function() {
202 if ($scope.autoFields) {
203 if (grid.autoLabel) {
205 egCore.idl.classes[grid.idlClass].label;
207 grid.columnsProvider.compileAutoColumns();
208 delete $scope.autoFields;
212 if (!grid.dataProvider) {
213 // no provider, um, provided.
214 // Use a flat data provider
216 grid.selfManagedData = true;
217 grid.dataProvider = egGridFlatDataProvider.instance({
218 indexField : grid.indexField,
219 idlClass : grid.idlClass,
220 columnsProvider : grid.columnsProvider,
225 grid.dataProvider.columnsProvider = grid.columnsProvider;
227 $scope.itemFieldValue = grid.dataProvider.itemFieldValue;
228 $scope.indexValue = function(item) {
229 return grid.indexValue(item)
232 grid.applyControlFunctions();
234 grid.loadConfig().then(function() {
235 // link columns to scope after loadConfig(), since it
236 // replaces the columns array.
237 $scope.columns = grid.columnsProvider.columns;
240 // NOTE: grid.collect() is first called from link(), not here.
243 // link our control functions into the gridControls
244 // scope object so the caller can access them.
245 grid.applyControlFunctions = function() {
247 // we use some of these controls internally, so sett
248 // them up even if the caller doesn't request them.
249 var controls = $scope.gridControls || {};
251 controls.columnMap = function() {
253 angular.forEach(grid.columnsProvider.columns, function (c) {
259 controls.columnsProvider = function() {
260 return grid.columnsProvider;
263 // link in the control functions
264 controls.selectedItems = function() {
265 return grid.getSelectedItems()
268 controls.allItems = function() {
272 controls.selectItems = function(ids) {
274 $scope.selected = {};
275 angular.forEach(ids, function(i) {
276 $scope.selected[''+i] = true;
280 // if the caller provided a functional setQuery,
281 // extract the value before replacing it
282 if (controls.setQuery) {
283 grid.dataProvider.query =
287 controls.setQuery = function(query) {
288 grid.dataProvider.query = query;
292 if (controls.watchQuery) {
293 // capture the initial query value
294 grid.dataProvider.query = controls.watchQuery();
297 $scope.gridWatchQuery = controls.watchQuery;
298 $scope.$watch('gridWatchQuery()', function(newv) {
299 controls.setQuery(newv);
303 // if the caller provided a functional setSort
304 // extract the value before replacing it
305 grid.dataProvider.sort =
306 controls.setSort ? controls.setSort() : [];
308 controls.setSort = function(sort) {
312 controls.refresh = function(noReset) {
313 if (!noReset) grid.offset = 0;
317 controls.setLimit = function(limit,forget) {
318 if (!forget && grid.persistKey)
319 egCore.hatch.setLocalItem('eg.grid.' + grid.persistKey + '.limit', limit);
322 controls.getLimit = function() {
325 controls.setOffset = function(offset) {
326 grid.offset = offset;
328 controls.getOffset = function() {
332 controls.saveConfig = function () {
333 return $scope.saveConfig();
336 grid.dataProvider.refresh = controls.refresh;
337 grid.controls = controls;
340 // If a menu item provides its own HTML template, translate it,
341 // using the menu item for the template scope.
342 // note: $sce is required to avoid security restrictions and
343 // is OK here, since the template comes directly from a
344 // local HTML template (not user input).
345 $scope.translateMenuItemTemplate = function(item) {
346 var html = egCore.strings.$replace(item.template, {item : item});
347 return $sce.trustAsHtml(html);
350 // add a new (global) grid menu item
351 grid.addMenuItem = function(item) {
352 $scope.menuItems.push(item);
353 var handler = item.handler;
354 item.handler = function() {
355 $scope.gridMenuIsOpen = false; // close menu
358 item.handlerData, grid.getSelectedItems());
363 // add a selected-items action
364 grid.addAction = function(act) {
366 $scope.actionGroups.forEach(function(g){
367 if (g.label === act.group) {
373 $scope.actionGroups.push({
380 // remove the stored column configuration preferenc, then recover
381 // the column visibility information from the initial page load.
382 $scope.resetColumns = function() {
383 $scope.gridColumnPickerIsOpen = false;
384 egCore.hatch.removeItem('eg.grid.' + grid.persistKey)
386 grid.columnsProvider.reset();
387 if (grid.selfManagedData) grid.collect();
391 $scope.showAllColumns = function() {
392 $scope.gridColumnPickerIsOpen = false;
393 grid.columnsProvider.showAllColumns();
394 if (grid.selfManagedData) grid.collect();
397 $scope.hideAllColumns = function() {
398 $scope.gridColumnPickerIsOpen = false;
399 grid.columnsProvider.hideAllColumns();
400 // note: no need to fetch new data if no columns are visible
403 $scope.toggleColumnVisibility = function(col) {
404 $scope.gridColumnPickerIsOpen = false;
405 col.visible = !col.visible;
407 // egGridFlatDataProvider only retrieves data to be
408 // displayed. When column visibility changes, it's
409 // necessary to fetch the newly visible column data.
410 if (grid.selfManagedData) grid.collect();
413 // save the columns configuration (position, sort, width) to
414 // eg.grid.<persist-key>
415 $scope.saveConfig = function() {
416 $scope.gridColumnPickerIsOpen = false;
418 if (!grid.persistKey) {
420 "Cannot save settings without a grid persist-key");
424 // only store information about visible columns.
425 var conf = grid.columnsProvider.columns.filter(
426 function(col) {return Boolean(col.visible) });
428 // now scrunch the data down to just the needed info
429 conf = conf.map(function(col) {
430 var c = {name : col.name}
431 // Apart from the name, only store non-default values.
432 // No need to store col.visible, since that's implicit
433 if (col.align != 'left') c.align = col.align;
434 if (col.flex != 2) c.flex = col.flex;
435 if (Number(col.sort)) c.sort = Number(c.sort);
439 egCore.hatch.setItem('eg.grid.' + grid.persistKey, conf)
441 // Save operation performed from the grid configuration UI.
442 // Hide the configuration UI and re-draw w/ sort applied
443 if ($scope.showGridConf)
444 $scope.toggleConfDisplay();
449 // load the columns configuration (position, sort, width) from
450 // eg.grid.<persist-key> and apply the loaded settings to the
451 // columns on our columnsProvider
452 grid.loadConfig = function() {
453 if (!grid.persistKey) return $q.when();
455 return egCore.hatch.getItem('eg.grid.' + grid.persistKey)
456 .then(function(conf) {
459 var columns = grid.columnsProvider.columns;
462 angular.forEach(conf, function(col) {
463 var grid_col = columns.filter(
464 function(c) {return c.name == col.name})[0];
467 // saved column does not match a column in the
468 // current grid. skip it.
472 grid_col.align = col.align || 'left';
473 grid_col.flex = col.flex || 2;
474 grid_col.sort = col.sort || 0;
475 // all saved columns are assumed to be true
476 grid_col.visible = true;
478 .filter(function (c) {
479 return c.name == grid_col.name;
482 new_cols.push(grid_col);
485 // columns which are not expressed within the saved
486 // configuration are marked as non-visible and
487 // appended to the end of the new list of columns.
488 angular.forEach(columns, function(col) {
489 var found = conf.filter(
490 function(c) {return (c.name == col.name)})[0];
497 grid.columnsProvider.columns = new_cols;
503 $scope.onContextMenu = function($event) {
504 var col = angular.element($event.target).attr('column');
505 console.log('selected column ' + col);
508 $scope.page = function() {
509 return (grid.offset / grid.limit) + 1;
512 $scope.goToPage = function(page) {
514 if (angular.isNumber(page) && page > 0) {
515 grid.offset = (page - 1) * grid.limit;
520 $scope.offset = function(o) {
521 if (angular.isNumber(o))
526 $scope.limit = function(l) {
527 if (angular.isNumber(l)) {
529 egCore.hatch.setLocalItem('eg.grid.' + grid.persistKey + '.limit', l);
535 $scope.onFirstPage = function() {
536 return grid.offset == 0;
539 $scope.hasNextPage = function() {
540 // we have less data than requested, there must
541 // not be any more pages
542 if (grid.count() < grid.limit) return false;
544 // if the total count is not known, assume that a full
545 // page of data implies more pages are available.
546 if (grid.totalCount == -1) return true;
548 // we have a full page of data, but is there more?
549 return grid.totalCount > (grid.offset + grid.count());
552 $scope.incrementPage = function() {
553 grid.offset += grid.limit;
557 $scope.decrementPage = function() {
558 if (grid.offset < grid.limit) {
561 grid.offset -= grid.limit;
566 // number of items loaded for the current page of results
567 grid.count = function() {
568 return $scope.items.length;
571 // returns the unique identifier value for the provided item
572 // for internal consistency, indexValue is always coerced
574 grid.indexValue = function(item) {
575 if (angular.isObject(item)) {
577 if (angular.isFunction(item[grid.indexField]))
578 return ''+item[grid.indexField]();
579 return ''+item[grid.indexField]; // flat data
582 // passed a non-object; assume it's an index
586 // fires the hide handler function for a context action
587 $scope.actionHide = function(action) {
588 if (typeof action.hide == 'undefined') {
591 if (angular.isFunction(action.hide))
592 return action.hide(action);
596 // fires the disable handler function for a context action
597 $scope.actionDisable = function(action) {
598 if (typeof action.disabled == 'undefined') {
601 if (angular.isFunction(action.disabled))
602 return action.disabled(action);
603 return action.disabled;
606 // fires the action handler function for a context action
607 $scope.actionLauncher = function(action) {
608 if (!action.handler) {
610 'No handler specified for "' + action.label + '"');
614 action.handler(grid.getSelectedItems());
616 console.error('Error executing handler for "'
617 + action.label + '" => ' + E + "\n" + E.stack);
620 if ($scope.action_context_showing) $scope.hideActionContextMenu();
625 $scope.hideActionContextMenu = function () {
626 $($scope.menu_dom).css({
628 width: $scope.action_context_width,
629 top: $scope.action_context_y,
630 left: $scope.action_context_x
632 $($scope.action_context_parent).append($scope.menu_dom);
633 $scope.action_context_oldy = $scope.action_context_oldx = 0;
634 $('body').unbind('click.remove_context_menu_'+$scope.action_context_index);
635 $scope.action_context_showing = false;
638 $scope.action_context_showing = false;
639 $scope.showActionContextMenu = function ($event) {
641 // Have to gather these here, instead of inside link()
642 if (!$scope.menu_dom) $scope.menu_dom = $($scope.grid_element).find('.grid-action-dropdown')[0];
643 if (!$scope.action_context_parent) $scope.action_context_parent = $($scope.menu_dom).parent();
645 if (!grid.getSelectedItems().length) // Nothing selected, fire the click event
646 $event.target.click();
648 if (!$scope.action_context_showing) {
649 $scope.action_context_width = $($scope.menu_dom).css('width');
650 $scope.action_context_y = $($scope.menu_dom).css('top');
651 $scope.action_context_x = $($scope.menu_dom).css('left');
652 $scope.action_context_showing = true;
653 $scope.action_context_index = Math.floor((Math.random() * 1000) + 1);
655 $('body').append($($scope.menu_dom));
656 $('body').bind('click.remove_context_menu_'+$scope.action_context_index, $scope.hideActionContextMenu);
659 $($scope.menu_dom).css({
661 width: $scope.action_context_width,
669 // returns the list of selected item objects
670 grid.getSelectedItems = function() {
671 return $scope.items.filter(
673 return Boolean($scope.selected[grid.indexValue(item)]);
678 grid.getItemByIndex = function(index) {
679 for (var i = 0; i < $scope.items.length; i++) {
680 var item = $scope.items[i];
681 if (grid.indexValue(item) == index)
686 // selects one row after deselecting all of the others
687 grid.selectOneItem = function(index) {
688 $scope.selected = {};
689 $scope.selected[index] = true;
692 // selects or deselects an item, without affecting the others.
693 // returns true if the item is selected; false if de-selected.
694 // we overwrite the object so that we can watch $scope.selected
695 grid.toggleSelectOneItem = function(index) {
696 if ($scope.selected[index]) {
697 delete $scope.selected[index];
698 $scope.selected = angular.copy($scope.selected);
701 $scope.selected[index] = true;
702 $scope.selected = angular.copy($scope.selected);
707 $scope.updateSelected = function () {
708 return $scope.selected = angular.copy($scope.selected);
711 grid.selectAllItems = function() {
712 angular.forEach($scope.items, function(item) {
713 $scope.selected[grid.indexValue(item)] = true
715 $scope.selected = angular.copy($scope.selected);
718 $scope.$watch('selectAll', function(newVal) {
720 grid.selectAllItems();
722 $scope.selected = {};
726 if ($scope.onSelect) {
727 $scope.$watch('selected', function(newVal) {
728 $scope.onSelect(grid.getSelectedItems());
729 if ($scope.afterSelect) $scope.afterSelect();
733 // returns true if item1 appears in the list before item2;
734 // false otherwise. this is slightly more efficient that
735 // finding the position of each then comparing them.
736 // item1 / item2 may be an item or an item index
737 grid.itemComesBefore = function(itemOrIndex1, itemOrIndex2) {
738 var idx1 = grid.indexValue(itemOrIndex1);
739 var idx2 = grid.indexValue(itemOrIndex2);
741 // use for() for early exit
742 for (var i = 0; i < $scope.items.length; i++) {
743 var idx = grid.indexValue($scope.items[i]);
744 if (idx == idx1) return true;
745 if (idx == idx2) return false;
750 // 0-based position of item in the current data set
751 grid.indexOf = function(item) {
752 var idx = grid.indexValue(item);
753 for (var i = 0; i < $scope.items.length; i++) {
754 if (grid.indexValue($scope.items[i]) == idx)
760 grid.modifyColumnFlex = function(column, val) {
762 // prevent flex:0; use hiding instead
766 $scope.modifyColumnFlex = function(col, val) {
767 $scope.lastModColumn = col.name;
768 grid.modifyColumnFlex(col, val);
771 grid.modifyColumnPos = function(col, diff) {
772 var srcIdx, targetIdx;
773 angular.forEach(grid.columnsProvider.columns,
774 function(c, i) { if (c.name == col.name) srcIdx = i });
776 targetIdx = srcIdx + diff;
779 } else if (targetIdx >= grid.columnsProvider.columns.length) {
780 // Target index follows the last visible column.
782 angular.forEach(grid.columnsProvider.columns,
783 function(column, idx) {
784 if (column.visible) lastVisible = idx;
788 // When moving a column (down) causes one or more
789 // visible columns to shuffle forward, our column
790 // moves into the slot of the last visible column.
791 // Otherwise, put it into the slot directly following
792 // the last visible column.
794 srcIdx <= lastVisible ? lastVisible : lastVisible + 1;
797 // Splice column out of old position, insert at new position.
798 grid.columnsProvider.columns.splice(srcIdx, 1);
799 grid.columnsProvider.columns.splice(targetIdx, 0, col);
802 $scope.modifyColumnPos = function(col, diff) {
803 $scope.lastModColumn = col.name;
804 return grid.modifyColumnPos(col, diff);
808 // handles click, control-click, and shift-click
809 $scope.handleRowClick = function($event, item) {
810 var index = grid.indexValue(item);
812 var origSelected = Object.keys($scope.selected);
814 if (!$scope.canMultiSelect) {
815 grid.selectOneItem(index);
816 grid.lastSelectedItemIndex = index;
820 if ($event.ctrlKey || $event.metaKey /* mac command */) {
822 if (grid.toggleSelectOneItem(index))
823 grid.lastSelectedItemIndex = index;
825 } else if ($event.shiftKey) {
828 if (!grid.lastSelectedItemIndex ||
829 index == grid.lastSelectedItemIndex) {
830 grid.selectOneItem(index);
831 grid.lastSelectedItemIndex = index;
835 var selecting = false;
836 var ascending = grid.itemComesBefore(
837 grid.lastSelectedItemIndex, item);
839 grid.indexOf(grid.lastSelectedItemIndex);
841 // update to new last-selected
842 grid.lastSelectedItemIndex = index;
844 // select each row between the last selected and
845 // currently selected items
847 startPos += ascending ? 1 : -1;
848 var curItem = $scope.items[startPos];
850 var curIdx = grid.indexValue(curItem);
851 $scope.selected[curIdx] = true;
852 if (curIdx == index) break; // all done
854 $scope.selected = angular.copy($scope.selected);
858 grid.selectOneItem(index);
859 grid.lastSelectedItemIndex = index;
863 // Builds a sort expression from column sort priorities.
864 // called on page load and any time the priorities are modified.
865 grid.compileSort = function() {
866 var sortList = grid.columnsProvider.columns.filter(
867 function(col) { return Number(col.sort) != 0 }
870 if (Math.abs(a.sort) < Math.abs(b.sort))
876 if (sortList.length) {
877 grid.dataProvider.sort = sortList.map(function(col) {
879 blob[col.name] = col.sort < 0 ? 'desc' : 'asc';
885 // builds a sort expression using a single column,
886 // toggling between ascending and descending sort.
887 $scope.quickSort = function(col_name) {
888 var sort = grid.dataProvider.sort;
889 if (sort && sort.length &&
890 sort[0] == col_name) {
892 blob[col_name] = 'desc';
893 grid.dataProvider.sort = [blob];
895 grid.dataProvider.sort = [col_name];
902 // show / hide the grid configuration row
903 $scope.toggleConfDisplay = function() {
904 if ($scope.showGridConf) {
905 $scope.showGridConf = false;
906 if (grid.columnsProvider.hasSortableColumn()) {
907 // only refresh the grid if the user has the
908 // ability to modify the sort priorities.
914 $scope.showGridConf = true;
917 delete $scope.lastModColumn;
918 $scope.gridColumnPickerIsOpen = false;
921 // called when a dragged column is dropped onto itself
922 // or any other column
923 grid.onColumnDrop = function(target) {
924 if (angular.isUndefined(target)) return;
925 if (target == grid.dragColumn) return;
926 var srcIdx, targetIdx, srcCol;
927 angular.forEach(grid.columnsProvider.columns,
929 if (col.name == grid.dragColumn) {
932 } else if (col.name == target) {
938 if (srcIdx < targetIdx) targetIdx--;
940 // move src column from old location to new location in
941 // the columns array, then force a page refresh
942 grid.columnsProvider.columns.splice(srcIdx, 1);
943 grid.columnsProvider.columns.splice(targetIdx, 0, srcCol);
947 // prepares a string for inclusion within a CSV document
948 // by escaping commas and quotes and removing newlines.
949 grid.csvDatum = function(str) {
952 str = str.replace(/\n/g, '');
953 if (str.match(/\,/) || str.match(/"/)) {
954 str = str.replace(/"/g, '""');
955 str = '"' + str + '"';
960 /** Export the full data set as CSV.
962 * 1. User clicks the 'download csv' link
963 * 2. All grid data is retrieved asychronously
964 * 3. Once all data is all present and CSV-ized, the download
965 * attributes are linked to the href.
966 * 4. The href .click() action is prgrammatically fired again,
967 * telling the browser to download the data, now that the
968 * data is available for download.
969 * 5 Once downloaded, the href attributes are reset.
971 grid.csvExportInProgress = false;
972 $scope.generateCSVExportURL = function($event) {
974 if (grid.csvExportInProgress) {
975 // This is secondary href click handler. Give the
976 // browser a moment to start the download, then reset
977 // the CSV download attributes / state.
980 $scope.csvExportURL = '';
981 $scope.csvExportFileName = '';
982 grid.csvExportInProgress = false;
988 grid.csvExportInProgress = true;
989 $scope.gridColumnPickerIsOpen = false;
991 // let the file name describe the grid
992 $scope.csvExportFileName =
993 ($scope.mainLabel || grid.persistKey || 'eg_grid_data')
994 .replace(/\s+/g, '_') + '_' + $scope.page();
996 // toss the CSV into a Blob and update the export URL
997 grid.generateCSV().then(function(csv) {
998 var blob = new Blob([csv], {type : 'text/plain'});
999 $scope.csvExportURL =
1000 ($window.URL || $window.webkitURL).createObjectURL(blob);
1002 // Fire the 2nd click event now that the browser has
1003 // information on how to download the CSV file.
1004 $timeout(function() {$event.target.click()});
1009 * TODO: does this serve any purpose given we can
1010 * print formatted HTML? If so, generateCSV() now
1011 * returns a promise, needs light refactoring...
1012 $scope.printCSV = function() {
1013 $scope.gridColumnPickerIsOpen = false;
1014 egCore.print.print({
1015 context : 'default',
1016 content : grid.generateCSV(),
1017 content_type : 'text/plain'
1022 // Given a row item and column definition, extract the
1023 // text content for printing. Templated columns must be
1024 // processed and parsed as HTML, then boiled down to their
1026 grid.getItemTextContent = function(item, col) {
1029 val = $scope.translateCellTemplate(col, item);
1031 var node = new DOMParser()
1032 .parseFromString(val, 'text/html');
1033 val = $(node).text();
1036 val = grid.dataProvider.itemFieldValue(item, col);
1037 val = $filter('egGridValueFilter')(val, col, item);
1043 * Fetches all grid data and transates each item into a simple
1044 * key-value pair of column name => text-value.
1045 * Included in the response for convenience is the list of
1046 * currently visible column definitions.
1047 * TODO: currently fetches a maximum of 10k rows. Does this
1048 * need to be configurable?
1050 grid.getAllItemsAsText = function() {
1051 var text_items = [];
1053 // we don't know the total number of rows we're about
1054 // to retrieve, but we can indicate the number retrieved
1055 // so far as each item arrives.
1056 egProgressDialog.open({value : 0});
1058 var visible_cols = grid.columnsProvider.columns.filter(
1059 function(c) { return c.visible });
1061 return grid.dataProvider.get(0, 10000).then(
1063 return {items : text_items, columns : visible_cols};
1067 egProgressDialog.increment();
1069 angular.forEach(visible_cols, function(col) {
1070 text_item[col.name] =
1071 grid.getItemTextContent(item, col);
1073 text_items.push(text_item);
1075 ).finally(egProgressDialog.close);
1078 // Fetch "all" of the grid data, translate it into print-friendly
1079 // text, and send it to the printer service.
1080 $scope.printHTML = function() {
1081 $scope.gridColumnPickerIsOpen = false;
1082 return grid.getAllItemsAsText().then(function(text_items) {
1083 return egCore.print.print({
1084 template : 'grid_html',
1090 $scope.showColumnDialog = function() {
1091 return $uibModal.open({
1092 templateUrl: './share/t_grid_columns',
1095 controller: ['$scope', '$uibModalInstance',
1096 function($dialogScope, $uibModalInstance) {
1097 $dialogScope.modifyColumnPos = $scope.modifyColumnPos;
1098 $dialogScope.disableMultiSort = $scope.disableMultiSort;
1099 $dialogScope.columns = $scope.columns;
1101 // Push visible columns to the top of the list
1102 $dialogScope.elevateVisible = function() {
1104 angular.forEach($dialogScope.columns, function(col) {
1105 if (col.visible) new_cols.push(col);
1107 angular.forEach($dialogScope.columns, function(col) {
1108 if (!col.visible) new_cols.push(col);
1111 // Update all references to the list of columns
1112 $dialogScope.columns =
1114 grid.columnsProvider.columns =
1118 $dialogScope.toggle = function(col) {
1119 col.visible = !Boolean(col.visible);
1121 $dialogScope.ok = $dialogScope.cancel = function() {
1122 delete $scope.lastModColumn;
1123 $uibModalInstance.close()
1130 // generates CSV for the currently visible grid contents
1131 grid.generateCSV = function() {
1132 return grid.getAllItemsAsText().then(function(text_items) {
1133 var columns = text_items.columns;
1134 var items = text_items.items;
1138 angular.forEach(columns, function(col) {
1139 csvStr += grid.csvDatum(col.label);
1143 csvStr = csvStr.replace(/,$/,'\n');
1146 angular.forEach(items, function(item) {
1147 angular.forEach(columns, function(col) {
1148 csvStr += grid.csvDatum(item[col.name]);
1151 csvStr = csvStr.replace(/,$/,'\n');
1158 // Interpolate the value for column.linkpath within the context
1159 // of the row item to generate the final link URL.
1160 $scope.generateLinkPath = function(col, item) {
1161 return egCore.strings.$replace(col.linkpath, {item : item});
1164 // If a column provides its own HTML template, translate it,
1165 // using the current item for the template scope.
1166 // note: $sce is required to avoid security restrictions and
1167 // is OK here, since the template comes directly from a
1168 // local HTML template (not user input).
1169 $scope.translateCellTemplate = function(col, item) {
1170 var html = egCore.strings.$replace(col.template, {item : item});
1171 return $sce.trustAsHtml(html);
1174 $scope.collect = function() { grid.collect() }
1176 // asks the dataProvider for a page of data
1177 grid.collect = function() {
1179 // avoid firing the collect if there is nothing to collect.
1180 if (grid.selfManagedData && !grid.dataProvider.query) return;
1182 if (grid.collecting) return; // avoid parallel collect()
1183 grid.collecting = true;
1185 console.debug('egGrid.collect() offset='
1186 + grid.offset + '; limit=' + grid.limit);
1188 // ensure all of our dropdowns are closed
1189 // TODO: git rid of these and just use dropdown-toggle,
1190 // which is more reliable.
1191 $scope.gridColumnPickerIsOpen = false;
1192 $scope.gridRowCountIsOpen = false;
1193 $scope.gridPageSelectIsOpen = false;
1196 $scope.selected = {};
1198 // Inform the caller we've asked the data provider
1199 // for data. This is useful for knowing when collection
1200 // has started (e.g. to display a progress dialg) when
1201 // using the stock (flattener) data provider, where the
1202 // user is not directly defining a get() handler.
1203 if (grid.controls.collectStarted)
1204 grid.controls.collectStarted(grid.offset, grid.limit);
1206 grid.dataProvider.get(grid.offset, grid.limit).then(
1208 if (grid.controls.allItemsRetrieved)
1209 grid.controls.allItemsRetrieved();
1214 $scope.items.push(item)
1215 if (grid.controls.itemRetrieved)
1216 grid.controls.itemRetrieved(item);
1217 if ($scope.selectAll)
1218 $scope.selected[grid.indexValue(item)] = true
1220 }).finally(function() {
1221 console.debug('egGrid.collect() complete');
1222 grid.collecting = false
1223 $scope.selected = angular.copy($scope.selected);
1233 * eg-grid-field : used for collecting custom field data from the templates.
1234 * This directive does not direct display, it just passes data up to the
1237 .directive('egGridField', function() {
1239 require : '^egGrid',
1242 flesher: '=', // optional; function that can flesh a linked field, given the value
1243 comparator: '=', // optional; function that can sort the thing at the end of 'path'
1244 name : '@', // required; unique name
1245 path : '@', // optional; flesh path
1246 ignore: '@', // optional; fields to ignore when path is a wildcard
1247 label : '@', // optional; display label
1248 flex : '@', // optional; default flex width
1249 align : '@', // optional; default alignment, left/center/right
1250 dateformat : '@', // optional: passed down to egGridValueFilter
1251 datecontext: '@', // optional: passed down to egGridValueFilter to choose TZ
1252 datefilter: '@', // optional: passed down to egGridValueFilter to choose specialized date filters
1253 dateonlyinterval: '@', // optional: passed down to egGridValueFilter to choose a "better" format
1255 // if a field is part of an IDL object, but we are unable to
1256 // determine the class, because it's nested within a hash
1257 // (i.e. we can't navigate directly to the object via the IDL),
1258 // idlClass lets us specify the class. This is particularly
1259 // useful for nested wildcard fields.
1260 parentIdlClass : '@',
1262 // optional: for non-IDL columns, specifying a datatype
1263 // lets the caller control which display filter is used.
1264 // datatype should match the standard IDL datatypes.
1267 link : function(scope, element, attrs, egGridCtrl) {
1269 // boolean fields are presented as value-less attributes
1278 'required' // if set, always fetch data for this column
1281 if (angular.isDefined(attrs[field]))
1282 scope[field] = true;
1286 // any HTML content within the field is its custom template
1287 var tmpl = element.html();
1288 if (tmpl && !tmpl.match(/^\s*$/))
1289 scope.template = tmpl
1291 egGridCtrl.columnsProvider.add(scope);
1298 * eg-grid-action : used for specifying actions which may be applied
1299 * to items within the grid.
1301 .directive('egGridAction', function() {
1303 require : '^egGrid',
1307 group : '@', // Action group, ungrouped if not set
1308 label : '@', // Action label
1309 handler : '=', // Action function handler
1311 disabled : '=', // function
1314 link : function(scope, element, attrs, egGridCtrl) {
1315 egGridCtrl.addAction({
1317 group : scope.group,
1318 label : scope.label,
1319 divider : scope.divider,
1320 handler : scope.handler,
1321 disabled : scope.disabled,
1328 .factory('egGridColumnsProvider', ['egCore', function(egCore) {
1330 function ColumnsProvider(args) {
1333 cols.stockVisible = [];
1334 cols.idlClass = args.idlClass;
1335 cols.clientSort = args.clientSort;
1336 cols.defaultToHidden = args.defaultToHidden;
1337 cols.defaultToNoSort = args.defaultToNoSort;
1338 cols.defaultToNoMultiSort = args.defaultToNoMultiSort;
1339 cols.defaultDateFormat = args.defaultDateFormat;
1340 cols.defaultDateContext = args.defaultDateContext;
1342 // resets column width, visibility, and sort behavior
1343 // Visibility resets to the visibility settings defined in the
1344 // template (i.e. the original egGridField values).
1345 cols.reset = function() {
1346 angular.forEach(cols.columns, function(col) {
1350 if (cols.stockVisible.indexOf(col.name) > -1) {
1353 col.visible = false;
1358 // returns true if any columns are sortable
1359 cols.hasSortableColumn = function() {
1360 return cols.columns.filter(
1362 return col.sortable || col.multisortable;
1367 cols.showAllColumns = function() {
1368 angular.forEach(cols.columns, function(column) {
1369 column.visible = true;
1373 cols.hideAllColumns = function() {
1374 angular.forEach(cols.columns, function(col) {
1379 cols.indexOf = function(name) {
1380 for (var i = 0; i < cols.columns.length; i++) {
1381 if (cols.columns[i].name == name)
1387 cols.findColumn = function(name) {
1388 return cols.columns[cols.indexOf(name)];
1391 cols.compileAutoColumns = function() {
1392 var idl_class = egCore.idl.classes[cols.idlClass];
1397 if (field.virtual) return;
1398 if (field.datatype == 'link' || field.datatype == 'org_unit') {
1399 // if the field is a link and the linked class has a
1400 // "selector" field specified, use the selector field
1401 // as the display field for the columns.
1402 // flattener will take care of the fleshing.
1403 if (field['class']) {
1404 var selector_field = egCore.idl.classes[field['class']].fields
1405 .filter(function(f) { return Boolean(f.selector) })[0];
1406 if (selector_field) {
1407 field.path = field.name + '.' + selector_field.selector;
1411 cols.add(field, true);
1416 // if a column definition has a path with a wildcard, create
1417 // columns for all non-virtual fields at the specified
1418 // position in the path.
1419 cols.expandPath = function(colSpec) {
1421 var ignoreList = [];
1423 ignoreList = colSpec.ignore.split(' ');
1425 var dotpath = colSpec.path.replace(/\.?\*$/,'');
1429 if (colSpec.parentIdlClass) {
1430 class_obj = egCore.idl.classes[colSpec.parentIdlClass];
1432 class_obj = egCore.idl.classes[cols.idlClass];
1434 var idl_parent = class_obj;
1435 var old_field_label = '';
1437 if (!class_obj) return;
1439 console.debug('egGrid: auto dotpath is: ' + dotpath);
1440 var path_parts = dotpath.split(/\./);
1442 // find the IDL class definition for the last element in the
1443 // path before the .*
1444 // an empty path_parts means expand the root class
1447 for (var path_idx in path_parts) {
1448 old_field = idl_field;
1450 var part = path_parts[path_idx];
1451 idl_field = class_obj.field_map[part];
1453 // unless we're at the end of the list, this field should
1454 // link to another class.
1455 if (idl_field && idl_field['class'] && (
1456 idl_field.datatype == 'link' ||
1457 idl_field.datatype == 'org_unit')) {
1458 if (old_field_label) old_field_label += ' : ';
1459 old_field_label += idl_field.label;
1460 class_obj = egCore.idl.classes[idl_field['class']];
1461 if (old_field) idl_parent = old_field;
1463 if (path_idx < (path_parts.length - 1)) {
1464 // we ran out of classes to hop through before
1465 // we ran out of path components
1466 console.error("egGrid: invalid IDL path: " + dotpath);
1473 angular.forEach(class_obj.fields, function(field) {
1475 // Only show wildcard fields where we have data to show
1476 // Virtual and un-fleshed links will not have any data.
1477 if (field.virtual ||
1478 (field.datatype == 'link' || field.datatype == 'org_unit') ||
1479 ignoreList.indexOf(field.name) > -1
1483 var col = cols.cloneFromScope(colSpec);
1484 col.path = (dotpath ? dotpath + '.' + field.name : field.name);
1486 // log line below is very chatty. disable until needed.
1487 // console.debug('egGrid: field: ' +field.name + '; parent field: ' + js2JSON(idl_parent));
1488 cols.add(col, false, true,
1489 {idl_parent : idl_parent, idl_field : field, idl_class : class_obj, field_parent_label : old_field_label });
1492 cols.columns = cols.columns.sort(
1494 if (a.explicit) return -1;
1495 if (b.explicit) return 1;
1497 if (a.idlclass && b.idlclass) {
1498 if (a.idlclass < b.idlclass) return -1;
1499 if (b.idlclass < a.idlclass) return 1;
1502 if (a.path && b.path && a.path.lastIndexOf('.') && b.path.lastIndexOf('.')) {
1503 if (a.path.substring(0, a.path.lastIndexOf('.')) < b.path.substring(0, b.path.lastIndexOf('.'))) return -1;
1504 if (b.path.substring(0, b.path.lastIndexOf('.')) < a.path.substring(0, a.path.lastIndexOf('.'))) return 1;
1507 if (a.label && b.label) {
1508 if (a.label < b.label) return -1;
1509 if (b.label < a.label) return 1;
1512 return a.name < b.name ? -1 : 1;
1519 "egGrid: wildcard path does not resolve to an object: "
1524 // angular.clone(scopeObject) is not permittable. Manually copy
1525 // the fields over that we need (so the scope object can go away).
1526 cols.cloneFromScope = function(colSpec) {
1528 flesher : colSpec.flesher,
1529 comparator : colSpec.comparator,
1530 name : colSpec.name,
1531 label : colSpec.label,
1532 path : colSpec.path,
1533 align : colSpec.align || 'left',
1534 flex : Number(colSpec.flex) || 2,
1535 sort : Number(colSpec.sort) || 0,
1536 required : colSpec.required,
1537 linkpath : colSpec.linkpath,
1538 template : colSpec.template,
1539 visible : colSpec.visible,
1540 hidden : colSpec.hidden,
1541 datatype : colSpec.datatype,
1542 sortable : colSpec.sortable,
1543 nonsortable : colSpec.nonsortable,
1544 multisortable : colSpec.multisortable,
1545 nonmultisortable : colSpec.nonmultisortable,
1546 dateformat : colSpec.dateformat,
1547 datecontext : colSpec.datecontext,
1548 datefilter : colSpec.datefilter,
1549 dateonlyinterval : colSpec.dateonlyinterval,
1550 parentIdlClass : colSpec.parentIdlClass
1555 // Add a column to the columns collection.
1556 // Columns may come from a slim eg-columns-field or
1557 // directly from the IDL.
1558 cols.add = function(colSpec, fromIDL, fromExpand, idl_info) {
1560 // First added column with the specified path takes precedence.
1561 // This allows for specific definitions followed by wildcard
1562 // definitions. If a match is found, back out.
1563 if (cols.columns.filter(function(c) {
1564 return (c.path == colSpec.path) })[0]) {
1565 console.debug('skipping pre-existing column ' + colSpec.path);
1569 var column = fromExpand ? colSpec : cols.cloneFromScope(colSpec);
1571 if (column.path && column.path.match(/\*$/))
1572 return cols.expandPath(colSpec);
1574 if (!fromExpand) column.explicit = true;
1576 if (!column.name) column.name = column.path;
1577 if (!column.path) column.path = column.name;
1579 if (column.visible || (!cols.defaultToHidden && !column.hidden))
1580 column.visible = true;
1582 if (column.sortable || (!cols.defaultToNoSort && !column.nonsortable))
1583 column.sortable = true;
1585 if (column.multisortable ||
1586 (!cols.defaultToNoMultiSort && !column.nonmultisortable))
1587 column.multisortable = true;
1589 if (cols.defaultDateFormat && ! column.dateformat) {
1590 column.dateformat = cols.defaultDateFormat;
1593 if (cols.defaultDateOnlyInterval && ! column.dateonlyinterval) {
1594 column.dateonlyinterval = cols.defaultDateOnlyInterval;
1597 if (cols.defaultDateContext && ! column.datecontext) {
1598 column.datecontext = cols.defaultDateContext;
1601 if (cols.defaultDateFilter && ! column.datefilter) {
1602 column.datefilter = cols.defaultDateFilter;
1605 cols.columns.push(column);
1607 // Track which columns are visible by default in case we
1608 // need to reset column visibility
1610 cols.stockVisible.push(column.name);
1612 if (fromIDL) return; // directly from egIDL. nothing left to do.
1614 // lookup the matching IDL field
1615 if (!idl_info && cols.idlClass)
1616 idl_info = cols.idlFieldFromPath(column.path);
1619 // column is not represented within the IDL
1620 column.adhoc = true;
1624 column.datatype = idl_info.idl_field.datatype;
1626 if (!column.label) {
1627 column.label = idl_info.idl_field.label || column.name;
1630 if (fromExpand && idl_info.idl_class) {
1631 column.idlclass = '';
1632 if (idl_info.field_parent_label && idl_info.idl_parent.label != idl_info.idl_class.label) {
1633 column.idlclass = (idl_info.field_parent_label || idl_info.idl_parent.label || idl_info.idl_parent.name);
1635 column.idlclass += idl_info.idl_class.label || idl_info.idl_class.name;
1640 // finds the IDL field from the dotpath, using the columns
1641 // idlClass as the base.
1642 cols.idlFieldFromPath = function(dotpath) {
1643 var class_obj = egCore.idl.classes[cols.idlClass];
1644 var path_parts = dotpath.split(/\./);
1648 for (var path_idx in path_parts) {
1649 var part = path_parts[path_idx];
1650 idl_parent = idl_field;
1651 idl_field = class_obj.field_map[part];
1654 if (idl_field['class'] && (
1655 idl_field.datatype == 'link' ||
1656 idl_field.datatype == 'org_unit')) {
1657 class_obj = egCore.idl.classes[idl_field['class']];
1665 idl_parent: idl_parent,
1666 idl_field : idl_field,
1667 idl_class : class_obj
1673 instance : function(args) { return new ColumnsProvider(args) }
1679 * Generic data provider template class. This is basically an abstract
1680 * class factory service whose instances can be locally modified to
1681 * meet the needs of each individual grid.
1683 .factory('egGridDataProvider',
1684 ['$q','$timeout','$filter','egCore',
1685 function($q , $timeout , $filter , egCore) {
1687 function GridDataProvider(args) {
1688 var gridData = this;
1689 if (!args) args = {};
1692 gridData.get = args.get;
1693 gridData.query = args.query;
1694 gridData.idlClass = args.idlClass;
1695 gridData.columnsProvider = args.columnsProvider;
1697 // Delivers a stream of array data via promise.notify()
1698 // Useful for passing an array of data to egGrid.get()
1699 // If a count is provided, the array will be trimmed to
1700 // the range defined by count and offset
1701 gridData.arrayNotifier = function(arr, offset, count) {
1702 if (!arr || arr.length == 0) return $q.when();
1704 if (gridData.columnsProvider.clientSort
1706 && gridData.sort.length > 0
1708 var sorter_cache = [];
1709 arr.sort(function(a,b) {
1710 for (var si = 0; si < gridData.sort.length; si++) {
1711 if (!sorter_cache[si]) { // Build sort structure on first comparison, reuse thereafter
1712 var field = gridData.sort[si];
1715 if (angular.isObject(field)) {
1716 dir = Object.values(field)[0];
1717 field = Object.keys(field)[0];
1720 var path = gridData.columnsProvider.findColumn(field).path || field;
1721 var comparator = gridData.columnsProvider.findColumn(field).comparator ||
1722 function (x,y) { if (x < y) return -1; if (x > y) return 1; return 0 };
1724 sorter_cache[si] = {
1727 comparator : comparator
1731 var sc = sorter_cache[si];
1735 if (a._isfieldmapper || angular.isFunction(a[sc.field])) {
1736 try {af = a[sc.field](); bf = b[sc.field]() } catch (e) {};
1738 af = a[sc.field]; bf = b[sc.field];
1740 if (af === undefined && sc.field.indexOf('.') > -1) { // assume an object, not flat path
1741 var parts = sc.field.split('.');
1744 angular.forEach(parts, function (p) {
1746 if (af._isfieldmapper || angular.isFunction(af[p])) af = af[p]();
1750 if (bf._isfieldmapper || angular.isFunction(bf[p])) bf = bf[p]();
1756 if (af === undefined) af = null;
1757 if (bf === undefined) bf = null;
1759 if (af === null && bf !== null) return 1;
1760 if (bf === null && af !== null) return -1;
1762 if (!(bf === null && af === null)) {
1763 var partial = sc.comparator(af,bf);
1765 if (sc.dir == 'desc') {
1766 if (partial > 0) return -1;
1778 if (count) arr = arr.slice(offset, offset + count);
1779 var def = $q.defer();
1780 // promise notifications are only witnessed when delivered
1781 // after the caller has his hands on the promise object
1782 $timeout(function() {
1783 angular.forEach(arr, def.notify);
1789 // Calls the grid refresh function. Once instantiated, the
1790 // grid will replace this function with it's own refresh()
1791 gridData.refresh = function(noReset) { }
1793 if (!gridData.get) {
1794 // returns a promise whose notify() delivers items
1795 gridData.get = function(index, count) {
1796 console.error("egGridDataProvider.get() not implemented");
1800 // attempts a flat field lookup first. If the column is not
1801 // found on the top-level object, attempts a nested lookup
1802 // TODO: consider a caching layer to speed up template
1803 // rendering, particularly for nested objects?
1804 gridData.itemFieldValue = function(item, column) {
1806 if (column.name in item) {
1807 if (typeof item[column.name] == 'function') {
1808 val = item[column.name]();
1810 val = item[column.name];
1813 val = gridData.nestedItemFieldValue(item, column);
1819 // TODO: deprecate me
1820 gridData.flatItemFieldValue = function(item, column) {
1821 console.warn('gridData.flatItemFieldValue deprecated; '
1822 + 'leave provider.itemFieldValue unset');
1823 return item[column.name];
1826 // given an object and a dot-separated path to a field,
1827 // extract the value of the field. The path can refer
1828 // to function names or object attributes. If the final
1829 // value is an IDL field, run the value through its
1830 // corresponding output filter.
1831 gridData.nestedItemFieldValue = function(obj, column) {
1832 item = obj; // keep a copy around
1834 if (obj === null || obj === undefined || obj === '') return '';
1835 if (!column.path) return obj;
1838 var parts = column.path.split('.');
1840 angular.forEach(parts, function(step, idx) {
1841 // object is not fleshed to the expected extent
1842 if (typeof obj != 'object') {
1843 if (typeof obj != 'undefined' && column.flesher) {
1844 obj = column.flesher(obj, column, item);
1851 if (!obj) return '';
1853 var cls = obj.classname;
1854 if (cls && (class_obj = egCore.idl.classes[cls])) {
1855 idl_field = class_obj.field_map[step];
1856 obj = obj[step] ? obj[step]() : '';
1858 if (angular.isFunction(obj[step])) {
1866 // We found a nested IDL object which may or may not have
1867 // been configured as a top-level column. Grab the datatype.
1868 if (idl_field && !column.datatype)
1869 column.datatype = idl_field.datatype;
1871 if (obj === null || obj === undefined || obj === '') return '';
1877 instance : function(args) {
1878 return new GridDataProvider(args);
1885 // Factory service for egGridDataManager instances, which are
1886 // responsible for collecting flattened grid data.
1887 .factory('egGridFlatDataProvider',
1888 ['$q','egCore','egGridDataProvider',
1889 function($q , egCore , egGridDataProvider) {
1892 instance : function(args) {
1893 var provider = egGridDataProvider.instance(args);
1895 provider.get = function(offset, count) {
1897 // no query means no call
1898 if (!provider.query ||
1899 angular.equals(provider.query, {}))
1902 // find all of the currently visible columns
1903 var queryFields = {}
1904 angular.forEach(provider.columnsProvider.columns,
1906 // only query IDL-tracked columns
1907 if (!col.adhoc && (col.required || col.visible))
1908 queryFields[col.name] = col.path;
1912 return egCore.net.request(
1914 'open-ils.fielder.flattened_search',
1915 egCore.auth.token(), provider.idlClass,
1916 queryFields, provider.query,
1917 { sort : provider.sort,
1923 //provider.itemFieldValue = provider.flatItemFieldValue;
1930 .directive('egGridColumnDragSource', function() {
1933 require : '^egGrid',
1934 link : function(scope, element, attrs, egGridCtrl) {
1935 angular.element(element).attr('draggable', 'true');
1937 element.bind('dragstart', function(e) {
1938 egGridCtrl.dragColumn = attrs.column;
1939 egGridCtrl.dragType = attrs.dragType || 'move'; // or resize
1940 egGridCtrl.colResizeDir = 0;
1942 if (egGridCtrl.dragType == 'move') {
1943 // style the column getting moved
1944 angular.element(e.target).addClass(
1945 'eg-grid-column-move-handle-active');
1949 element.bind('dragend', function(e) {
1950 if (egGridCtrl.dragType == 'move') {
1951 angular.element(e.target).removeClass(
1952 'eg-grid-column-move-handle-active');
1959 .directive('egGridColumnDragDest', function() {
1962 require : '^egGrid',
1963 link : function(scope, element, attrs, egGridCtrl) {
1965 element.bind('dragover', function(e) { // required for drop
1966 e.stopPropagation();
1968 e.dataTransfer.dropEffect = 'move';
1970 if (egGridCtrl.colResizeDir == 0) return; // move
1972 var cols = egGridCtrl.columnsProvider;
1973 var srcCol = egGridCtrl.dragColumn;
1974 var srcColIdx = cols.indexOf(srcCol);
1976 if (egGridCtrl.colResizeDir == -1) {
1977 if (cols.indexOf(attrs.column) <= srcColIdx) {
1978 egGridCtrl.modifyColumnFlex(
1979 egGridCtrl.columnsProvider.findColumn(
1980 egGridCtrl.dragColumn), -1);
1981 if (cols.columns[srcColIdx+1]) {
1982 // source column shrinks by one, column to the
1983 // right grows by one.
1984 egGridCtrl.modifyColumnFlex(
1985 cols.columns[srcColIdx+1], 1);
1990 if (cols.indexOf(attrs.column) > srcColIdx) {
1991 egGridCtrl.modifyColumnFlex(
1992 egGridCtrl.columnsProvider.findColumn(
1993 egGridCtrl.dragColumn), 1);
1994 if (cols.columns[srcColIdx+1]) {
1995 // source column grows by one, column to the
1996 // right grows by one.
1997 egGridCtrl.modifyColumnFlex(
1998 cols.columns[srcColIdx+1], -1);
2006 element.bind('dragenter', function(e) {
2007 e.stopPropagation();
2009 if (egGridCtrl.dragType == 'move') {
2010 angular.element(e.target).addClass('eg-grid-col-hover');
2012 // resize grips are on the right side of each column.
2013 // dragenter will either occur on the source column
2014 // (dragging left) or the column to the right.
2015 if (egGridCtrl.colResizeDir == 0) {
2016 if (egGridCtrl.dragColumn == attrs.column) {
2017 egGridCtrl.colResizeDir = -1; // west
2019 egGridCtrl.colResizeDir = 1; // east
2025 element.bind('dragleave', function(e) {
2026 e.stopPropagation();
2028 if (egGridCtrl.dragType == 'move') {
2029 angular.element(e.target).removeClass('eg-grid-col-hover');
2033 element.bind('drop', function(e) {
2034 e.stopPropagation();
2036 egGridCtrl.colResizeDir = 0;
2037 if (egGridCtrl.dragType == 'move') {
2038 angular.element(e.target).removeClass('eg-grid-col-hover');
2039 egGridCtrl.onColumnDrop(attrs.column); // move the column
2046 .directive('egGridMenuItem', function() {
2049 require : '^egGrid',
2055 handler : '=', // onclick handler function
2056 divider : '=', // if true, show a divider only
2057 handlerData : '=', // if set, passed as second argument to handler
2058 disabled : '=', // function
2059 hidden : '=' // function
2061 link : function(scope, element, attrs, egGridCtrl) {
2062 egGridCtrl.addMenuItem({
2063 checkbox : scope.checkbox,
2064 checked : scope.checked ? true : false,
2065 label : scope.label,
2066 standalone : scope.standalone ? true : false,
2067 handler : scope.handler,
2068 divider : scope.divider,
2069 disabled : scope.disabled,
2070 hidden : scope.hidden,
2071 handlerData : scope.handlerData
2081 * Translates bare IDL object values into display values.
2082 * 1. Passes dates through the angular date filter
2083 * 2. Translates bools to Booleans so the browser can display translated
2084 * value. (Though we could manually translate instead..)
2085 * Others likely to follow...
2087 .filter('egGridValueFilter', ['$filter','egCore', function($filter,egCore) {
2088 function traversePath(obj,path) {
2089 var list = path.split('.');
2090 for (var part in path) {
2091 if (obj[path]) obj = obj[path]
2097 var GVF = function(value, column, item) {
2098 switch(column.datatype) {
2101 // Browser will translate true/false for us
2103 case '1' : // legacy
2107 case '0' : // legacy
2110 // value may be null, '', etc.
2111 default : return '';
2114 var interval = angular.isFunction(item[column.dateonlyinterval])
2115 ? item[column.dateonlyinterval]()
2116 : item[column.dateonlyinterval];
2118 if (column.dateonlyinterval && !interval) // try it as a dotted path
2119 interval = traversePath(item, column.dateonlyinterval);
2121 var context = angular.isFunction(item[column.datecontext])
2122 ? item[column.datecontext]()
2123 : item[column.datecontext];
2125 if (column.datecontext && !context) // try it as a dotted path
2126 context = traversePath(item, column.datecontext);
2128 var date_filter = column.datefilter || 'egOrgDateInContext';
2130 return $filter(date_filter)(value, column.dateformat, context, interval);
2132 return $filter('currency')(value);
2138 GVF.$stateful = true;