1 angular.module('egGridMod',
2 ['egCoreMod', 'egUiMod', 'ui.bootstrap'])
4 .directive('egGrid', function() {
10 // IDL class hint (e.g. "aou")
16 // if true, grid columns are derived from all non-virtual
17 // fields on the base idlClass
20 // grid preferences will be stored / retrieved with this key
23 // field whose value is unique and may be used for item
24 // reference / lookup. This will usually be someting like
25 // "id". This is not needed when using autoFields, since we
26 // can determine the primary key directly from the IDL.
29 // Reference to externally provided egGridDataProvider
32 // Reference to externally provided item-selection handler
35 // Reference to externally provided after-item-selection handler
38 // comma-separated list of supported or disabled grid features
39 // supported features:
40 // startSelected : init the grid with all rows selected by default
41 // allowAll : add an "All" option to row count (really 10000)
42 // -menu : don't show any menu buttons (or use space for them)
43 // -picker : don't show the column picker
44 // -pagination : don't show any pagination elements, and set
46 // -actions : don't show the actions dropdown
47 // -index : don't show the row index column (can't use "index"
48 // as the idField in this case)
49 // -display : columns are hidden by default
50 // -sort : columns are unsortable by default
51 // -multisort : sort priorities config disabled by default
52 // -multiselect : only one row at a time can be selected;
53 // choosing this also disables the checkbox
57 // optional: object containing function to conditionally apply
61 // optional: object that enables status icon field and contains
62 // function to handle what status icons should exist and why.
65 // optional primary grid label
68 // if true, use the IDL class label as the mainLabel
71 // optional context menu label
74 dateformat : '@', // optional: passed down to egGridValueFilter
75 datecontext: '@', // optional: passed down to egGridValueFilter to choose TZ
76 datefilter: '@', // optional: passed down to egGridValueFilter to choose specialized date filters
77 dateonlyinterval: '@', // optional: passed down to egGridValueFilter to choose a "better" format
79 // Hash of control functions.
81 // These functions are defined by the calling scope and
82 // invoked as-is by the grid w/ the specified parameters.
84 // collectStarted : function() {}
85 // itemRetrieved : function(item) {}
86 // allItemsRetrieved : function() {}
89 // If defined, the grid will watch the return value from
90 // the function defined at watchQuery on each digest and
91 // re-draw the grid when query changes occur.
93 // watchQuery : function() { /* return grid query */ }
96 // These functions are defined by the grid and thus
97 // replace any values defined for these attributes from the
100 // activateItem : function(item) {}
101 // allItems : function(allItems) {}
102 // selectedItems : function(selected) {}
103 // selectItems : function(ids) {}
104 // setQuery : function(queryStruct) {} // causes reload
105 // setSort : function(sortSturct) {} // causes reload
109 // TODO: avoid hard-coded url
110 templateUrl : '/eg/staff/share/t_autogrid',
112 link : function(scope, element, attrs) {
113 // link() is called after page compilation, which means our
114 // eg-grid-field's have been parsed and loaded. Now it's
115 // safe to perform our initial page load.
117 // load auto fields after eg-grid-field's so they are not clobbered
118 scope.handleAutoFields();
121 var statusCell = scope.statusCell;
122 var rowClass = scope.rowClass;
124 scope.grid_element = element;
126 .find('.eg-grid-content-body')
127 .bind('contextmenu', scope.showActionContextMenu);
131 '$scope','$q','egCore','egGridFlatDataProvider','$location',
132 'egGridColumnsProvider','$filter','$window','$sce','$timeout',
133 'egProgressDialog','$uibModal',
134 function($scope, $q , egCore, egGridFlatDataProvider , $location,
135 egGridColumnsProvider , $filter , $window , $sce , $timeout,
136 egProgressDialog , $uibModal) {
140 grid.init = function() {
143 $scope.showGridConf = false;
144 grid.totalCount = -1;
145 $scope.selected = {};
146 $scope.actionGroups = [{actions:[]}]; // Grouped actions for selected items
147 $scope.menuItems = []; // global actions
149 // returns true if any rows are selected.
150 $scope.hasSelected = function() {
151 return grid.getSelectedItems().length > 0 };
153 var features = ($scope.features) ?
154 $scope.features.split(',') : [];
155 delete $scope.features;
157 $scope.showIndex = (features.indexOf('-index') == -1);
159 $scope.allowAll = (features.indexOf('allowAll') > -1);
160 $scope.startSelected = $scope.selectAll = (features.indexOf('startSelected') > -1);
161 $scope.showActions = (features.indexOf('-actions') == -1);
162 $scope.showPagination = (features.indexOf('-pagination') == -1);
163 $scope.showPicker = (features.indexOf('-picker') == -1);
165 $scope.showMenu = (features.indexOf('-menu') == -1);
167 // remove some unneeded values from the scope to reduce bloat
169 grid.idlClass = $scope.idlClass;
170 delete $scope.idlClass;
172 grid.persistKey = $scope.persistKey;
173 delete $scope.persistKey;
175 var stored_limit = 0;
176 if ($scope.showPagination) {
177 if (grid.persistKey) {
178 var stored_limit = Number(
179 egCore.hatch.getLocalItem('eg.grid.' + grid.persistKey + '.limit')
183 stored_limit = 10000; // maybe support "Inf"?
186 grid.limit = Number(stored_limit) || Number($scope.pageSize) || 25;
188 grid.indexField = $scope.idField;
189 delete $scope.idField;
191 grid.dataProvider = $scope.itemsProvider;
193 if (!grid.indexField && grid.idlClass)
194 grid.indexField = egCore.idl.classes[grid.idlClass].pkey;
196 grid.columnsProvider = egGridColumnsProvider.instance({
197 idlClass : grid.idlClass,
198 clientSort : (features.indexOf('clientsort') > -1 && features.indexOf('-clientsort') == -1),
199 defaultToHidden : (features.indexOf('-display') > -1),
200 defaultToNoSort : (features.indexOf('-sort') > -1),
201 defaultToNoMultiSort : (features.indexOf('-multisort') > -1),
202 defaultDateFormat : $scope.dateformat,
203 defaultDateContext : $scope.datecontext,
204 defaultDateFilter : $scope.datefilter,
205 defaultDateOnlyInterval : $scope.dateonlyinterval
207 $scope.canMultiSelect = (features.indexOf('-multiselect') == -1);
209 $scope.handleAutoFields = function() {
210 if ($scope.autoFields) {
211 if (grid.autoLabel) {
213 egCore.idl.classes[grid.idlClass].label;
215 grid.columnsProvider.compileAutoColumns();
216 delete $scope.autoFields;
220 if (!grid.dataProvider) {
221 // no provider, um, provided.
222 // Use a flat data provider
224 grid.selfManagedData = true;
225 grid.dataProvider = egGridFlatDataProvider.instance({
226 indexField : grid.indexField,
227 idlClass : grid.idlClass,
228 columnsProvider : grid.columnsProvider,
233 // make grid ref available in get() to set totalCount, if known.
234 // this allows us disable the 'next' paging button correctly
235 grid.dataProvider.grid = grid;
237 grid.dataProvider.columnsProvider = grid.columnsProvider;
239 $scope.itemFieldValue = grid.dataProvider.itemFieldValue;
240 $scope.indexValue = function(item) {
241 return grid.indexValue(item)
244 grid.applyControlFunctions();
246 grid.loadConfig().then(function() {
247 // link columns to scope after loadConfig(), since it
248 // replaces the columns array.
249 $scope.columns = grid.columnsProvider.columns;
252 // NOTE: grid.collect() is first called from link(), not here.
255 // link our control functions into the gridControls
256 // scope object so the caller can access them.
257 grid.applyControlFunctions = function() {
259 // we use some of these controls internally, so sett
260 // them up even if the caller doesn't request them.
261 var controls = $scope.gridControls || {};
263 controls.columnMap = function() {
265 angular.forEach(grid.columnsProvider.columns, function (c) {
271 controls.columnsProvider = function() {
272 return grid.columnsProvider;
275 // link in the control functions
276 controls.selectedItems = function() {
277 return grid.getSelectedItems()
280 controls.allItems = function() {
284 controls.selectItems = function(ids) {
286 $scope.selected = {};
287 angular.forEach(ids, function(i) {
288 $scope.selected[''+i] = true;
292 // if the caller provided a functional setQuery,
293 // extract the value before replacing it
294 if (controls.setQuery) {
295 grid.dataProvider.query =
299 controls.setQuery = function(query) {
300 grid.dataProvider.query = query;
304 if (controls.watchQuery) {
305 // capture the initial query value
306 grid.dataProvider.query = controls.watchQuery();
309 $scope.gridWatchQuery = controls.watchQuery;
310 $scope.$watch('gridWatchQuery()', function(newv) {
311 controls.setQuery(newv);
315 // if the caller provided a functional setSort
316 // extract the value before replacing it
317 grid.dataProvider.sort =
318 controls.setSort ? controls.setSort() : [];
320 controls.setSort = function(sort) {
324 controls.refresh = function(noReset) {
325 if (!noReset) grid.offset = 0;
329 controls.setLimit = function(limit,forget) {
330 if (!forget && grid.persistKey)
331 egCore.hatch.setLocalItem('eg.grid.' + grid.persistKey + '.limit', limit);
334 controls.getLimit = function() {
337 controls.setOffset = function(offset) {
338 grid.offset = offset;
340 controls.getOffset = function() {
344 controls.saveConfig = function () {
345 return $scope.saveConfig();
348 grid.dataProvider.refresh = controls.refresh;
349 grid.controls = controls;
352 // If a menu item provides its own HTML template, translate it,
353 // using the menu item for the template scope.
354 // note: $sce is required to avoid security restrictions and
355 // is OK here, since the template comes directly from a
356 // local HTML template (not user input).
357 $scope.translateMenuItemTemplate = function(item) {
358 var html = egCore.strings.$replace(item.template, {item : item});
359 return $sce.trustAsHtml(html);
362 // add a new (global) grid menu item
363 grid.addMenuItem = function(item) {
364 $scope.menuItems.push(item);
365 var handler = item.handler;
366 item.handler = function() {
367 $scope.gridMenuIsOpen = false; // close menu
370 item.handlerData, grid.getSelectedItems());
375 // add a selected-items action
376 grid.addAction = function(act) {
378 $scope.actionGroups.forEach(function(g){
379 if (g.label === act.group) {
385 $scope.actionGroups.push({
392 // remove the stored column configuration preferenc, then recover
393 // the column visibility information from the initial page load.
394 $scope.resetColumns = function() {
395 $scope.gridColumnPickerIsOpen = false;
396 egCore.hatch.removeItem('eg.grid.' + grid.persistKey)
398 grid.columnsProvider.reset();
399 if (grid.selfManagedData) grid.collect();
403 $scope.showAllColumns = function() {
404 $scope.gridColumnPickerIsOpen = false;
405 grid.columnsProvider.showAllColumns();
406 if (grid.selfManagedData) grid.collect();
409 $scope.hideAllColumns = function() {
410 $scope.gridColumnPickerIsOpen = false;
411 grid.columnsProvider.hideAllColumns();
412 // note: no need to fetch new data if no columns are visible
415 $scope.toggleColumnVisibility = function(col) {
416 $scope.gridColumnPickerIsOpen = false;
417 col.visible = !col.visible;
419 // egGridFlatDataProvider only retrieves data to be
420 // displayed. When column visibility changes, it's
421 // necessary to fetch the newly visible column data.
422 if (grid.selfManagedData) grid.collect();
425 // save the columns configuration (position, sort, width) to
426 // eg.grid.<persist-key>
427 $scope.saveConfig = function() {
428 $scope.gridColumnPickerIsOpen = false;
430 if (!grid.persistKey) {
432 "Cannot save settings without a grid persist-key");
436 // only store information about visible columns.
437 var conf = grid.columnsProvider.columns.filter(
438 function(col) {return Boolean(col.visible) });
440 // now scrunch the data down to just the needed info
441 conf = conf.map(function(col) {
442 var c = {name : col.name}
443 // Apart from the name, only store non-default values.
444 // No need to store col.visible, since that's implicit
445 if (col.align != 'left') c.align = col.align;
446 if (col.flex != 2) c.flex = col.flex;
447 if (Number(col.sort)) c.sort = Number(c.sort);
451 egCore.hatch.setItem('eg.grid.' + grid.persistKey, conf)
453 // Save operation performed from the grid configuration UI.
454 // Hide the configuration UI and re-draw w/ sort applied
455 if ($scope.showGridConf)
456 $scope.toggleConfDisplay();
461 // load the columns configuration (position, sort, width) from
462 // eg.grid.<persist-key> and apply the loaded settings to the
463 // columns on our columnsProvider
464 grid.loadConfig = function() {
465 if (!grid.persistKey) return $q.when();
467 return egCore.hatch.getItem('eg.grid.' + grid.persistKey)
468 .then(function(conf) {
471 var columns = grid.columnsProvider.columns;
474 angular.forEach(conf, function(col) {
475 var grid_col = columns.filter(
476 function(c) {return c.name == col.name})[0];
479 // saved column does not match a column in the
480 // current grid. skip it.
484 grid_col.align = col.align || 'left';
485 grid_col.flex = col.flex || 2;
486 grid_col.sort = col.sort || 0;
487 // all saved columns are assumed to be true
488 grid_col.visible = true;
490 .filter(function (c) {
491 return c.name == grid_col.name;
494 new_cols.push(grid_col);
497 // columns which are not expressed within the saved
498 // configuration are marked as non-visible and
499 // appended to the end of the new list of columns.
500 angular.forEach(columns, function(col) {
501 var found = conf.filter(
502 function(c) {return (c.name == col.name)})[0];
509 grid.columnsProvider.columns = new_cols;
515 $scope.onContextMenu = function($event) {
516 var col = angular.element($event.target).attr('column');
517 console.log('selected column ' + col);
520 $scope.page = function() {
521 return (grid.offset / grid.limit) + 1;
524 $scope.goToPage = function(page) {
526 if (angular.isNumber(page) && page > 0) {
527 grid.offset = (page - 1) * grid.limit;
532 $scope.offset = function(o) {
533 if (angular.isNumber(o))
538 $scope.limit = function(l) {
539 if (angular.isNumber(l)) {
541 egCore.hatch.setLocalItem('eg.grid.' + grid.persistKey + '.limit', l);
547 $scope.onFirstPage = function() {
548 return grid.offset == 0;
551 $scope.hasNextPage = function() {
552 // we have less data than requested, there must
553 // not be any more pages
554 if (grid.count() < grid.limit) return false;
556 // if the total count is not known, assume that a full
557 // page of data implies more pages are available.
558 if (grid.totalCount == -1) return true;
560 // we have a full page of data, but is there more?
561 return grid.totalCount > (grid.offset + grid.count());
564 $scope.incrementPage = function() {
565 grid.offset += grid.limit;
569 $scope.decrementPage = function() {
570 if (grid.offset < grid.limit) {
573 grid.offset -= grid.limit;
578 // number of items loaded for the current page of results
579 grid.count = function() {
580 return $scope.items.length;
583 // returns the unique identifier value for the provided item
584 // for internal consistency, indexValue is always coerced
586 grid.indexValue = function(item) {
587 if (angular.isObject(item)) {
589 if (angular.isFunction(item[grid.indexField]))
590 return ''+item[grid.indexField]();
591 return ''+item[grid.indexField]; // flat data
594 // passed a non-object; assume it's an index
598 // fires the hide handler function for a context action
599 $scope.actionHide = function(action) {
600 if (typeof action.hide == 'undefined') {
603 if (angular.isFunction(action.hide))
604 return action.hide(action);
608 // fires the disable handler function for a context action
609 $scope.actionDisable = function(action) {
610 if (typeof action.disabled == 'undefined') {
613 if (angular.isFunction(action.disabled))
614 return action.disabled(action);
615 return action.disabled;
618 // fires the action handler function for a context action
619 $scope.actionLauncher = function(action) {
620 if (!action.handler) {
622 'No handler specified for "' + action.label + '"');
626 action.handler(grid.getSelectedItems());
628 console.error('Error executing handler for "'
629 + action.label + '" => ' + E + "\n" + E.stack);
632 if ($scope.action_context_showing) $scope.hideActionContextMenu();
637 $scope.hideActionContextMenu = function () {
638 $($scope.menu_dom).css({
640 width: $scope.action_context_width,
641 top: $scope.action_context_y,
642 left: $scope.action_context_x
644 $($scope.action_context_parent).append($scope.menu_dom);
645 $scope.action_context_oldy = $scope.action_context_oldx = 0;
646 $('body').unbind('click.remove_context_menu_'+$scope.action_context_index);
647 $scope.action_context_showing = false;
650 $scope.action_context_showing = false;
651 $scope.showActionContextMenu = function ($event) {
653 // Have to gather these here, instead of inside link()
654 if (!$scope.menu_dom) $scope.menu_dom = $($scope.grid_element).find('.grid-action-dropdown')[0];
655 if (!$scope.action_context_parent) $scope.action_context_parent = $($scope.menu_dom).parent();
657 if (!grid.getSelectedItems().length) // Nothing selected, fire the click event
658 $event.target.click();
660 if (!$scope.action_context_showing) {
661 $scope.action_context_width = $($scope.menu_dom).css('width');
662 $scope.action_context_y = $($scope.menu_dom).css('top');
663 $scope.action_context_x = $($scope.menu_dom).css('left');
664 $scope.action_context_showing = true;
665 $scope.action_context_index = Math.floor((Math.random() * 1000) + 1);
667 $('body').append($($scope.menu_dom));
668 $('body').bind('click.remove_context_menu_'+$scope.action_context_index, $scope.hideActionContextMenu);
671 $($scope.menu_dom).css({
673 width: $scope.action_context_width,
681 // returns the list of selected item objects
682 grid.getSelectedItems = function() {
683 return $scope.items.filter(
685 return Boolean($scope.selected[grid.indexValue(item)]);
690 grid.getItemByIndex = function(index) {
691 for (var i = 0; i < $scope.items.length; i++) {
692 var item = $scope.items[i];
693 if (grid.indexValue(item) == index)
698 // selects one row after deselecting all of the others
699 grid.selectOneItem = function(index) {
700 $scope.selected = {};
701 $scope.selected[index] = true;
704 // selects or deselects an item, without affecting the others.
705 // returns true if the item is selected; false if de-selected.
706 // we overwrite the object so that we can watch $scope.selected
707 grid.toggleSelectOneItem = function(index) {
708 if ($scope.selected[index]) {
709 delete $scope.selected[index];
710 $scope.selected = angular.copy($scope.selected);
713 $scope.selected[index] = true;
714 $scope.selected = angular.copy($scope.selected);
719 $scope.updateSelected = function () {
720 return $scope.selected = angular.copy($scope.selected);
723 grid.selectAllItems = function() {
724 angular.forEach($scope.items, function(item) {
725 $scope.selected[grid.indexValue(item)] = true
727 $scope.selected = angular.copy($scope.selected);
730 $scope.$watch('selectAll', function(newVal) {
732 grid.selectAllItems();
734 $scope.selected = {};
738 if ($scope.onSelect) {
739 $scope.$watch('selected', function(newVal) {
740 $scope.onSelect(grid.getSelectedItems());
741 if ($scope.afterSelect) $scope.afterSelect();
745 // returns true if item1 appears in the list before item2;
746 // false otherwise. this is slightly more efficient that
747 // finding the position of each then comparing them.
748 // item1 / item2 may be an item or an item index
749 grid.itemComesBefore = function(itemOrIndex1, itemOrIndex2) {
750 var idx1 = grid.indexValue(itemOrIndex1);
751 var idx2 = grid.indexValue(itemOrIndex2);
753 // use for() for early exit
754 for (var i = 0; i < $scope.items.length; i++) {
755 var idx = grid.indexValue($scope.items[i]);
756 if (idx == idx1) return true;
757 if (idx == idx2) return false;
762 // 0-based position of item in the current data set
763 grid.indexOf = function(item) {
764 var idx = grid.indexValue(item);
765 for (var i = 0; i < $scope.items.length; i++) {
766 if (grid.indexValue($scope.items[i]) == idx)
772 grid.modifyColumnFlex = function(column, val) {
774 // prevent flex:0; use hiding instead
778 $scope.modifyColumnFlex = function(col, val) {
779 $scope.lastModColumn = col;
780 grid.modifyColumnFlex(col, val);
783 $scope.isLastModifiedColumn = function(col) {
784 if ($scope.lastModColumn)
785 return $scope.lastModColumn === col;
789 grid.modifyColumnPos = function(col, diff) {
790 var srcIdx, targetIdx;
791 angular.forEach(grid.columnsProvider.columns,
792 function(c, i) { if (c.name == col.name) srcIdx = i });
794 targetIdx = srcIdx + diff;
797 } else if (targetIdx >= grid.columnsProvider.columns.length) {
798 // Target index follows the last visible column.
800 angular.forEach(grid.columnsProvider.columns,
801 function(column, idx) {
802 if (column.visible) lastVisible = idx;
806 // When moving a column (down) causes one or more
807 // visible columns to shuffle forward, our column
808 // moves into the slot of the last visible column.
809 // Otherwise, put it into the slot directly following
810 // the last visible column.
812 srcIdx <= lastVisible ? lastVisible : lastVisible + 1;
815 // Splice column out of old position, insert at new position.
816 grid.columnsProvider.columns.splice(srcIdx, 1);
817 grid.columnsProvider.columns.splice(targetIdx, 0, col);
820 $scope.modifyColumnPos = function(col, diff) {
821 $scope.lastModColumn = col;
822 return grid.modifyColumnPos(col, diff);
826 // handles click, control-click, and shift-click
827 $scope.handleRowClick = function($event, item) {
828 var index = grid.indexValue(item);
830 var origSelected = Object.keys($scope.selected);
832 if (!$scope.canMultiSelect) {
833 grid.selectOneItem(index);
834 grid.lastSelectedItemIndex = index;
838 if ($event.ctrlKey || $event.metaKey /* mac command */) {
840 if (grid.toggleSelectOneItem(index))
841 grid.lastSelectedItemIndex = index;
843 } else if ($event.shiftKey) {
846 if (!grid.lastSelectedItemIndex ||
847 index == grid.lastSelectedItemIndex) {
848 grid.selectOneItem(index);
849 grid.lastSelectedItemIndex = index;
853 var selecting = false;
854 var ascending = grid.itemComesBefore(
855 grid.lastSelectedItemIndex, item);
857 grid.indexOf(grid.lastSelectedItemIndex);
859 // update to new last-selected
860 grid.lastSelectedItemIndex = index;
862 // select each row between the last selected and
863 // currently selected items
865 startPos += ascending ? 1 : -1;
866 var curItem = $scope.items[startPos];
868 var curIdx = grid.indexValue(curItem);
869 $scope.selected[curIdx] = true;
870 if (curIdx == index) break; // all done
872 $scope.selected = angular.copy($scope.selected);
876 grid.selectOneItem(index);
877 grid.lastSelectedItemIndex = index;
881 // Builds a sort expression from column sort priorities.
882 // called on page load and any time the priorities are modified.
883 grid.compileSort = function() {
884 var sortList = grid.columnsProvider.columns.filter(
885 function(col) { return Number(col.sort) != 0 }
888 if (Math.abs(a.sort) < Math.abs(b.sort))
894 if (sortList.length) {
895 grid.dataProvider.sort = sortList.map(function(col) {
897 blob[col.name] = col.sort < 0 ? 'desc' : 'asc';
903 // builds a sort expression using a single column,
904 // toggling between ascending and descending sort.
905 $scope.quickSort = function(col_name) {
906 var sort = grid.dataProvider.sort;
907 if (sort && sort.length &&
908 sort[0] == col_name) {
910 blob[col_name] = 'desc';
911 grid.dataProvider.sort = [blob];
913 grid.dataProvider.sort = [col_name];
920 // show / hide the grid configuration row
921 $scope.toggleConfDisplay = function() {
922 if ($scope.showGridConf) {
923 $scope.showGridConf = false;
924 if (grid.columnsProvider.hasSortableColumn()) {
925 // only refresh the grid if the user has the
926 // ability to modify the sort priorities.
932 $scope.showGridConf = true;
935 delete $scope.lastModColumn;
936 $scope.gridColumnPickerIsOpen = false;
939 // called when a dragged column is dropped onto itself
940 // or any other column
941 grid.onColumnDrop = function(target) {
942 if (angular.isUndefined(target)) return;
943 if (target == grid.dragColumn) return;
944 var srcIdx, targetIdx, srcCol;
945 angular.forEach(grid.columnsProvider.columns,
947 if (col.name == grid.dragColumn) {
950 } else if (col.name == target) {
956 if (srcIdx < targetIdx) targetIdx--;
958 // move src column from old location to new location in
959 // the columns array, then force a page refresh
960 grid.columnsProvider.columns.splice(srcIdx, 1);
961 grid.columnsProvider.columns.splice(targetIdx, 0, srcCol);
965 // prepares a string for inclusion within a CSV document
966 // by escaping commas and quotes and removing newlines.
967 grid.csvDatum = function(str) {
970 str = str.replace(/\n/g, '');
971 if (str.match(/\,/) || str.match(/"/)) {
972 str = str.replace(/"/g, '""');
973 str = '"' + str + '"';
978 /** Export the full data set as CSV.
980 * 1. User clicks the 'download csv' link
981 * 2. All grid data is retrieved asychronously
982 * 3. Once all data is all present and CSV-ized, the download
983 * attributes are linked to the href.
984 * 4. The href .click() action is prgrammatically fired again,
985 * telling the browser to download the data, now that the
986 * data is available for download.
987 * 5 Once downloaded, the href attributes are reset.
989 grid.csvExportInProgress = false;
990 $scope.generateCSVExportURL = function($event) {
992 if (grid.csvExportInProgress) {
993 // This is secondary href click handler. Give the
994 // browser a moment to start the download, then reset
995 // the CSV download attributes / state.
998 $scope.csvExportURL = '';
999 $scope.csvExportFileName = '';
1000 grid.csvExportInProgress = false;
1006 grid.csvExportInProgress = true;
1007 $scope.gridColumnPickerIsOpen = false;
1009 // let the file name describe the grid
1010 $scope.csvExportFileName =
1011 ($scope.mainLabel || grid.persistKey || 'eg_grid_data')
1012 .replace(/\s+/g, '_') + '_' + $scope.page();
1014 // toss the CSV into a Blob and update the export URL
1015 grid.generateCSV().then(function(csv) {
1016 var blob = new Blob([csv], {type : 'text/plain'});
1017 $scope.csvExportURL =
1018 ($window.URL || $window.webkitURL).createObjectURL(blob);
1020 // Fire the 2nd click event now that the browser has
1021 // information on how to download the CSV file.
1022 $timeout(function() {$event.target.click()});
1027 * TODO: does this serve any purpose given we can
1028 * print formatted HTML? If so, generateCSV() now
1029 * returns a promise, needs light refactoring...
1030 $scope.printCSV = function() {
1031 $scope.gridColumnPickerIsOpen = false;
1032 egCore.print.print({
1033 context : 'default',
1034 content : grid.generateCSV(),
1035 content_type : 'text/plain'
1040 // Given a row item and column definition, extract the
1041 // text content for printing. Templated columns must be
1042 // processed and parsed as HTML, then boiled down to their
1044 grid.getItemTextContent = function(item, col) {
1047 val = $scope.translateCellTemplate(col, item);
1049 var node = new DOMParser()
1050 .parseFromString(val, 'text/html');
1051 val = $(node).text();
1054 val = grid.dataProvider.itemFieldValue(item, col);
1055 val = $filter('egGridValueFilter')(val, col, item);
1061 * Fetches all grid data and transates each item into a simple
1062 * key-value pair of column name => text-value.
1063 * Included in the response for convenience is the list of
1064 * currently visible column definitions.
1065 * TODO: currently fetches a maximum of 10k rows. Does this
1066 * need to be configurable?
1068 grid.getAllItemsAsText = function() {
1069 var text_items = [];
1071 // we don't know the total number of rows we're about
1072 // to retrieve, but we can indicate the number retrieved
1073 // so far as each item arrives.
1074 egProgressDialog.open({value : 0});
1076 var visible_cols = grid.columnsProvider.columns.filter(
1077 function(c) { return c.visible });
1079 return grid.dataProvider.get(0, 10000).then(
1081 return {items : text_items, columns : visible_cols};
1085 egProgressDialog.increment();
1087 angular.forEach(visible_cols, function(col) {
1088 text_item[col.name] =
1089 grid.getItemTextContent(item, col);
1091 text_items.push(text_item);
1093 ).finally(egProgressDialog.close);
1096 // Fetch "all" of the grid data, translate it into print-friendly
1097 // text, and send it to the printer service.
1098 $scope.printHTML = function() {
1099 $scope.gridColumnPickerIsOpen = false;
1100 return grid.getAllItemsAsText().then(function(text_items) {
1101 return egCore.print.print({
1102 template : 'grid_html',
1108 $scope.showColumnDialog = function() {
1109 return $uibModal.open({
1110 templateUrl: './share/t_grid_columns',
1113 controller: ['$scope', '$uibModalInstance',
1114 function($dialogScope, $uibModalInstance) {
1115 $dialogScope.modifyColumnPos = $scope.modifyColumnPos;
1116 $dialogScope.disableMultiSort = $scope.disableMultiSort;
1117 $dialogScope.columns = $scope.columns;
1119 // Push visible columns to the top of the list
1120 $dialogScope.elevateVisible = function() {
1122 angular.forEach($dialogScope.columns, function(col) {
1123 if (col.visible) new_cols.push(col);
1125 angular.forEach($dialogScope.columns, function(col) {
1126 if (!col.visible) new_cols.push(col);
1129 // Update all references to the list of columns
1130 $dialogScope.columns =
1132 grid.columnsProvider.columns =
1136 $dialogScope.toggle = function(col) {
1137 col.visible = !Boolean(col.visible);
1139 $dialogScope.ok = $dialogScope.cancel = function() {
1140 delete $scope.lastModColumn;
1141 $uibModalInstance.close()
1148 // generates CSV for the currently visible grid contents
1149 grid.generateCSV = function() {
1150 return grid.getAllItemsAsText().then(function(text_items) {
1151 var columns = text_items.columns;
1152 var items = text_items.items;
1156 angular.forEach(columns, function(col) {
1157 csvStr += grid.csvDatum(col.label);
1161 csvStr = csvStr.replace(/,$/,'\n');
1164 angular.forEach(items, function(item) {
1165 angular.forEach(columns, function(col) {
1166 csvStr += grid.csvDatum(item[col.name]);
1169 csvStr = csvStr.replace(/,$/,'\n');
1176 // Interpolate the value for column.linkpath within the context
1177 // of the row item to generate the final link URL.
1178 $scope.generateLinkPath = function(col, item) {
1179 return egCore.strings.$replace(col.linkpath, {item : item});
1182 // If a column provides its own HTML template, translate it,
1183 // using the current item for the template scope.
1184 // note: $sce is required to avoid security restrictions and
1185 // is OK here, since the template comes directly from a
1186 // local HTML template (not user input).
1187 $scope.translateCellTemplate = function(col, item) {
1188 var html = egCore.strings.$replace(col.template, {item : item});
1189 return $sce.trustAsHtml(html);
1192 $scope.collect = function() { grid.collect() }
1194 // asks the dataProvider for a page of data
1195 grid.collect = function() {
1197 // avoid firing the collect if there is nothing to collect.
1198 if (grid.selfManagedData && !grid.dataProvider.query) return;
1200 if (grid.collecting) return; // avoid parallel collect()
1201 grid.collecting = true;
1203 console.debug('egGrid.collect() offset='
1204 + grid.offset + '; limit=' + grid.limit);
1206 // ensure all of our dropdowns are closed
1207 // TODO: git rid of these and just use dropdown-toggle,
1208 // which is more reliable.
1209 $scope.gridColumnPickerIsOpen = false;
1210 $scope.gridRowCountIsOpen = false;
1211 $scope.gridPageSelectIsOpen = false;
1214 $scope.selected = {};
1216 // Inform the caller we've asked the data provider
1217 // for data. This is useful for knowing when collection
1218 // has started (e.g. to display a progress dialg) when
1219 // using the stock (flattener) data provider, where the
1220 // user is not directly defining a get() handler.
1221 if (grid.controls.collectStarted)
1222 grid.controls.collectStarted(grid.offset, grid.limit);
1224 grid.dataProvider.get(grid.offset, grid.limit).then(
1226 if (grid.controls.allItemsRetrieved)
1227 grid.controls.allItemsRetrieved();
1232 $scope.items.push(item)
1233 if (grid.controls.itemRetrieved)
1234 grid.controls.itemRetrieved(item);
1235 if ($scope.selectAll)
1236 $scope.selected[grid.indexValue(item)] = true
1238 }).finally(function() {
1239 console.debug('egGrid.collect() complete');
1240 grid.collecting = false
1241 $scope.selected = angular.copy($scope.selected);
1251 * eg-grid-field : used for collecting custom field data from the templates.
1252 * This directive does not direct display, it just passes data up to the
1255 .directive('egGridField', function() {
1257 require : '^egGrid',
1260 flesher: '=', // optional; function that can flesh a linked field, given the value
1261 comparator: '=', // optional; function that can sort the thing at the end of 'path'
1262 name : '@', // required; unique name
1263 path : '@', // optional; flesh path
1264 ignore: '@', // optional; fields to ignore when path is a wildcard
1265 label : '@', // optional; display label
1266 flex : '@', // optional; default flex width
1267 align : '@', // optional; default alignment, left/center/right
1268 dateformat : '@', // optional: passed down to egGridValueFilter
1269 datecontext: '@', // optional: passed down to egGridValueFilter to choose TZ
1270 datefilter: '@', // optional: passed down to egGridValueFilter to choose specialized date filters
1271 dateonlyinterval: '@', // optional: passed down to egGridValueFilter to choose a "better" format
1273 // if a field is part of an IDL object, but we are unable to
1274 // determine the class, because it's nested within a hash
1275 // (i.e. we can't navigate directly to the object via the IDL),
1276 // idlClass lets us specify the class. This is particularly
1277 // useful for nested wildcard fields.
1278 parentIdlClass : '@',
1280 // optional: for non-IDL columns, specifying a datatype
1281 // lets the caller control which display filter is used.
1282 // datatype should match the standard IDL datatypes.
1285 // optional hash of functions that can be imported into
1286 // the directive's scope; meant for cases where the "compiled"
1290 link : function(scope, element, attrs, egGridCtrl) {
1292 // boolean fields are presented as value-less attributes
1302 'required' // if set, always fetch data for this column
1305 if (angular.isDefined(attrs[field]))
1306 scope[field] = true;
1310 // any HTML content within the field is its custom template
1311 var tmpl = element.html();
1312 if (tmpl && !tmpl.match(/^\s*$/))
1313 scope.template = tmpl
1315 egGridCtrl.columnsProvider.add(scope);
1322 * eg-grid-action : used for specifying actions which may be applied
1323 * to items within the grid.
1325 .directive('egGridAction', function() {
1327 require : '^egGrid',
1331 group : '@', // Action group, ungrouped if not set
1332 label : '@', // Action label
1333 handler : '=', // Action function handler
1335 disabled : '=', // function
1338 link : function(scope, element, attrs, egGridCtrl) {
1339 egGridCtrl.addAction({
1341 group : scope.group,
1342 label : scope.label,
1343 divider : scope.divider,
1344 handler : scope.handler,
1345 disabled : scope.disabled,
1352 .factory('egGridColumnsProvider', ['egCore', function(egCore) {
1354 function ColumnsProvider(args) {
1357 cols.stockVisible = [];
1358 cols.idlClass = args.idlClass;
1359 cols.clientSort = args.clientSort;
1360 cols.defaultToHidden = args.defaultToHidden;
1361 cols.defaultToNoSort = args.defaultToNoSort;
1362 cols.defaultToNoMultiSort = args.defaultToNoMultiSort;
1363 cols.defaultDateFormat = args.defaultDateFormat;
1364 cols.defaultDateContext = args.defaultDateContext;
1366 // resets column width, visibility, and sort behavior
1367 // Visibility resets to the visibility settings defined in the
1368 // template (i.e. the original egGridField values).
1369 cols.reset = function() {
1370 angular.forEach(cols.columns, function(col) {
1374 if (cols.stockVisible.indexOf(col.name) > -1) {
1377 col.visible = false;
1382 // returns true if any columns are sortable
1383 cols.hasSortableColumn = function() {
1384 return cols.columns.filter(
1386 return col.sortable || col.multisortable;
1391 cols.showAllColumns = function() {
1392 angular.forEach(cols.columns, function(column) {
1393 column.visible = true;
1397 cols.hideAllColumns = function() {
1398 angular.forEach(cols.columns, function(col) {
1403 cols.indexOf = function(name) {
1404 for (var i = 0; i < cols.columns.length; i++) {
1405 if (cols.columns[i].name == name)
1411 cols.findColumn = function(name) {
1412 return cols.columns[cols.indexOf(name)];
1415 cols.compileAutoColumns = function() {
1416 var idl_class = egCore.idl.classes[cols.idlClass];
1421 if (field.virtual) return;
1422 if (field.datatype == 'link' || field.datatype == 'org_unit') {
1423 // if the field is a link and the linked class has a
1424 // "selector" field specified, use the selector field
1425 // as the display field for the columns.
1426 // flattener will take care of the fleshing.
1427 if (field['class']) {
1428 var selector_field = egCore.idl.classes[field['class']].fields
1429 .filter(function(f) { return Boolean(f.selector) })[0];
1430 if (selector_field) {
1431 field.path = field.name + '.' + selector_field.selector;
1435 cols.add(field, true);
1440 // if a column definition has a path with a wildcard, create
1441 // columns for all non-virtual fields at the specified
1442 // position in the path.
1443 cols.expandPath = function(colSpec) {
1445 var ignoreList = [];
1447 ignoreList = colSpec.ignore.split(' ');
1449 var dotpath = colSpec.path.replace(/\.?\*$/,'');
1453 if (colSpec.parentIdlClass) {
1454 class_obj = egCore.idl.classes[colSpec.parentIdlClass];
1456 class_obj = egCore.idl.classes[cols.idlClass];
1458 var idl_parent = class_obj;
1459 var old_field_label = '';
1461 if (!class_obj) return;
1463 //console.debug('egGrid: auto dotpath is: ' + dotpath);
1464 var path_parts = dotpath.split(/\./);
1466 // find the IDL class definition for the last element in the
1467 // path before the .*
1468 // an empty path_parts means expand the root class
1471 for (var path_idx in path_parts) {
1472 old_field = idl_field;
1474 var part = path_parts[path_idx];
1475 idl_field = class_obj.field_map[part];
1477 // unless we're at the end of the list, this field should
1478 // link to another class.
1479 if (idl_field && idl_field['class'] && (
1480 idl_field.datatype == 'link' ||
1481 idl_field.datatype == 'org_unit')) {
1482 if (old_field_label) old_field_label += ' : ';
1483 old_field_label += idl_field.label;
1484 class_obj = egCore.idl.classes[idl_field['class']];
1485 if (old_field) idl_parent = old_field;
1487 if (path_idx < (path_parts.length - 1)) {
1488 // we ran out of classes to hop through before
1489 // we ran out of path components
1490 console.error("egGrid: invalid IDL path: " + dotpath);
1497 angular.forEach(class_obj.fields, function(field) {
1499 // Only show wildcard fields where we have data to show
1500 // Virtual and un-fleshed links will not have any data.
1501 if (field.virtual ||
1502 (field.datatype == 'link' || field.datatype == 'org_unit') ||
1503 ignoreList.indexOf(field.name) > -1
1507 var col = cols.cloneFromScope(colSpec);
1508 col.path = (dotpath ? dotpath + '.' + field.name : field.name);
1510 // log line below is very chatty. disable until needed.
1511 // console.debug('egGrid: field: ' +field.name + '; parent field: ' + js2JSON(idl_parent));
1512 cols.add(col, false, true,
1513 {idl_parent : idl_parent, idl_field : field, idl_class : class_obj, field_parent_label : old_field_label });
1516 cols.columns = cols.columns.sort(
1518 if (a.explicit) return -1;
1519 if (b.explicit) return 1;
1521 if (a.idlclass && b.idlclass) {
1522 if (a.idlclass < b.idlclass) return -1;
1523 if (b.idlclass < a.idlclass) return 1;
1526 if (a.path && b.path && a.path.lastIndexOf('.') && b.path.lastIndexOf('.')) {
1527 if (a.path.substring(0, a.path.lastIndexOf('.')) < b.path.substring(0, b.path.lastIndexOf('.'))) return -1;
1528 if (b.path.substring(0, b.path.lastIndexOf('.')) < a.path.substring(0, a.path.lastIndexOf('.'))) return 1;
1531 if (a.label && b.label) {
1532 if (a.label < b.label) return -1;
1533 if (b.label < a.label) return 1;
1536 return a.name < b.name ? -1 : 1;
1543 "egGrid: wildcard path does not resolve to an object: "
1548 // angular.clone(scopeObject) is not permittable. Manually copy
1549 // the fields over that we need (so the scope object can go away).
1550 cols.cloneFromScope = function(colSpec) {
1552 flesher : colSpec.flesher,
1553 comparator : colSpec.comparator,
1554 name : colSpec.name,
1555 label : colSpec.label,
1556 path : colSpec.path,
1557 align : colSpec.align || 'left',
1558 flex : Number(colSpec.flex) || 2,
1559 sort : Number(colSpec.sort) || 0,
1560 required : colSpec.required,
1561 linkpath : colSpec.linkpath,
1562 template : colSpec.template,
1563 visible : colSpec.visible,
1564 compiled : colSpec.compiled,
1565 handlers : colSpec.handlers,
1566 hidden : colSpec.hidden,
1567 datatype : colSpec.datatype,
1568 sortable : colSpec.sortable,
1569 nonsortable : colSpec.nonsortable,
1570 multisortable : colSpec.multisortable,
1571 nonmultisortable : colSpec.nonmultisortable,
1572 dateformat : colSpec.dateformat,
1573 datecontext : colSpec.datecontext,
1574 datefilter : colSpec.datefilter,
1575 dateonlyinterval : colSpec.dateonlyinterval,
1576 parentIdlClass : colSpec.parentIdlClass
1581 // Add a column to the columns collection.
1582 // Columns may come from a slim eg-columns-field or
1583 // directly from the IDL.
1584 cols.add = function(colSpec, fromIDL, fromExpand, idl_info) {
1586 // First added column with the specified path takes precedence.
1587 // This allows for specific definitions followed by wildcard
1588 // definitions. If a match is found, back out.
1589 if (cols.columns.filter(function(c) {
1590 return (c.path == colSpec.path) })[0]) {
1591 console.debug('skipping pre-existing column ' + colSpec.path);
1595 var column = fromExpand ? colSpec : cols.cloneFromScope(colSpec);
1597 if (column.path && column.path.match(/\*$/))
1598 return cols.expandPath(colSpec);
1600 if (!fromExpand) column.explicit = true;
1602 if (!column.name) column.name = column.path;
1603 if (!column.path) column.path = column.name;
1605 if (column.visible || (!cols.defaultToHidden && !column.hidden))
1606 column.visible = true;
1608 if (column.sortable || (!cols.defaultToNoSort && !column.nonsortable))
1609 column.sortable = true;
1611 if (column.multisortable ||
1612 (!cols.defaultToNoMultiSort && !column.nonmultisortable))
1613 column.multisortable = true;
1615 if (cols.defaultDateFormat && ! column.dateformat) {
1616 column.dateformat = cols.defaultDateFormat;
1619 if (cols.defaultDateOnlyInterval && ! column.dateonlyinterval) {
1620 column.dateonlyinterval = cols.defaultDateOnlyInterval;
1623 if (cols.defaultDateContext && ! column.datecontext) {
1624 column.datecontext = cols.defaultDateContext;
1627 if (cols.defaultDateFilter && ! column.datefilter) {
1628 column.datefilter = cols.defaultDateFilter;
1631 cols.columns.push(column);
1633 // Track which columns are visible by default in case we
1634 // need to reset column visibility
1636 cols.stockVisible.push(column.name);
1638 if (fromIDL) return; // directly from egIDL. nothing left to do.
1640 // lookup the matching IDL field
1641 if (!idl_info && cols.idlClass)
1642 idl_info = cols.idlFieldFromPath(column.path);
1645 // column is not represented within the IDL
1646 column.adhoc = true;
1650 column.datatype = idl_info.idl_field.datatype;
1652 if (!column.label) {
1653 column.label = idl_info.idl_field.label || column.name;
1656 if (fromExpand && idl_info.idl_class) {
1657 column.idlclass = '';
1658 if (idl_info.field_parent_label && idl_info.idl_parent.label != idl_info.idl_class.label) {
1659 column.idlclass = (idl_info.field_parent_label || idl_info.idl_parent.label || idl_info.idl_parent.name);
1661 column.idlclass += idl_info.idl_class.label || idl_info.idl_class.name;
1666 // finds the IDL field from the dotpath, using the columns
1667 // idlClass as the base.
1668 cols.idlFieldFromPath = function(dotpath) {
1669 var class_obj = egCore.idl.classes[cols.idlClass];
1670 if (!dotpath) return null;
1672 var path_parts = dotpath.split(/\./);
1676 for (var path_idx in path_parts) {
1677 var part = path_parts[path_idx];
1678 idl_parent = idl_field;
1679 idl_field = class_obj.field_map[part];
1682 if (idl_field['class'] && (
1683 idl_field.datatype == 'link' ||
1684 idl_field.datatype == 'org_unit')) {
1685 class_obj = egCore.idl.classes[idl_field['class']];
1693 idl_parent: idl_parent,
1694 idl_field : idl_field,
1695 idl_class : class_obj
1701 instance : function(args) { return new ColumnsProvider(args) }
1707 * Generic data provider template class. This is basically an abstract
1708 * class factory service whose instances can be locally modified to
1709 * meet the needs of each individual grid.
1711 .factory('egGridDataProvider',
1712 ['$q','$timeout','$filter','egCore',
1713 function($q , $timeout , $filter , egCore) {
1715 function GridDataProvider(args) {
1716 var gridData = this;
1717 if (!args) args = {};
1720 gridData.get = args.get;
1721 gridData.query = args.query;
1722 gridData.idlClass = args.idlClass;
1723 gridData.columnsProvider = args.columnsProvider;
1725 // Delivers a stream of array data via promise.notify()
1726 // Useful for passing an array of data to egGrid.get()
1727 // If a count is provided, the array will be trimmed to
1728 // the range defined by count and offset
1729 gridData.arrayNotifier = function(arr, offset, count) {
1730 if (!arr || arr.length == 0) return $q.when();
1732 if (gridData.columnsProvider.clientSort
1734 && gridData.sort.length > 0
1736 var sorter_cache = [];
1737 arr.sort(function(a,b) {
1738 for (var si = 0; si < gridData.sort.length; si++) {
1739 if (!sorter_cache[si]) { // Build sort structure on first comparison, reuse thereafter
1740 var field = gridData.sort[si];
1743 if (angular.isObject(field)) {
1744 dir = Object.values(field)[0];
1745 field = Object.keys(field)[0];
1748 var path = gridData.columnsProvider.findColumn(field).path || field;
1749 var comparator = gridData.columnsProvider.findColumn(field).comparator ||
1750 function (x,y) { if (x < y) return -1; if (x > y) return 1; return 0 };
1752 sorter_cache[si] = {
1755 comparator : comparator
1759 var sc = sorter_cache[si];
1763 if (a._isfieldmapper || angular.isFunction(a[sc.field])) {
1764 try {af = a[sc.field](); bf = b[sc.field]() } catch (e) {};
1766 af = a[sc.field]; bf = b[sc.field];
1768 if (af === undefined && sc.field.indexOf('.') > -1) { // assume an object, not flat path
1769 var parts = sc.field.split('.');
1772 angular.forEach(parts, function (p) {
1774 if (af._isfieldmapper || angular.isFunction(af[p])) af = af[p]();
1778 if (bf._isfieldmapper || angular.isFunction(bf[p])) bf = bf[p]();
1784 if (af === undefined) af = null;
1785 if (bf === undefined) bf = null;
1787 if (af === null && bf !== null) return 1;
1788 if (bf === null && af !== null) return -1;
1790 if (!(bf === null && af === null)) {
1791 var partial = sc.comparator(af,bf);
1793 if (sc.dir == 'desc') {
1794 if (partial > 0) return -1;
1806 if (count) arr = arr.slice(offset, offset + count);
1807 var def = $q.defer();
1808 // promise notifications are only witnessed when delivered
1809 // after the caller has his hands on the promise object
1810 $timeout(function() {
1811 angular.forEach(arr, def.notify);
1817 // Calls the grid refresh function. Once instantiated, the
1818 // grid will replace this function with it's own refresh()
1819 gridData.refresh = function(noReset) { }
1821 if (!gridData.get) {
1822 // returns a promise whose notify() delivers items
1823 gridData.get = function(index, count) {
1824 console.error("egGridDataProvider.get() not implemented");
1828 // attempts a flat field lookup first. If the column is not
1829 // found on the top-level object, attempts a nested lookup
1830 // TODO: consider a caching layer to speed up template
1831 // rendering, particularly for nested objects?
1832 gridData.itemFieldValue = function(item, column) {
1834 if (column.name in item) {
1835 if (typeof item[column.name] == 'function') {
1836 val = item[column.name]();
1838 val = item[column.name];
1841 val = gridData.nestedItemFieldValue(item, column);
1847 // TODO: deprecate me
1848 gridData.flatItemFieldValue = function(item, column) {
1849 console.warn('gridData.flatItemFieldValue deprecated; '
1850 + 'leave provider.itemFieldValue unset');
1851 return item[column.name];
1854 // given an object and a dot-separated path to a field,
1855 // extract the value of the field. The path can refer
1856 // to function names or object attributes. If the final
1857 // value is an IDL field, run the value through its
1858 // corresponding output filter.
1859 gridData.nestedItemFieldValue = function(obj, column) {
1860 item = obj; // keep a copy around
1862 if (obj === null || obj === undefined || obj === '') return '';
1863 if (!column.path) return obj;
1866 var parts = column.path.split('.');
1868 angular.forEach(parts, function(step, idx) {
1869 // object is not fleshed to the expected extent
1870 if (typeof obj != 'object') {
1871 if (typeof obj != 'undefined' && column.flesher) {
1872 obj = column.flesher(obj, column, item);
1879 if (!obj) return '';
1881 var cls = obj.classname;
1882 if (cls && (class_obj = egCore.idl.classes[cls])) {
1883 idl_field = class_obj.field_map[step];
1884 obj = obj[step] ? obj[step]() : '';
1886 if (angular.isFunction(obj[step])) {
1894 // We found a nested IDL object which may or may not have
1895 // been configured as a top-level column. Grab the datatype.
1896 if (idl_field && !column.datatype)
1897 column.datatype = idl_field.datatype;
1899 if (obj === null || obj === undefined || obj === '') return '';
1905 instance : function(args) {
1906 return new GridDataProvider(args);
1913 // Factory service for egGridDataManager instances, which are
1914 // responsible for collecting flattened grid data.
1915 .factory('egGridFlatDataProvider',
1916 ['$q','egCore','egGridDataProvider',
1917 function($q , egCore , egGridDataProvider) {
1920 instance : function(args) {
1921 var provider = egGridDataProvider.instance(args);
1923 provider.get = function(offset, count) {
1925 // no query means no call
1926 if (!provider.query ||
1927 angular.equals(provider.query, {}))
1930 // find all of the currently visible columns
1931 var queryFields = {}
1932 angular.forEach(provider.columnsProvider.columns,
1934 // only query IDL-tracked columns
1935 if (!col.adhoc && col.name && col.path && (col.required || col.visible))
1936 queryFields[col.name] = col.path;
1940 return egCore.net.request(
1942 'open-ils.fielder.flattened_search',
1943 egCore.auth.token(), provider.idlClass,
1944 queryFields, provider.query,
1945 { sort : provider.sort,
1951 //provider.itemFieldValue = provider.flatItemFieldValue;
1958 .directive('egGridColumnDragSource', function() {
1961 require : '^egGrid',
1962 link : function(scope, element, attrs, egGridCtrl) {
1963 angular.element(element).attr('draggable', 'true');
1965 element.bind('dragstart', function(e) {
1966 egGridCtrl.dragColumn = attrs.column;
1967 egGridCtrl.dragType = attrs.dragType || 'move'; // or resize
1968 egGridCtrl.colResizeDir = 0;
1970 if (egGridCtrl.dragType == 'move') {
1971 // style the column getting moved
1972 angular.element(e.target).addClass(
1973 'eg-grid-column-move-handle-active');
1977 element.bind('dragend', function(e) {
1978 if (egGridCtrl.dragType == 'move') {
1979 angular.element(e.target).removeClass(
1980 'eg-grid-column-move-handle-active');
1987 .directive('egGridColumnDragDest', function() {
1990 require : '^egGrid',
1991 link : function(scope, element, attrs, egGridCtrl) {
1993 element.bind('dragover', function(e) { // required for drop
1994 e.stopPropagation();
1996 e.dataTransfer.dropEffect = 'move';
1998 if (egGridCtrl.colResizeDir == 0) return; // move
2000 var cols = egGridCtrl.columnsProvider;
2001 var srcCol = egGridCtrl.dragColumn;
2002 var srcColIdx = cols.indexOf(srcCol);
2004 if (egGridCtrl.colResizeDir == -1) {
2005 if (cols.indexOf(attrs.column) <= srcColIdx) {
2006 egGridCtrl.modifyColumnFlex(
2007 egGridCtrl.columnsProvider.findColumn(
2008 egGridCtrl.dragColumn), -1);
2009 if (cols.columns[srcColIdx+1]) {
2010 // source column shrinks by one, column to the
2011 // right grows by one.
2012 egGridCtrl.modifyColumnFlex(
2013 cols.columns[srcColIdx+1], 1);
2018 if (cols.indexOf(attrs.column) > srcColIdx) {
2019 egGridCtrl.modifyColumnFlex(
2020 egGridCtrl.columnsProvider.findColumn(
2021 egGridCtrl.dragColumn), 1);
2022 if (cols.columns[srcColIdx+1]) {
2023 // source column grows by one, column to the
2024 // right grows by one.
2025 egGridCtrl.modifyColumnFlex(
2026 cols.columns[srcColIdx+1], -1);
2034 element.bind('dragenter', function(e) {
2035 e.stopPropagation();
2037 if (egGridCtrl.dragType == 'move') {
2038 angular.element(e.target).addClass('eg-grid-col-hover');
2040 // resize grips are on the right side of each column.
2041 // dragenter will either occur on the source column
2042 // (dragging left) or the column to the right.
2043 if (egGridCtrl.colResizeDir == 0) {
2044 if (egGridCtrl.dragColumn == attrs.column) {
2045 egGridCtrl.colResizeDir = -1; // west
2047 egGridCtrl.colResizeDir = 1; // east
2053 element.bind('dragleave', function(e) {
2054 e.stopPropagation();
2056 if (egGridCtrl.dragType == 'move') {
2057 angular.element(e.target).removeClass('eg-grid-col-hover');
2061 element.bind('drop', function(e) {
2062 e.stopPropagation();
2064 egGridCtrl.colResizeDir = 0;
2065 if (egGridCtrl.dragType == 'move') {
2066 angular.element(e.target).removeClass('eg-grid-col-hover');
2067 egGridCtrl.onColumnDrop(attrs.column); // move the column
2074 .directive('egGridMenuItem', function() {
2077 require : '^egGrid',
2083 handler : '=', // onclick handler function
2084 divider : '=', // if true, show a divider only
2085 handlerData : '=', // if set, passed as second argument to handler
2086 disabled : '=', // function
2087 hidden : '=' // function
2089 link : function(scope, element, attrs, egGridCtrl) {
2090 egGridCtrl.addMenuItem({
2091 checkbox : scope.checkbox,
2092 checked : scope.checked ? true : false,
2093 label : scope.label,
2094 standalone : scope.standalone ? true : false,
2095 handler : scope.handler,
2096 divider : scope.divider,
2097 disabled : scope.disabled,
2098 hidden : scope.hidden,
2099 handlerData : scope.handlerData
2106 /* https://stackoverflow.com/questions/17343696/adding-an-ng-click-event-inside-a-filter/17344875#17344875 */
2107 .directive('compile', ['$compile', function ($compile) {
2108 return function(scope, element, attrs) {
2109 // pass through column defs from grid cell's scope
2110 scope.col = scope.$parent.col;
2113 // watch the 'compile' expression for changes
2114 return scope.$eval(attrs.compile);
2117 // when the 'compile' expression changes
2118 // assign it into the current DOM
2119 element.html(value);
2121 // compile the new DOM and link it to the current
2123 // NOTE: we only compile .childNodes so that
2124 // we don't get into infinite loop compiling ourselves
2125 $compile(element.contents())(scope);
2134 * Translates bare IDL object values into display values.
2135 * 1. Passes dates through the angular date filter
2136 * 2. Translates bools to Booleans so the browser can display translated
2137 * value. (Though we could manually translate instead..)
2138 * Others likely to follow...
2140 .filter('egGridValueFilter', ['$filter','egCore', function($filter,egCore) {
2141 function traversePath(obj,path) {
2142 var list = path.split('.');
2143 for (var part in path) {
2144 if (obj[path]) obj = obj[path]
2150 var GVF = function(value, column, item) {
2151 switch(column.datatype) {
2154 // Browser will translate true/false for us
2156 case '1' : // legacy
2160 case '0' : // legacy
2163 // value may be null, '', etc.
2164 default : return '';
2167 var interval = angular.isFunction(item[column.dateonlyinterval])
2168 ? item[column.dateonlyinterval]()
2169 : item[column.dateonlyinterval];
2171 if (column.dateonlyinterval && !interval) // try it as a dotted path
2172 interval = traversePath(item, column.dateonlyinterval);
2174 var context = angular.isFunction(item[column.datecontext])
2175 ? item[column.datecontext]()
2176 : item[column.datecontext];
2178 if (column.datecontext && !context) // try it as a dotted path
2179 context = traversePath(item, column.datecontext);
2181 var date_filter = column.datefilter || 'egOrgDateInContext';
2183 return $filter(date_filter)(value, column.dateformat, context, interval);
2185 return $filter('currency')(value);
2191 GVF.$stateful = true;