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;
182 if (!grid.indexField && grid.idlClass)
183 grid.indexField = egCore.idl.classes[grid.idlClass].pkey;
185 grid.columnsProvider = egGridColumnsProvider.instance({
186 idlClass : grid.idlClass,
187 clientSort : (features.indexOf('clientsort') > -1 && features.indexOf('-clientsort') == -1),
188 defaultToHidden : (features.indexOf('-display') > -1),
189 defaultToNoSort : (features.indexOf('-sort') > -1),
190 defaultToNoMultiSort : (features.indexOf('-multisort') > -1),
191 defaultDateFormat : $scope.dateformat,
192 defaultDateContext : $scope.datecontext,
193 defaultDateFilter : $scope.datefilter,
194 defaultDateOnlyInterval : $scope.dateonlyinterval
196 $scope.canMultiSelect = (features.indexOf('-multiselect') == -1);
198 $scope.handleAutoFields = function() {
199 if ($scope.autoFields) {
200 if (grid.autoLabel) {
202 egCore.idl.classes[grid.idlClass].label;
204 grid.columnsProvider.compileAutoColumns();
205 delete $scope.autoFields;
209 if (!grid.dataProvider) {
210 // no provider, um, provided.
211 // Use a flat data provider
213 grid.selfManagedData = true;
214 grid.dataProvider = egGridFlatDataProvider.instance({
215 indexField : grid.indexField,
216 idlClass : grid.idlClass,
217 columnsProvider : grid.columnsProvider,
222 // make grid ref available in get() to set totalCount, if known.
223 // this allows us disable the 'next' paging button correctly
224 grid.dataProvider.grid = grid;
226 grid.dataProvider.columnsProvider = grid.columnsProvider;
228 $scope.itemFieldValue = grid.dataProvider.itemFieldValue;
229 $scope.indexValue = function(item) {
230 return grid.indexValue(item)
233 grid.applyControlFunctions();
235 grid.loadConfig().then(function() {
236 // link columns to scope after loadConfig(), since it
237 // replaces the columns array.
238 $scope.columns = grid.columnsProvider.columns;
241 // NOTE: grid.collect() is first called from link(), not here.
244 // link our control functions into the gridControls
245 // scope object so the caller can access them.
246 grid.applyControlFunctions = function() {
248 // we use some of these controls internally, so sett
249 // them up even if the caller doesn't request them.
250 var controls = $scope.gridControls || {};
252 controls.columnMap = function() {
254 angular.forEach(grid.columnsProvider.columns, function (c) {
260 controls.columnsProvider = function() {
261 return grid.columnsProvider;
264 // link in the control functions
265 controls.selectedItems = function() {
266 return grid.getSelectedItems()
269 controls.allItems = function() {
273 controls.selectItems = function(ids) {
275 $scope.selected = {};
276 angular.forEach(ids, function(i) {
277 $scope.selected[''+i] = true;
281 // if the caller provided a functional setQuery,
282 // extract the value before replacing it
283 if (controls.setQuery) {
284 grid.dataProvider.query =
288 controls.setQuery = function(query) {
289 grid.dataProvider.query = query;
293 if (controls.watchQuery) {
294 // capture the initial query value
295 grid.dataProvider.query = controls.watchQuery();
298 $scope.gridWatchQuery = controls.watchQuery;
299 $scope.$watch('gridWatchQuery()', function(newv) {
300 controls.setQuery(newv);
304 // if the caller provided a functional setSort
305 // extract the value before replacing it
306 grid.dataProvider.sort =
307 controls.setSort ? controls.setSort() : [];
309 controls.setSort = function(sort) {
313 controls.refresh = function(noReset) {
314 if (!noReset) grid.offset = 0;
318 controls.setLimit = function(limit,forget) {
319 if (!forget && grid.persistKey)
320 egCore.hatch.setLocalItem('eg.grid.' + grid.persistKey + '.limit', limit);
323 controls.getLimit = function() {
326 controls.setOffset = function(offset) {
327 grid.offset = offset;
329 controls.getOffset = function() {
333 controls.saveConfig = function () {
334 return $scope.saveConfig();
337 grid.dataProvider.refresh = controls.refresh;
338 grid.controls = controls;
341 // If a menu item provides its own HTML template, translate it,
342 // using the menu item for the template scope.
343 // note: $sce is required to avoid security restrictions and
344 // is OK here, since the template comes directly from a
345 // local HTML template (not user input).
346 $scope.translateMenuItemTemplate = function(item) {
347 var html = egCore.strings.$replace(item.template, {item : item});
348 return $sce.trustAsHtml(html);
351 // add a new (global) grid menu item
352 grid.addMenuItem = function(item) {
353 $scope.menuItems.push(item);
354 var handler = item.handler;
355 item.handler = function() {
356 $scope.gridMenuIsOpen = false; // close menu
359 item.handlerData, grid.getSelectedItems());
364 // add a selected-items action
365 grid.addAction = function(act) {
367 $scope.actionGroups.forEach(function(g){
368 if (g.label === act.group) {
374 $scope.actionGroups.push({
381 // remove the stored column configuration preferenc, then recover
382 // the column visibility information from the initial page load.
383 $scope.resetColumns = function() {
384 $scope.gridColumnPickerIsOpen = false;
385 egCore.hatch.removeItem('eg.grid.' + grid.persistKey)
387 grid.columnsProvider.reset();
388 if (grid.selfManagedData) grid.collect();
392 $scope.showAllColumns = function() {
393 $scope.gridColumnPickerIsOpen = false;
394 grid.columnsProvider.showAllColumns();
395 if (grid.selfManagedData) grid.collect();
398 $scope.hideAllColumns = function() {
399 $scope.gridColumnPickerIsOpen = false;
400 grid.columnsProvider.hideAllColumns();
401 // note: no need to fetch new data if no columns are visible
404 $scope.toggleColumnVisibility = function(col) {
405 $scope.gridColumnPickerIsOpen = false;
406 col.visible = !col.visible;
408 // egGridFlatDataProvider only retrieves data to be
409 // displayed. When column visibility changes, it's
410 // necessary to fetch the newly visible column data.
411 if (grid.selfManagedData) grid.collect();
414 // save the columns configuration (position, sort, width) to
415 // eg.grid.<persist-key>
416 $scope.saveConfig = function() {
417 $scope.gridColumnPickerIsOpen = false;
419 if (!grid.persistKey) {
421 "Cannot save settings without a grid persist-key");
425 // only store information about visible columns.
426 var conf = grid.columnsProvider.columns.filter(
427 function(col) {return Boolean(col.visible) });
429 // now scrunch the data down to just the needed info
430 conf = conf.map(function(col) {
431 var c = {name : col.name}
432 // Apart from the name, only store non-default values.
433 // No need to store col.visible, since that's implicit
434 if (col.align != 'left') c.align = col.align;
435 if (col.flex != 2) c.flex = col.flex;
436 if (Number(col.sort)) c.sort = Number(c.sort);
440 egCore.hatch.setItem('eg.grid.' + grid.persistKey, conf)
442 // Save operation performed from the grid configuration UI.
443 // Hide the configuration UI and re-draw w/ sort applied
444 if ($scope.showGridConf)
445 $scope.toggleConfDisplay();
450 // load the columns configuration (position, sort, width) from
451 // eg.grid.<persist-key> and apply the loaded settings to the
452 // columns on our columnsProvider
453 grid.loadConfig = function() {
454 if (!grid.persistKey) return $q.when();
456 return egCore.hatch.getItem('eg.grid.' + grid.persistKey)
457 .then(function(conf) {
460 var columns = grid.columnsProvider.columns;
463 angular.forEach(conf, function(col) {
464 var grid_col = columns.filter(
465 function(c) {return c.name == col.name})[0];
468 // saved column does not match a column in the
469 // current grid. skip it.
473 grid_col.align = col.align || 'left';
474 grid_col.flex = col.flex || 2;
475 grid_col.sort = col.sort || 0;
476 // all saved columns are assumed to be true
477 grid_col.visible = true;
479 .filter(function (c) {
480 return c.name == grid_col.name;
483 new_cols.push(grid_col);
486 // columns which are not expressed within the saved
487 // configuration are marked as non-visible and
488 // appended to the end of the new list of columns.
489 angular.forEach(columns, function(col) {
490 var found = conf.filter(
491 function(c) {return (c.name == col.name)})[0];
498 grid.columnsProvider.columns = new_cols;
504 $scope.onContextMenu = function($event) {
505 var col = angular.element($event.target).attr('column');
506 console.log('selected column ' + col);
509 $scope.page = function() {
510 return (grid.offset / grid.limit) + 1;
513 $scope.goToPage = function(page) {
515 if (angular.isNumber(page) && page > 0) {
516 grid.offset = (page - 1) * grid.limit;
521 $scope.offset = function(o) {
522 if (angular.isNumber(o))
527 $scope.limit = function(l) {
528 if (angular.isNumber(l)) {
530 egCore.hatch.setLocalItem('eg.grid.' + grid.persistKey + '.limit', l);
536 $scope.onFirstPage = function() {
537 return grid.offset == 0;
540 $scope.hasNextPage = function() {
541 // we have less data than requested, there must
542 // not be any more pages
543 if (grid.count() < grid.limit) return false;
545 // if the total count is not known, assume that a full
546 // page of data implies more pages are available.
547 if (grid.totalCount == -1) return true;
549 // we have a full page of data, but is there more?
550 return grid.totalCount > (grid.offset + grid.count());
553 $scope.incrementPage = function() {
554 grid.offset += grid.limit;
558 $scope.decrementPage = function() {
559 if (grid.offset < grid.limit) {
562 grid.offset -= grid.limit;
567 // number of items loaded for the current page of results
568 grid.count = function() {
569 return $scope.items.length;
572 // returns the unique identifier value for the provided item
573 // for internal consistency, indexValue is always coerced
575 grid.indexValue = function(item) {
576 if (angular.isObject(item)) {
578 if (angular.isFunction(item[grid.indexField]))
579 return ''+item[grid.indexField]();
580 return ''+item[grid.indexField]; // flat data
583 // passed a non-object; assume it's an index
587 // fires the hide handler function for a context action
588 $scope.actionHide = function(action) {
589 if (typeof action.hide == 'undefined') {
592 if (angular.isFunction(action.hide))
593 return action.hide(action);
597 // fires the disable handler function for a context action
598 $scope.actionDisable = function(action) {
599 if (typeof action.disabled == 'undefined') {
602 if (angular.isFunction(action.disabled))
603 return action.disabled(action);
604 return action.disabled;
607 // fires the action handler function for a context action
608 $scope.actionLauncher = function(action) {
609 if (!action.handler) {
611 'No handler specified for "' + action.label + '"');
615 action.handler(grid.getSelectedItems());
617 console.error('Error executing handler for "'
618 + action.label + '" => ' + E + "\n" + E.stack);
621 if ($scope.action_context_showing) $scope.hideActionContextMenu();
626 $scope.hideActionContextMenu = function () {
627 $($scope.menu_dom).css({
629 width: $scope.action_context_width,
630 top: $scope.action_context_y,
631 left: $scope.action_context_x
633 $($scope.action_context_parent).append($scope.menu_dom);
634 $scope.action_context_oldy = $scope.action_context_oldx = 0;
635 $('body').unbind('click.remove_context_menu_'+$scope.action_context_index);
636 $scope.action_context_showing = false;
639 $scope.action_context_showing = false;
640 $scope.showActionContextMenu = function ($event) {
642 // Have to gather these here, instead of inside link()
643 if (!$scope.menu_dom) $scope.menu_dom = $($scope.grid_element).find('.grid-action-dropdown')[0];
644 if (!$scope.action_context_parent) $scope.action_context_parent = $($scope.menu_dom).parent();
646 if (!grid.getSelectedItems().length) // Nothing selected, fire the click event
647 $event.target.click();
649 if (!$scope.action_context_showing) {
650 $scope.action_context_width = $($scope.menu_dom).css('width');
651 $scope.action_context_y = $($scope.menu_dom).css('top');
652 $scope.action_context_x = $($scope.menu_dom).css('left');
653 $scope.action_context_showing = true;
654 $scope.action_context_index = Math.floor((Math.random() * 1000) + 1);
656 $('body').append($($scope.menu_dom));
657 $('body').bind('click.remove_context_menu_'+$scope.action_context_index, $scope.hideActionContextMenu);
660 $($scope.menu_dom).css({
662 width: $scope.action_context_width,
670 // returns the list of selected item objects
671 grid.getSelectedItems = function() {
672 return $scope.items.filter(
674 return Boolean($scope.selected[grid.indexValue(item)]);
679 grid.getItemByIndex = function(index) {
680 for (var i = 0; i < $scope.items.length; i++) {
681 var item = $scope.items[i];
682 if (grid.indexValue(item) == index)
687 // selects one row after deselecting all of the others
688 grid.selectOneItem = function(index) {
689 $scope.selected = {};
690 $scope.selected[index] = true;
693 // selects or deselects an item, without affecting the others.
694 // returns true if the item is selected; false if de-selected.
695 // we overwrite the object so that we can watch $scope.selected
696 grid.toggleSelectOneItem = function(index) {
697 if ($scope.selected[index]) {
698 delete $scope.selected[index];
699 $scope.selected = angular.copy($scope.selected);
702 $scope.selected[index] = true;
703 $scope.selected = angular.copy($scope.selected);
708 $scope.updateSelected = function () {
709 return $scope.selected = angular.copy($scope.selected);
712 grid.selectAllItems = function() {
713 angular.forEach($scope.items, function(item) {
714 $scope.selected[grid.indexValue(item)] = true
716 $scope.selected = angular.copy($scope.selected);
719 $scope.$watch('selectAll', function(newVal) {
721 grid.selectAllItems();
723 $scope.selected = {};
727 if ($scope.onSelect) {
728 $scope.$watch('selected', function(newVal) {
729 $scope.onSelect(grid.getSelectedItems());
730 if ($scope.afterSelect) $scope.afterSelect();
734 // returns true if item1 appears in the list before item2;
735 // false otherwise. this is slightly more efficient that
736 // finding the position of each then comparing them.
737 // item1 / item2 may be an item or an item index
738 grid.itemComesBefore = function(itemOrIndex1, itemOrIndex2) {
739 var idx1 = grid.indexValue(itemOrIndex1);
740 var idx2 = grid.indexValue(itemOrIndex2);
742 // use for() for early exit
743 for (var i = 0; i < $scope.items.length; i++) {
744 var idx = grid.indexValue($scope.items[i]);
745 if (idx == idx1) return true;
746 if (idx == idx2) return false;
751 // 0-based position of item in the current data set
752 grid.indexOf = function(item) {
753 var idx = grid.indexValue(item);
754 for (var i = 0; i < $scope.items.length; i++) {
755 if (grid.indexValue($scope.items[i]) == idx)
761 grid.modifyColumnFlex = function(column, val) {
763 // prevent flex:0; use hiding instead
767 $scope.modifyColumnFlex = function(col, val) {
768 $scope.lastModColumn = col;
769 grid.modifyColumnFlex(col, val);
772 $scope.isLastModifiedColumn = function(col) {
773 if ($scope.lastModColumn)
774 return $scope.lastModColumn === col;
778 grid.modifyColumnPos = function(col, diff) {
779 var srcIdx, targetIdx;
780 angular.forEach(grid.columnsProvider.columns,
781 function(c, i) { if (c.name == col.name) srcIdx = i });
783 targetIdx = srcIdx + diff;
786 } else if (targetIdx >= grid.columnsProvider.columns.length) {
787 // Target index follows the last visible column.
789 angular.forEach(grid.columnsProvider.columns,
790 function(column, idx) {
791 if (column.visible) lastVisible = idx;
795 // When moving a column (down) causes one or more
796 // visible columns to shuffle forward, our column
797 // moves into the slot of the last visible column.
798 // Otherwise, put it into the slot directly following
799 // the last visible column.
801 srcIdx <= lastVisible ? lastVisible : lastVisible + 1;
804 // Splice column out of old position, insert at new position.
805 grid.columnsProvider.columns.splice(srcIdx, 1);
806 grid.columnsProvider.columns.splice(targetIdx, 0, col);
809 $scope.modifyColumnPos = function(col, diff) {
810 $scope.lastModColumn = col;
811 return grid.modifyColumnPos(col, diff);
815 // handles click, control-click, and shift-click
816 $scope.handleRowClick = function($event, item) {
817 var index = grid.indexValue(item);
819 var origSelected = Object.keys($scope.selected);
821 if (!$scope.canMultiSelect) {
822 grid.selectOneItem(index);
823 grid.lastSelectedItemIndex = index;
827 if ($event.ctrlKey || $event.metaKey /* mac command */) {
829 if (grid.toggleSelectOneItem(index))
830 grid.lastSelectedItemIndex = index;
832 } else if ($event.shiftKey) {
835 if (!grid.lastSelectedItemIndex ||
836 index == grid.lastSelectedItemIndex) {
837 grid.selectOneItem(index);
838 grid.lastSelectedItemIndex = index;
842 var selecting = false;
843 var ascending = grid.itemComesBefore(
844 grid.lastSelectedItemIndex, item);
846 grid.indexOf(grid.lastSelectedItemIndex);
848 // update to new last-selected
849 grid.lastSelectedItemIndex = index;
851 // select each row between the last selected and
852 // currently selected items
854 startPos += ascending ? 1 : -1;
855 var curItem = $scope.items[startPos];
857 var curIdx = grid.indexValue(curItem);
858 $scope.selected[curIdx] = true;
859 if (curIdx == index) break; // all done
861 $scope.selected = angular.copy($scope.selected);
865 grid.selectOneItem(index);
866 grid.lastSelectedItemIndex = index;
870 // Builds a sort expression from column sort priorities.
871 // called on page load and any time the priorities are modified.
872 grid.compileSort = function() {
873 var sortList = grid.columnsProvider.columns.filter(
874 function(col) { return Number(col.sort) != 0 }
877 if (Math.abs(a.sort) < Math.abs(b.sort))
883 if (sortList.length) {
884 grid.dataProvider.sort = sortList.map(function(col) {
886 blob[col.name] = col.sort < 0 ? 'desc' : 'asc';
892 // builds a sort expression using a single column,
893 // toggling between ascending and descending sort.
894 $scope.quickSort = function(col_name) {
895 var sort = grid.dataProvider.sort;
896 if (sort && sort.length &&
897 sort[0] == col_name) {
899 blob[col_name] = 'desc';
900 grid.dataProvider.sort = [blob];
902 grid.dataProvider.sort = [col_name];
909 // show / hide the grid configuration row
910 $scope.toggleConfDisplay = function() {
911 if ($scope.showGridConf) {
912 $scope.showGridConf = false;
913 if (grid.columnsProvider.hasSortableColumn()) {
914 // only refresh the grid if the user has the
915 // ability to modify the sort priorities.
921 $scope.showGridConf = true;
924 delete $scope.lastModColumn;
925 $scope.gridColumnPickerIsOpen = false;
928 // called when a dragged column is dropped onto itself
929 // or any other column
930 grid.onColumnDrop = function(target) {
931 if (angular.isUndefined(target)) return;
932 if (target == grid.dragColumn) return;
933 var srcIdx, targetIdx, srcCol;
934 angular.forEach(grid.columnsProvider.columns,
936 if (col.name == grid.dragColumn) {
939 } else if (col.name == target) {
945 if (srcIdx < targetIdx) targetIdx--;
947 // move src column from old location to new location in
948 // the columns array, then force a page refresh
949 grid.columnsProvider.columns.splice(srcIdx, 1);
950 grid.columnsProvider.columns.splice(targetIdx, 0, srcCol);
954 // prepares a string for inclusion within a CSV document
955 // by escaping commas and quotes and removing newlines.
956 grid.csvDatum = function(str) {
959 str = str.replace(/\n/g, '');
960 if (str.match(/\,/) || str.match(/"/)) {
961 str = str.replace(/"/g, '""');
962 str = '"' + str + '"';
967 /** Export the full data set as CSV.
969 * 1. User clicks the 'download csv' link
970 * 2. All grid data is retrieved asychronously
971 * 3. Once all data is all present and CSV-ized, the download
972 * attributes are linked to the href.
973 * 4. The href .click() action is prgrammatically fired again,
974 * telling the browser to download the data, now that the
975 * data is available for download.
976 * 5 Once downloaded, the href attributes are reset.
978 grid.csvExportInProgress = false;
979 $scope.generateCSVExportURL = function($event) {
981 if (grid.csvExportInProgress) {
982 // This is secondary href click handler. Give the
983 // browser a moment to start the download, then reset
984 // the CSV download attributes / state.
987 $scope.csvExportURL = '';
988 $scope.csvExportFileName = '';
989 grid.csvExportInProgress = false;
995 grid.csvExportInProgress = true;
996 $scope.gridColumnPickerIsOpen = false;
998 // let the file name describe the grid
999 $scope.csvExportFileName =
1000 ($scope.mainLabel || grid.persistKey || 'eg_grid_data')
1001 .replace(/\s+/g, '_') + '_' + $scope.page();
1003 // toss the CSV into a Blob and update the export URL
1004 grid.generateCSV().then(function(csv) {
1005 var blob = new Blob([csv], {type : 'text/plain'});
1006 $scope.csvExportURL =
1007 ($window.URL || $window.webkitURL).createObjectURL(blob);
1009 // Fire the 2nd click event now that the browser has
1010 // information on how to download the CSV file.
1011 $timeout(function() {$event.target.click()});
1016 * TODO: does this serve any purpose given we can
1017 * print formatted HTML? If so, generateCSV() now
1018 * returns a promise, needs light refactoring...
1019 $scope.printCSV = function() {
1020 $scope.gridColumnPickerIsOpen = false;
1021 egCore.print.print({
1022 context : 'default',
1023 content : grid.generateCSV(),
1024 content_type : 'text/plain'
1029 // Given a row item and column definition, extract the
1030 // text content for printing. Templated columns must be
1031 // processed and parsed as HTML, then boiled down to their
1033 grid.getItemTextContent = function(item, col) {
1036 val = $scope.translateCellTemplate(col, item);
1038 var node = new DOMParser()
1039 .parseFromString(val, 'text/html');
1040 val = $(node).text();
1043 val = grid.dataProvider.itemFieldValue(item, col);
1044 val = $filter('egGridValueFilter')(val, col, item);
1050 * Fetches all grid data and transates each item into a simple
1051 * key-value pair of column name => text-value.
1052 * Included in the response for convenience is the list of
1053 * currently visible column definitions.
1054 * TODO: currently fetches a maximum of 10k rows. Does this
1055 * need to be configurable?
1057 grid.getAllItemsAsText = function() {
1058 var text_items = [];
1060 // we don't know the total number of rows we're about
1061 // to retrieve, but we can indicate the number retrieved
1062 // so far as each item arrives.
1063 egProgressDialog.open({value : 0});
1065 var visible_cols = grid.columnsProvider.columns.filter(
1066 function(c) { return c.visible });
1068 return grid.dataProvider.get(0, 10000).then(
1070 return {items : text_items, columns : visible_cols};
1074 egProgressDialog.increment();
1076 angular.forEach(visible_cols, function(col) {
1077 text_item[col.name] =
1078 grid.getItemTextContent(item, col);
1080 text_items.push(text_item);
1082 ).finally(egProgressDialog.close);
1085 // Fetch "all" of the grid data, translate it into print-friendly
1086 // text, and send it to the printer service.
1087 $scope.printHTML = function() {
1088 $scope.gridColumnPickerIsOpen = false;
1089 return grid.getAllItemsAsText().then(function(text_items) {
1090 return egCore.print.print({
1091 template : 'grid_html',
1097 $scope.showColumnDialog = function() {
1098 return $uibModal.open({
1099 templateUrl: './share/t_grid_columns',
1102 controller: ['$scope', '$uibModalInstance',
1103 function($dialogScope, $uibModalInstance) {
1104 $dialogScope.modifyColumnPos = $scope.modifyColumnPos;
1105 $dialogScope.disableMultiSort = $scope.disableMultiSort;
1106 $dialogScope.columns = $scope.columns;
1108 // Push visible columns to the top of the list
1109 $dialogScope.elevateVisible = function() {
1111 angular.forEach($dialogScope.columns, function(col) {
1112 if (col.visible) new_cols.push(col);
1114 angular.forEach($dialogScope.columns, function(col) {
1115 if (!col.visible) new_cols.push(col);
1118 // Update all references to the list of columns
1119 $dialogScope.columns =
1121 grid.columnsProvider.columns =
1125 $dialogScope.toggle = function(col) {
1126 col.visible = !Boolean(col.visible);
1128 $dialogScope.ok = $dialogScope.cancel = function() {
1129 delete $scope.lastModColumn;
1130 $uibModalInstance.close()
1137 // generates CSV for the currently visible grid contents
1138 grid.generateCSV = function() {
1139 return grid.getAllItemsAsText().then(function(text_items) {
1140 var columns = text_items.columns;
1141 var items = text_items.items;
1145 angular.forEach(columns, function(col) {
1146 csvStr += grid.csvDatum(col.label);
1150 csvStr = csvStr.replace(/,$/,'\n');
1153 angular.forEach(items, function(item) {
1154 angular.forEach(columns, function(col) {
1155 csvStr += grid.csvDatum(item[col.name]);
1158 csvStr = csvStr.replace(/,$/,'\n');
1165 // Interpolate the value for column.linkpath within the context
1166 // of the row item to generate the final link URL.
1167 $scope.generateLinkPath = function(col, item) {
1168 return egCore.strings.$replace(col.linkpath, {item : item});
1171 // If a column provides its own HTML template, translate it,
1172 // using the current item for the template scope.
1173 // note: $sce is required to avoid security restrictions and
1174 // is OK here, since the template comes directly from a
1175 // local HTML template (not user input).
1176 $scope.translateCellTemplate = function(col, item) {
1177 var html = egCore.strings.$replace(col.template, {item : item});
1178 return $sce.trustAsHtml(html);
1181 $scope.collect = function() { grid.collect() }
1183 // asks the dataProvider for a page of data
1184 grid.collect = function() {
1186 // avoid firing the collect if there is nothing to collect.
1187 if (grid.selfManagedData && !grid.dataProvider.query) return;
1189 if (grid.collecting) return; // avoid parallel collect()
1190 grid.collecting = true;
1192 console.debug('egGrid.collect() offset='
1193 + grid.offset + '; limit=' + grid.limit);
1195 // ensure all of our dropdowns are closed
1196 // TODO: git rid of these and just use dropdown-toggle,
1197 // which is more reliable.
1198 $scope.gridColumnPickerIsOpen = false;
1199 $scope.gridRowCountIsOpen = false;
1200 $scope.gridPageSelectIsOpen = false;
1203 $scope.selected = {};
1205 // Inform the caller we've asked the data provider
1206 // for data. This is useful for knowing when collection
1207 // has started (e.g. to display a progress dialg) when
1208 // using the stock (flattener) data provider, where the
1209 // user is not directly defining a get() handler.
1210 if (grid.controls.collectStarted)
1211 grid.controls.collectStarted(grid.offset, grid.limit);
1213 grid.dataProvider.get(grid.offset, grid.limit).then(
1215 if (grid.controls.allItemsRetrieved)
1216 grid.controls.allItemsRetrieved();
1221 $scope.items.push(item)
1222 if (grid.controls.itemRetrieved)
1223 grid.controls.itemRetrieved(item);
1224 if ($scope.selectAll)
1225 $scope.selected[grid.indexValue(item)] = true
1227 }).finally(function() {
1228 console.debug('egGrid.collect() complete');
1229 grid.collecting = false
1230 $scope.selected = angular.copy($scope.selected);
1240 * eg-grid-field : used for collecting custom field data from the templates.
1241 * This directive does not direct display, it just passes data up to the
1244 .directive('egGridField', function() {
1246 require : '^egGrid',
1249 flesher: '=', // optional; function that can flesh a linked field, given the value
1250 comparator: '=', // optional; function that can sort the thing at the end of 'path'
1251 name : '@', // required; unique name
1252 path : '@', // optional; flesh path
1253 ignore: '@', // optional; fields to ignore when path is a wildcard
1254 label : '@', // optional; display label
1255 flex : '@', // optional; default flex width
1256 align : '@', // optional; default alignment, left/center/right
1257 dateformat : '@', // optional: passed down to egGridValueFilter
1258 datecontext: '@', // optional: passed down to egGridValueFilter to choose TZ
1259 datefilter: '@', // optional: passed down to egGridValueFilter to choose specialized date filters
1260 dateonlyinterval: '@', // optional: passed down to egGridValueFilter to choose a "better" format
1262 // if a field is part of an IDL object, but we are unable to
1263 // determine the class, because it's nested within a hash
1264 // (i.e. we can't navigate directly to the object via the IDL),
1265 // idlClass lets us specify the class. This is particularly
1266 // useful for nested wildcard fields.
1267 parentIdlClass : '@',
1269 // optional: for non-IDL columns, specifying a datatype
1270 // lets the caller control which display filter is used.
1271 // datatype should match the standard IDL datatypes.
1274 // optional hash of functions that can be imported into
1275 // the directive's scope; meant for cases where the "compiled"
1279 link : function(scope, element, attrs, egGridCtrl) {
1281 // boolean fields are presented as value-less attributes
1291 'required' // if set, always fetch data for this column
1294 if (angular.isDefined(attrs[field]))
1295 scope[field] = true;
1299 // any HTML content within the field is its custom template
1300 var tmpl = element.html();
1301 if (tmpl && !tmpl.match(/^\s*$/))
1302 scope.template = tmpl
1304 egGridCtrl.columnsProvider.add(scope);
1311 * eg-grid-action : used for specifying actions which may be applied
1312 * to items within the grid.
1314 .directive('egGridAction', function() {
1316 require : '^egGrid',
1320 group : '@', // Action group, ungrouped if not set
1321 label : '@', // Action label
1322 handler : '=', // Action function handler
1324 disabled : '=', // function
1327 link : function(scope, element, attrs, egGridCtrl) {
1328 egGridCtrl.addAction({
1330 group : scope.group,
1331 label : scope.label,
1332 divider : scope.divider,
1333 handler : scope.handler,
1334 disabled : scope.disabled,
1341 .factory('egGridColumnsProvider', ['egCore', function(egCore) {
1343 function ColumnsProvider(args) {
1346 cols.stockVisible = [];
1347 cols.idlClass = args.idlClass;
1348 cols.clientSort = args.clientSort;
1349 cols.defaultToHidden = args.defaultToHidden;
1350 cols.defaultToNoSort = args.defaultToNoSort;
1351 cols.defaultToNoMultiSort = args.defaultToNoMultiSort;
1352 cols.defaultDateFormat = args.defaultDateFormat;
1353 cols.defaultDateContext = args.defaultDateContext;
1355 // resets column width, visibility, and sort behavior
1356 // Visibility resets to the visibility settings defined in the
1357 // template (i.e. the original egGridField values).
1358 cols.reset = function() {
1359 angular.forEach(cols.columns, function(col) {
1363 if (cols.stockVisible.indexOf(col.name) > -1) {
1366 col.visible = false;
1371 // returns true if any columns are sortable
1372 cols.hasSortableColumn = function() {
1373 return cols.columns.filter(
1375 return col.sortable || col.multisortable;
1380 cols.showAllColumns = function() {
1381 angular.forEach(cols.columns, function(column) {
1382 column.visible = true;
1386 cols.hideAllColumns = function() {
1387 angular.forEach(cols.columns, function(col) {
1392 cols.indexOf = function(name) {
1393 for (var i = 0; i < cols.columns.length; i++) {
1394 if (cols.columns[i].name == name)
1400 cols.findColumn = function(name) {
1401 return cols.columns[cols.indexOf(name)];
1404 cols.compileAutoColumns = function() {
1405 var idl_class = egCore.idl.classes[cols.idlClass];
1410 if (field.virtual) return;
1411 if (field.datatype == 'link' || field.datatype == 'org_unit') {
1412 // if the field is a link and the linked class has a
1413 // "selector" field specified, use the selector field
1414 // as the display field for the columns.
1415 // flattener will take care of the fleshing.
1416 if (field['class']) {
1417 var selector_field = egCore.idl.classes[field['class']].fields
1418 .filter(function(f) { return Boolean(f.selector) })[0];
1419 if (selector_field) {
1420 field.path = field.name + '.' + selector_field.selector;
1424 cols.add(field, true);
1429 // if a column definition has a path with a wildcard, create
1430 // columns for all non-virtual fields at the specified
1431 // position in the path.
1432 cols.expandPath = function(colSpec) {
1434 var ignoreList = [];
1436 ignoreList = colSpec.ignore.split(' ');
1438 var dotpath = colSpec.path.replace(/\.?\*$/,'');
1442 if (colSpec.parentIdlClass) {
1443 class_obj = egCore.idl.classes[colSpec.parentIdlClass];
1445 class_obj = egCore.idl.classes[cols.idlClass];
1447 var idl_parent = class_obj;
1448 var old_field_label = '';
1450 if (!class_obj) return;
1452 //console.debug('egGrid: auto dotpath is: ' + dotpath);
1453 var path_parts = dotpath.split(/\./);
1455 // find the IDL class definition for the last element in the
1456 // path before the .*
1457 // an empty path_parts means expand the root class
1460 for (var path_idx in path_parts) {
1461 old_field = idl_field;
1463 var part = path_parts[path_idx];
1464 idl_field = class_obj.field_map[part];
1466 // unless we're at the end of the list, this field should
1467 // link to another class.
1468 if (idl_field && idl_field['class'] && (
1469 idl_field.datatype == 'link' ||
1470 idl_field.datatype == 'org_unit')) {
1471 if (old_field_label) old_field_label += ' : ';
1472 old_field_label += idl_field.label;
1473 class_obj = egCore.idl.classes[idl_field['class']];
1474 if (old_field) idl_parent = old_field;
1476 if (path_idx < (path_parts.length - 1)) {
1477 // we ran out of classes to hop through before
1478 // we ran out of path components
1479 console.error("egGrid: invalid IDL path: " + dotpath);
1486 angular.forEach(class_obj.fields, function(field) {
1488 // Only show wildcard fields where we have data to show
1489 // Virtual and un-fleshed links will not have any data.
1490 if (field.virtual ||
1491 (field.datatype == 'link' || field.datatype == 'org_unit') ||
1492 ignoreList.indexOf(field.name) > -1
1496 var col = cols.cloneFromScope(colSpec);
1497 col.path = (dotpath ? dotpath + '.' + field.name : field.name);
1499 // log line below is very chatty. disable until needed.
1500 // console.debug('egGrid: field: ' +field.name + '; parent field: ' + js2JSON(idl_parent));
1501 cols.add(col, false, true,
1502 {idl_parent : idl_parent, idl_field : field, idl_class : class_obj, field_parent_label : old_field_label });
1505 cols.columns = cols.columns.sort(
1507 if (a.explicit) return -1;
1508 if (b.explicit) return 1;
1510 if (a.idlclass && b.idlclass) {
1511 if (a.idlclass < b.idlclass) return -1;
1512 if (b.idlclass < a.idlclass) return 1;
1515 if (a.path && b.path && a.path.lastIndexOf('.') && b.path.lastIndexOf('.')) {
1516 if (a.path.substring(0, a.path.lastIndexOf('.')) < b.path.substring(0, b.path.lastIndexOf('.'))) return -1;
1517 if (b.path.substring(0, b.path.lastIndexOf('.')) < a.path.substring(0, a.path.lastIndexOf('.'))) return 1;
1520 if (a.label && b.label) {
1521 if (a.label < b.label) return -1;
1522 if (b.label < a.label) return 1;
1525 return a.name < b.name ? -1 : 1;
1532 "egGrid: wildcard path does not resolve to an object: "
1537 // angular.clone(scopeObject) is not permittable. Manually copy
1538 // the fields over that we need (so the scope object can go away).
1539 cols.cloneFromScope = function(colSpec) {
1541 flesher : colSpec.flesher,
1542 comparator : colSpec.comparator,
1543 name : colSpec.name,
1544 label : colSpec.label,
1545 path : colSpec.path,
1546 align : colSpec.align || 'left',
1547 flex : Number(colSpec.flex) || 2,
1548 sort : Number(colSpec.sort) || 0,
1549 required : colSpec.required,
1550 linkpath : colSpec.linkpath,
1551 template : colSpec.template,
1552 visible : colSpec.visible,
1553 compiled : colSpec.compiled,
1554 handlers : colSpec.handlers,
1555 hidden : colSpec.hidden,
1556 datatype : colSpec.datatype,
1557 sortable : colSpec.sortable,
1558 nonsortable : colSpec.nonsortable,
1559 multisortable : colSpec.multisortable,
1560 nonmultisortable : colSpec.nonmultisortable,
1561 dateformat : colSpec.dateformat,
1562 datecontext : colSpec.datecontext,
1563 datefilter : colSpec.datefilter,
1564 dateonlyinterval : colSpec.dateonlyinterval,
1565 parentIdlClass : colSpec.parentIdlClass
1570 // Add a column to the columns collection.
1571 // Columns may come from a slim eg-columns-field or
1572 // directly from the IDL.
1573 cols.add = function(colSpec, fromIDL, fromExpand, idl_info) {
1575 // First added column with the specified path takes precedence.
1576 // This allows for specific definitions followed by wildcard
1577 // definitions. If a match is found, back out.
1578 if (cols.columns.filter(function(c) {
1579 return (c.path == colSpec.path) })[0]) {
1580 console.debug('skipping pre-existing column ' + colSpec.path);
1584 var column = fromExpand ? colSpec : cols.cloneFromScope(colSpec);
1586 if (column.path && column.path.match(/\*$/))
1587 return cols.expandPath(colSpec);
1589 if (!fromExpand) column.explicit = true;
1591 if (!column.name) column.name = column.path;
1592 if (!column.path) column.path = column.name;
1594 if (column.visible || (!cols.defaultToHidden && !column.hidden))
1595 column.visible = true;
1597 if (column.sortable || (!cols.defaultToNoSort && !column.nonsortable))
1598 column.sortable = true;
1600 if (column.multisortable ||
1601 (!cols.defaultToNoMultiSort && !column.nonmultisortable))
1602 column.multisortable = true;
1604 if (cols.defaultDateFormat && ! column.dateformat) {
1605 column.dateformat = cols.defaultDateFormat;
1608 if (cols.defaultDateOnlyInterval && ! column.dateonlyinterval) {
1609 column.dateonlyinterval = cols.defaultDateOnlyInterval;
1612 if (cols.defaultDateContext && ! column.datecontext) {
1613 column.datecontext = cols.defaultDateContext;
1616 if (cols.defaultDateFilter && ! column.datefilter) {
1617 column.datefilter = cols.defaultDateFilter;
1620 cols.columns.push(column);
1622 // Track which columns are visible by default in case we
1623 // need to reset column visibility
1625 cols.stockVisible.push(column.name);
1627 if (fromIDL) return; // directly from egIDL. nothing left to do.
1629 // lookup the matching IDL field
1630 if (!idl_info && cols.idlClass)
1631 idl_info = cols.idlFieldFromPath(column.path);
1634 // column is not represented within the IDL
1635 column.adhoc = true;
1639 column.datatype = idl_info.idl_field.datatype;
1641 if (!column.label) {
1642 column.label = idl_info.idl_field.label || column.name;
1645 if (fromExpand && idl_info.idl_class) {
1646 column.idlclass = '';
1647 if (idl_info.field_parent_label && idl_info.idl_parent.label != idl_info.idl_class.label) {
1648 column.idlclass = (idl_info.field_parent_label || idl_info.idl_parent.label || idl_info.idl_parent.name);
1650 column.idlclass += idl_info.idl_class.label || idl_info.idl_class.name;
1655 // finds the IDL field from the dotpath, using the columns
1656 // idlClass as the base.
1657 cols.idlFieldFromPath = function(dotpath) {
1658 var class_obj = egCore.idl.classes[cols.idlClass];
1659 if (!dotpath) return null;
1661 var path_parts = dotpath.split(/\./);
1665 for (var path_idx in path_parts) {
1666 var part = path_parts[path_idx];
1667 idl_parent = idl_field;
1668 idl_field = class_obj.field_map[part];
1671 if (idl_field['class'] && (
1672 idl_field.datatype == 'link' ||
1673 idl_field.datatype == 'org_unit')) {
1674 class_obj = egCore.idl.classes[idl_field['class']];
1682 idl_parent: idl_parent,
1683 idl_field : idl_field,
1684 idl_class : class_obj
1690 instance : function(args) { return new ColumnsProvider(args) }
1696 * Generic data provider template class. This is basically an abstract
1697 * class factory service whose instances can be locally modified to
1698 * meet the needs of each individual grid.
1700 .factory('egGridDataProvider',
1701 ['$q','$timeout','$filter','egCore',
1702 function($q , $timeout , $filter , egCore) {
1704 function GridDataProvider(args) {
1705 var gridData = this;
1706 if (!args) args = {};
1709 gridData.get = args.get;
1710 gridData.query = args.query;
1711 gridData.idlClass = args.idlClass;
1712 gridData.columnsProvider = args.columnsProvider;
1714 // Delivers a stream of array data via promise.notify()
1715 // Useful for passing an array of data to egGrid.get()
1716 // If a count is provided, the array will be trimmed to
1717 // the range defined by count and offset
1718 gridData.arrayNotifier = function(arr, offset, count) {
1719 if (!arr || arr.length == 0) return $q.when();
1721 if (gridData.columnsProvider.clientSort
1723 && gridData.sort.length > 0
1725 var sorter_cache = [];
1726 arr.sort(function(a,b) {
1727 for (var si = 0; si < gridData.sort.length; si++) {
1728 if (!sorter_cache[si]) { // Build sort structure on first comparison, reuse thereafter
1729 var field = gridData.sort[si];
1732 if (angular.isObject(field)) {
1733 dir = Object.values(field)[0];
1734 field = Object.keys(field)[0];
1737 var path = gridData.columnsProvider.findColumn(field).path || field;
1738 var comparator = gridData.columnsProvider.findColumn(field).comparator ||
1739 function (x,y) { if (x < y) return -1; if (x > y) return 1; return 0 };
1741 sorter_cache[si] = {
1744 comparator : comparator
1748 var sc = sorter_cache[si];
1752 if (a._isfieldmapper || angular.isFunction(a[sc.field])) {
1753 try {af = a[sc.field](); bf = b[sc.field]() } catch (e) {};
1755 af = a[sc.field]; bf = b[sc.field];
1757 if (af === undefined && sc.field.indexOf('.') > -1) { // assume an object, not flat path
1758 var parts = sc.field.split('.');
1761 angular.forEach(parts, function (p) {
1763 if (af._isfieldmapper || angular.isFunction(af[p])) af = af[p]();
1767 if (bf._isfieldmapper || angular.isFunction(bf[p])) bf = bf[p]();
1773 if (af === undefined) af = null;
1774 if (bf === undefined) bf = null;
1776 if (af === null && bf !== null) return 1;
1777 if (bf === null && af !== null) return -1;
1779 if (!(bf === null && af === null)) {
1780 var partial = sc.comparator(af,bf);
1782 if (sc.dir == 'desc') {
1783 if (partial > 0) return -1;
1795 if (count) arr = arr.slice(offset, offset + count);
1796 var def = $q.defer();
1797 // promise notifications are only witnessed when delivered
1798 // after the caller has his hands on the promise object
1799 $timeout(function() {
1800 angular.forEach(arr, def.notify);
1806 // Calls the grid refresh function. Once instantiated, the
1807 // grid will replace this function with it's own refresh()
1808 gridData.refresh = function(noReset) { }
1810 if (!gridData.get) {
1811 // returns a promise whose notify() delivers items
1812 gridData.get = function(index, count) {
1813 console.error("egGridDataProvider.get() not implemented");
1817 // attempts a flat field lookup first. If the column is not
1818 // found on the top-level object, attempts a nested lookup
1819 // TODO: consider a caching layer to speed up template
1820 // rendering, particularly for nested objects?
1821 gridData.itemFieldValue = function(item, column) {
1823 if (column.name in item) {
1824 if (typeof item[column.name] == 'function') {
1825 val = item[column.name]();
1827 val = item[column.name];
1830 val = gridData.nestedItemFieldValue(item, column);
1836 // TODO: deprecate me
1837 gridData.flatItemFieldValue = function(item, column) {
1838 console.warn('gridData.flatItemFieldValue deprecated; '
1839 + 'leave provider.itemFieldValue unset');
1840 return item[column.name];
1843 // given an object and a dot-separated path to a field,
1844 // extract the value of the field. The path can refer
1845 // to function names or object attributes. If the final
1846 // value is an IDL field, run the value through its
1847 // corresponding output filter.
1848 gridData.nestedItemFieldValue = function(obj, column) {
1849 item = obj; // keep a copy around
1851 if (obj === null || obj === undefined || obj === '') return '';
1852 if (!column.path) return obj;
1855 var parts = column.path.split('.');
1857 angular.forEach(parts, function(step, idx) {
1858 // object is not fleshed to the expected extent
1859 if (typeof obj != 'object') {
1860 if (typeof obj != 'undefined' && column.flesher) {
1861 obj = column.flesher(obj, column, item);
1868 if (!obj) return '';
1870 var cls = obj.classname;
1871 if (cls && (class_obj = egCore.idl.classes[cls])) {
1872 idl_field = class_obj.field_map[step];
1873 obj = obj[step] ? obj[step]() : '';
1875 if (angular.isFunction(obj[step])) {
1883 // We found a nested IDL object which may or may not have
1884 // been configured as a top-level column. Grab the datatype.
1885 if (idl_field && !column.datatype)
1886 column.datatype = idl_field.datatype;
1888 if (obj === null || obj === undefined || obj === '') return '';
1894 instance : function(args) {
1895 return new GridDataProvider(args);
1902 // Factory service for egGridDataManager instances, which are
1903 // responsible for collecting flattened grid data.
1904 .factory('egGridFlatDataProvider',
1905 ['$q','egCore','egGridDataProvider',
1906 function($q , egCore , egGridDataProvider) {
1909 instance : function(args) {
1910 var provider = egGridDataProvider.instance(args);
1912 provider.get = function(offset, count) {
1914 // no query means no call
1915 if (!provider.query ||
1916 angular.equals(provider.query, {}))
1919 // find all of the currently visible columns
1920 var queryFields = {}
1921 angular.forEach(provider.columnsProvider.columns,
1923 // only query IDL-tracked columns
1924 if (!col.adhoc && col.name && col.path && (col.required || col.visible))
1925 queryFields[col.name] = col.path;
1929 return egCore.net.request(
1931 'open-ils.fielder.flattened_search',
1932 egCore.auth.token(), provider.idlClass,
1933 queryFields, provider.query,
1934 { sort : provider.sort,
1940 //provider.itemFieldValue = provider.flatItemFieldValue;
1947 .directive('egGridColumnDragSource', function() {
1950 require : '^egGrid',
1951 link : function(scope, element, attrs, egGridCtrl) {
1952 angular.element(element).attr('draggable', 'true');
1954 element.bind('dragstart', function(e) {
1955 egGridCtrl.dragColumn = attrs.column;
1956 egGridCtrl.dragType = attrs.dragType || 'move'; // or resize
1957 egGridCtrl.colResizeDir = 0;
1959 if (egGridCtrl.dragType == 'move') {
1960 // style the column getting moved
1961 angular.element(e.target).addClass(
1962 'eg-grid-column-move-handle-active');
1966 element.bind('dragend', function(e) {
1967 if (egGridCtrl.dragType == 'move') {
1968 angular.element(e.target).removeClass(
1969 'eg-grid-column-move-handle-active');
1976 .directive('egGridColumnDragDest', function() {
1979 require : '^egGrid',
1980 link : function(scope, element, attrs, egGridCtrl) {
1982 element.bind('dragover', function(e) { // required for drop
1983 e.stopPropagation();
1985 e.dataTransfer.dropEffect = 'move';
1987 if (egGridCtrl.colResizeDir == 0) return; // move
1989 var cols = egGridCtrl.columnsProvider;
1990 var srcCol = egGridCtrl.dragColumn;
1991 var srcColIdx = cols.indexOf(srcCol);
1993 if (egGridCtrl.colResizeDir == -1) {
1994 if (cols.indexOf(attrs.column) <= srcColIdx) {
1995 egGridCtrl.modifyColumnFlex(
1996 egGridCtrl.columnsProvider.findColumn(
1997 egGridCtrl.dragColumn), -1);
1998 if (cols.columns[srcColIdx+1]) {
1999 // source column shrinks by one, column to the
2000 // right grows by one.
2001 egGridCtrl.modifyColumnFlex(
2002 cols.columns[srcColIdx+1], 1);
2007 if (cols.indexOf(attrs.column) > srcColIdx) {
2008 egGridCtrl.modifyColumnFlex(
2009 egGridCtrl.columnsProvider.findColumn(
2010 egGridCtrl.dragColumn), 1);
2011 if (cols.columns[srcColIdx+1]) {
2012 // source column grows by one, column to the
2013 // right grows by one.
2014 egGridCtrl.modifyColumnFlex(
2015 cols.columns[srcColIdx+1], -1);
2023 element.bind('dragenter', function(e) {
2024 e.stopPropagation();
2026 if (egGridCtrl.dragType == 'move') {
2027 angular.element(e.target).addClass('eg-grid-col-hover');
2029 // resize grips are on the right side of each column.
2030 // dragenter will either occur on the source column
2031 // (dragging left) or the column to the right.
2032 if (egGridCtrl.colResizeDir == 0) {
2033 if (egGridCtrl.dragColumn == attrs.column) {
2034 egGridCtrl.colResizeDir = -1; // west
2036 egGridCtrl.colResizeDir = 1; // east
2042 element.bind('dragleave', function(e) {
2043 e.stopPropagation();
2045 if (egGridCtrl.dragType == 'move') {
2046 angular.element(e.target).removeClass('eg-grid-col-hover');
2050 element.bind('drop', function(e) {
2051 e.stopPropagation();
2053 egGridCtrl.colResizeDir = 0;
2054 if (egGridCtrl.dragType == 'move') {
2055 angular.element(e.target).removeClass('eg-grid-col-hover');
2056 egGridCtrl.onColumnDrop(attrs.column); // move the column
2063 .directive('egGridMenuItem', function() {
2066 require : '^egGrid',
2072 handler : '=', // onclick handler function
2073 divider : '=', // if true, show a divider only
2074 handlerData : '=', // if set, passed as second argument to handler
2075 disabled : '=', // function
2076 hidden : '=' // function
2078 link : function(scope, element, attrs, egGridCtrl) {
2079 egGridCtrl.addMenuItem({
2080 checkbox : scope.checkbox,
2081 checked : scope.checked ? true : false,
2082 label : scope.label,
2083 standalone : scope.standalone ? true : false,
2084 handler : scope.handler,
2085 divider : scope.divider,
2086 disabled : scope.disabled,
2087 hidden : scope.hidden,
2088 handlerData : scope.handlerData
2095 /* https://stackoverflow.com/questions/17343696/adding-an-ng-click-event-inside-a-filter/17344875#17344875 */
2096 .directive('compile', ['$compile', function ($compile) {
2097 return function(scope, element, attrs) {
2098 // pass through column defs from grid cell's scope
2099 scope.col = scope.$parent.col;
2102 // watch the 'compile' expression for changes
2103 return scope.$eval(attrs.compile);
2106 // when the 'compile' expression changes
2107 // assign it into the current DOM
2108 element.html(value);
2110 // compile the new DOM and link it to the current
2112 // NOTE: we only compile .childNodes so that
2113 // we don't get into infinite loop compiling ourselves
2114 $compile(element.contents())(scope);
2123 * Translates bare IDL object values into display values.
2124 * 1. Passes dates through the angular date filter
2125 * 2. Translates bools to Booleans so the browser can display translated
2126 * value. (Though we could manually translate instead..)
2127 * Others likely to follow...
2129 .filter('egGridValueFilter', ['$filter','egCore', function($filter,egCore) {
2130 function traversePath(obj,path) {
2131 var list = path.split('.');
2132 for (var part in path) {
2133 if (obj[path]) obj = obj[path]
2139 var GVF = function(value, column, item) {
2140 switch(column.datatype) {
2143 // Browser will translate true/false for us
2145 case '1' : // legacy
2149 case '0' : // legacy
2152 // value may be null, '', etc.
2153 default : return '';
2156 var interval = angular.isFunction(item[column.dateonlyinterval])
2157 ? item[column.dateonlyinterval]()
2158 : item[column.dateonlyinterval];
2160 if (column.dateonlyinterval && !interval) // try it as a dotted path
2161 interval = traversePath(item, column.dateonlyinterval);
2163 var context = angular.isFunction(item[column.datecontext])
2164 ? item[column.datecontext]()
2165 : item[column.datecontext];
2167 if (column.datecontext && !context) // try it as a dotted path
2168 context = traversePath(item, column.datecontext);
2170 var date_filter = column.datefilter || 'egOrgDateInContext';
2172 return $filter(date_filter)(value, column.dateformat, context, interval);
2174 return $filter('currency')(value);
2180 GVF.$stateful = true;