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 // comma-separated list of supported or disabled grid features
33 // supported features:
34 // -display : columns are hidden by default
35 // -sort : columns are unsortable by default
36 // -multisort : sort priorities config disabled by default
39 // optional primary grid label
42 // if true, use the IDL class label as the mainLabel
45 // optional context menu label
48 // Hash of control functions.
50 // These functions are defined by the calling scope and
51 // invoked as-is by the grid w/ the specified parameters.
53 // itemRetrieved : function(item) {}
54 // allItemsRetrieved : function() {}
57 // If defined, the grid will watch the return value from
58 // the function defined at watchQuery on each digest and
59 // re-draw the grid when query changes occur.
61 // watchQuery : function() { /* return grid query */ }
64 // These functions are defined by the grid and thus
65 // replace any values defined for these attributes from the
68 // activateItem : function(item) {}
69 // allItems : function(allItems) {}
70 // selectedItems : function(selected) {}
71 // selectItems : function(ids) {}
72 // setQuery : function(queryStruct) {} // causes reload
73 // setSort : function(sortSturct) {} // causes reload
77 // TODO: avoid hard-coded url
78 templateUrl : '/eg/staff/share/t_autogrid',
80 link : function(scope, element, attrs) {
81 // link() is called after page compilation, which means our
82 // eg-grid-field's have been parsed and loaded. Now it's
83 // safe to perform our initial page load.
85 // load auto fields after eg-grid-field's so they are not clobbered
86 scope.handleAutoFields();
89 scope.grid_element = element;
91 .find('.eg-grid-content-body')
92 .bind('contextmenu', scope.showActionContextMenu);
96 '$scope','$q','egCore','egGridFlatDataProvider','$location',
97 'egGridColumnsProvider','$filter','$window','$sce','$timeout',
98 function($scope, $q , egCore, egGridFlatDataProvider , $location,
99 egGridColumnsProvider , $filter , $window , $sce , $timeout) {
103 grid.init = function() {
106 $scope.showGridConf = false;
107 grid.totalCount = -1;
108 $scope.selected = {};
109 $scope.actionGroups = [{actions:[]}]; // Grouped actions for selected items
110 $scope.menuItems = []; // global actions
112 // remove some unneeded values from the scope to reduce bloat
114 grid.idlClass = $scope.idlClass;
115 delete $scope.idlClass;
117 grid.persistKey = $scope.persistKey;
118 delete $scope.persistKey;
120 var stored_limit = 0;
121 if (grid.persistKey) {
122 var stored_limit = Number(
123 egCore.hatch.getLocalItem('eg.grid.' + grid.persistKey + '.limit')
126 grid.limit = Number(stored_limit) || Number($scope.pageSize) || 25;
128 grid.indexField = $scope.idField;
129 delete $scope.idField;
131 grid.dataProvider = $scope.itemsProvider;
133 var features = ($scope.features) ?
134 $scope.features.split(',') : [];
135 delete $scope.features;
137 if (!grid.indexField && grid.idlClass)
138 grid.indexField = egCore.idl.classes[grid.idlClass].pkey;
140 grid.columnsProvider = egGridColumnsProvider.instance({
141 idlClass : grid.idlClass,
142 defaultToHidden : (features.indexOf('-display') > -1),
143 defaultToNoSort : (features.indexOf('-sort') > -1),
144 defaultToNoMultiSort : (features.indexOf('-multisort') > -1)
147 $scope.handleAutoFields = function() {
148 if ($scope.autoFields) {
149 if (grid.autoLabel) {
151 egCore.idl.classes[grid.idlClass].label;
153 grid.columnsProvider.compileAutoColumns();
154 delete $scope.autoFields;
158 if (!grid.dataProvider) {
159 // no provider, um, provided.
160 // Use a flat data provider
162 grid.selfManagedData = true;
163 grid.dataProvider = egGridFlatDataProvider.instance({
164 indexField : grid.indexField,
165 idlClass : grid.idlClass,
166 columnsProvider : grid.columnsProvider,
171 $scope.itemFieldValue = grid.dataProvider.itemFieldValue;
172 $scope.indexValue = function(item) {
173 return grid.indexValue(item)
176 grid.applyControlFunctions();
178 grid.loadConfig().then(function() {
179 // link columns to scope after loadConfig(), since it
180 // replaces the columns array.
181 $scope.columns = grid.columnsProvider.columns;
184 // NOTE: grid.collect() is first called from link(), not here.
187 // link our control functions into the gridControls
188 // scope object so the caller can access them.
189 grid.applyControlFunctions = function() {
191 // we use some of these controls internally, so sett
192 // them up even if the caller doesn't request them.
193 var controls = $scope.gridControls || {};
195 // link in the control functions
196 controls.selectedItems = function() {
197 return grid.getSelectedItems()
200 controls.allItems = function() {
204 controls.selectItems = function(ids) {
206 $scope.selected = {};
207 angular.forEach(ids, function(i) {
208 $scope.selected[''+i] = true;
212 // if the caller provided a functional setQuery,
213 // extract the value before replacing it
214 if (controls.setQuery) {
215 grid.dataProvider.query =
219 controls.setQuery = function(query) {
220 grid.dataProvider.query = query;
224 if (controls.watchQuery) {
225 // capture the initial query value
226 grid.dataProvider.query = controls.watchQuery();
229 $scope.gridWatchQuery = controls.watchQuery;
230 $scope.$watch('gridWatchQuery()', function(newv) {
231 controls.setQuery(newv);
235 // if the caller provided a functional setSort
236 // extract the value before replacing it
237 grid.dataProvider.sort =
238 controls.setSort ? controls.setSort() : [];
240 controls.setSort = function(sort) {
244 controls.refresh = function(noReset) {
245 if (!noReset) grid.offset = 0;
249 controls.setLimit = function(limit,forget) {
250 if (!forget && grid.persistKey)
251 egCore.hatch.setLocalItem('eg.grid.' + grid.persistKey + '.limit', limit);
254 controls.getLimit = function() {
257 controls.setOffset = function(offset) {
258 grid.offset = offset;
260 controls.getOffset = function() {
264 grid.dataProvider.refresh = controls.refresh;
265 grid.controls = controls;
268 // If a menu item provides its own HTML template, translate it,
269 // using the menu item for the template scope.
270 // note: $sce is required to avoid security restrictions and
271 // is OK here, since the template comes directly from a
272 // local HTML template (not user input).
273 $scope.translateMenuItemTemplate = function(item) {
274 var html = egCore.strings.$replace(item.template, {item : item});
275 return $sce.trustAsHtml(html);
278 // add a new (global) grid menu item
279 grid.addMenuItem = function(item) {
280 $scope.menuItems.push(item);
281 var handler = item.handler;
282 item.handler = function() {
283 $scope.gridMenuIsOpen = false; // close menu
286 item.handlerData, grid.getSelectedItems());
291 // add a selected-items action
292 grid.addAction = function(act) {
294 $scope.actionGroups.forEach(function(g){
295 if (g.label === act.group) {
301 $scope.actionGroups.push({
308 // remove the stored column configuration preferenc, then recover
309 // the column visibility information from the initial page load.
310 $scope.resetColumns = function() {
311 $scope.gridColumnPickerIsOpen = false;
312 egCore.hatch.removeItem('eg.grid.' + grid.persistKey)
314 grid.columnsProvider.reset();
315 if (grid.selfManagedData) grid.collect();
319 $scope.showAllColumns = function() {
320 $scope.gridColumnPickerIsOpen = false;
321 grid.columnsProvider.showAllColumns();
322 if (grid.selfManagedData) grid.collect();
325 $scope.hideAllColumns = function() {
326 $scope.gridColumnPickerIsOpen = false;
327 grid.columnsProvider.hideAllColumns();
328 // note: no need to fetch new data if no columns are visible
331 $scope.toggleColumnVisibility = function(col) {
332 $scope.gridColumnPickerIsOpen = false;
333 col.visible = !col.visible;
335 // egGridFlatDataProvider only retrieves data to be
336 // displayed. When column visibility changes, it's
337 // necessary to fetch the newly visible column data.
338 if (grid.selfManagedData) grid.collect();
341 // save the columns configuration (position, sort, width) to
342 // eg.grid.<persist-key>
343 $scope.saveConfig = function() {
344 $scope.gridColumnPickerIsOpen = false;
346 if (!grid.persistKey) {
348 "Cannot save settings without a grid persist-key");
352 // only store information about visible columns.
353 var conf = grid.columnsProvider.columns.filter(
354 function(col) {return Boolean(col.visible) });
356 // now scrunch the data down to just the needed info
357 conf = conf.map(function(col) {
358 var c = {name : col.name}
359 // Apart from the name, only store non-default values.
360 // No need to store col.visible, since that's implicit
361 if (col.align != 'left') c.align = col.align;
362 if (col.flex != 2) c.flex = col.flex;
363 if (Number(col.sort)) c.sort = Number(c.sort);
367 egCore.hatch.setItem('eg.grid.' + grid.persistKey, conf)
369 // Save operation performed from the grid configuration UI.
370 // Hide the configuration UI and re-draw w/ sort applied
371 if ($scope.showGridConf)
372 $scope.toggleConfDisplay();
376 // load the columns configuration (position, sort, width) from
377 // eg.grid.<persist-key> and apply the loaded settings to the
378 // columns on our columnsProvider
379 grid.loadConfig = function() {
380 if (!grid.persistKey) return $q.when();
382 return egCore.hatch.getItem('eg.grid.' + grid.persistKey)
383 .then(function(conf) {
386 var columns = grid.columnsProvider.columns;
389 angular.forEach(conf, function(col) {
390 var grid_col = columns.filter(
391 function(c) {return c.name == col.name})[0];
394 // saved column does not match a column in the
395 // current grid. skip it.
399 grid_col.align = col.align || 'left';
400 grid_col.flex = col.flex || 2;
401 grid_col.sort = col.sort || 0;
402 // all saved columns are assumed to be true
403 grid_col.visible = true;
404 new_cols.push(grid_col);
407 // columns which are not expressed within the saved
408 // configuration are marked as non-visible and
409 // appended to the end of the new list of columns.
410 angular.forEach(columns, function(col) {
411 var found = conf.filter(
412 function(c) {return (c.name == col.name)})[0];
419 grid.columnsProvider.columns = new_cols;
424 $scope.onContextMenu = function($event) {
425 var col = angular.element($event.target).attr('column');
426 console.log('selected column ' + col);
429 $scope.page = function() {
430 return (grid.offset / grid.limit) + 1;
433 $scope.goToPage = function(page) {
435 if (angular.isNumber(page) && page > 0) {
436 grid.offset = (page - 1) * grid.limit;
441 $scope.offset = function(o) {
442 if (angular.isNumber(o))
447 $scope.limit = function(l) {
448 if (angular.isNumber(l)) {
450 egCore.hatch.setLocalItem('eg.grid.' + grid.persistKey + '.limit', l);
456 $scope.onFirstPage = function() {
457 return grid.offset == 0;
460 $scope.hasNextPage = function() {
461 // we have less data than requested, there must
462 // not be any more pages
463 if (grid.count() < grid.limit) return false;
465 // if the total count is not known, assume that a full
466 // page of data implies more pages are available.
467 if (grid.totalCount == -1) return true;
469 // we have a full page of data, but is there more?
470 return grid.totalCount > (grid.offset + grid.count());
473 $scope.incrementPage = function() {
474 grid.offset += grid.limit;
478 $scope.decrementPage = function() {
479 if (grid.offset < grid.limit) {
482 grid.offset -= grid.limit;
487 // number of items loaded for the current page of results
488 grid.count = function() {
489 return $scope.items.length;
492 // returns the unique identifier value for the provided item
493 // for internal consistency, indexValue is always coerced
495 grid.indexValue = function(item) {
496 if (angular.isObject(item)) {
498 if (angular.isFunction(item[grid.indexField]))
499 return ''+item[grid.indexField]();
500 return ''+item[grid.indexField]; // flat data
503 // passed a non-object; assume it's an index
507 // fires the hide handler function for a context action
508 $scope.actionHide = function(action) {
512 return action.hide(action);
515 // fires the action handler function for a context action
516 $scope.actionLauncher = function(action) {
517 if (!action.handler) {
519 'No handler specified for "' + action.label + '"');
523 action.handler(grid.getSelectedItems());
525 console.error('Error executing handler for "'
526 + action.label + '" => ' + E + "\n" + E.stack);
529 if ($scope.action_context_showing) $scope.hideActionContextMenu();
534 $scope.hideActionContextMenu = function () {
535 $($scope.menu_dom).css({
537 width: $scope.action_context_width,
538 top: $scope.action_context_y,
539 left: $scope.action_context_x
541 $($scope.action_context_parent).append($scope.menu_dom);
542 $scope.action_context_oldy = $scope.action_context_oldx = 0;
543 $('body').unbind('click.remove_context_menu_'+$scope.action_context_index);
544 $scope.action_context_showing = false;
547 $scope.action_context_showing = false;
548 $scope.showActionContextMenu = function ($event) {
550 // Have to gather these here, instead of inside link()
551 if (!$scope.menu_dom) $scope.menu_dom = $($scope.grid_element).find('.grid-action-dropdown')[0];
552 if (!$scope.action_context_parent) $scope.action_context_parent = $($scope.menu_dom).parent();
554 if (!grid.getSelectedItems().length) // Nothing selected, fire the click event
555 $event.target.click();
557 if (!$scope.action_context_showing) {
558 $scope.action_context_width = $($scope.menu_dom).css('width');
559 $scope.action_context_y = $($scope.menu_dom).css('top');
560 $scope.action_context_x = $($scope.menu_dom).css('left');
561 $scope.action_context_showing = true;
562 $scope.action_context_index = Math.floor((Math.random() * 1000) + 1);
564 $('body').append($($scope.menu_dom));
565 $('body').bind('click.remove_context_menu_'+$scope.action_context_index, $scope.hideActionContextMenu);
568 $($scope.menu_dom).css({
570 width: $scope.action_context_width,
578 // returns the list of selected item objects
579 grid.getSelectedItems = function() {
580 return $scope.items.filter(
582 return Boolean($scope.selected[grid.indexValue(item)]);
587 grid.getItemByIndex = function(index) {
588 for (var i = 0; i < $scope.items.length; i++) {
589 var item = $scope.items[i];
590 if (grid.indexValue(item) == index)
595 // selects one row after deselecting all of the others
596 grid.selectOneItem = function(index) {
597 $scope.selected = {};
598 $scope.selected[index] = true;
601 // selects or deselects an item, without affecting the others.
602 // returns true if the item is selected; false if de-selected.
603 grid.toggleSelectOneItem = function(index) {
604 if ($scope.selected[index]) {
605 delete $scope.selected[index];
608 return $scope.selected[index] = true;
612 grid.selectAllItems = function() {
613 angular.forEach($scope.items, function(item) {
614 $scope.selected[grid.indexValue(item)] = true
618 $scope.$watch('selectAll', function(newVal) {
620 grid.selectAllItems();
622 $scope.selected = {};
626 // returns true if item1 appears in the list before item2;
627 // false otherwise. this is slightly more efficient that
628 // finding the position of each then comparing them.
629 // item1 / item2 may be an item or an item index
630 grid.itemComesBefore = function(itemOrIndex1, itemOrIndex2) {
631 var idx1 = grid.indexValue(itemOrIndex1);
632 var idx2 = grid.indexValue(itemOrIndex2);
634 // use for() for early exit
635 for (var i = 0; i < $scope.items.length; i++) {
636 var idx = grid.indexValue($scope.items[i]);
637 if (idx == idx1) return true;
638 if (idx == idx2) return false;
643 // 0-based position of item in the current data set
644 grid.indexOf = function(item) {
645 var idx = grid.indexValue(item);
646 for (var i = 0; i < $scope.items.length; i++) {
647 if (grid.indexValue($scope.items[i]) == idx)
653 grid.modifyColumnFlex = function(column, val) {
655 // prevent flex:0; use hiding instead
659 $scope.modifyColumnFlex = function(col, val) {
660 grid.modifyColumnFlex(col, val);
663 // handles click, control-click, and shift-click
664 $scope.handleRowClick = function($event, item) {
665 var index = grid.indexValue(item);
667 var origSelected = Object.keys($scope.selected);
669 if ($event.ctrlKey || $event.metaKey /* mac command */) {
671 if (grid.toggleSelectOneItem(index))
672 grid.lastSelectedItemIndex = index;
674 } else if ($event.shiftKey) {
677 if (!grid.lastSelectedItemIndex ||
678 index == grid.lastSelectedItemIndex) {
679 grid.selectOneItem(index);
680 grid.lastSelectedItemIndex = index;
684 var selecting = false;
685 var ascending = grid.itemComesBefore(
686 grid.lastSelectedItemIndex, item);
688 grid.indexOf(grid.lastSelectedItemIndex);
690 // update to new last-selected
691 grid.lastSelectedItemIndex = index;
693 // select each row between the last selected and
694 // currently selected items
696 startPos += ascending ? 1 : -1;
697 var curItem = $scope.items[startPos];
699 var curIdx = grid.indexValue(curItem);
700 $scope.selected[curIdx] = true;
701 if (curIdx == index) break; // all done
706 grid.selectOneItem(index);
707 grid.lastSelectedItemIndex = index;
711 // Builds a sort expression from column sort priorities.
712 // called on page load and any time the priorities are modified.
713 grid.compileSort = function() {
714 var sortList = grid.columnsProvider.columns.filter(
715 function(col) { return Number(col.sort) != 0 }
718 if (Math.abs(a.sort) < Math.abs(b.sort))
724 if (sortList.length) {
725 grid.dataProvider.sort = sortList.map(function(col) {
727 blob[col.name] = col.sort < 0 ? 'desc' : 'asc';
733 // builds a sort expression using a single column,
734 // toggling between ascending and descending sort.
735 $scope.quickSort = function(col_name) {
736 var sort = grid.dataProvider.sort;
737 if (sort && sort.length &&
738 sort[0] == col_name) {
740 blob[col_name] = 'desc';
741 grid.dataProvider.sort = [blob];
743 grid.dataProvider.sort = [col_name];
750 // show / hide the grid configuration row
751 $scope.toggleConfDisplay = function() {
752 if ($scope.showGridConf) {
753 $scope.showGridConf = false;
754 if (grid.columnsProvider.hasSortableColumn()) {
755 // only refresh the grid if the user has the
756 // ability to modify the sort priorities.
762 $scope.showGridConf = true;
765 $scope.gridColumnPickerIsOpen = false;
768 // called when a dragged column is dropped onto itself
769 // or any other column
770 grid.onColumnDrop = function(target) {
771 if (angular.isUndefined(target)) return;
772 if (target == grid.dragColumn) return;
773 var srcIdx, targetIdx, srcCol;
774 angular.forEach(grid.columnsProvider.columns,
776 if (col.name == grid.dragColumn) {
779 } else if (col.name == target) {
785 if (srcIdx < targetIdx) targetIdx--;
787 // move src column from old location to new location in
788 // the columns array, then force a page refresh
789 grid.columnsProvider.columns.splice(srcIdx, 1);
790 grid.columnsProvider.columns.splice(targetIdx, 0, srcCol);
794 // prepares a string for inclusion within a CSV document
795 // by escaping commas and quotes and removing newlines.
796 grid.csvDatum = function(str) {
799 str = str.replace(/\n/g, '');
800 if (str.match(/\,/) || str.match(/"/)) {
801 str = str.replace(/"/g, '""');
802 str = '"' + str + '"';
807 // sets the download file name and inserts the current CSV
808 // into a Blob URL for browser download.
809 $scope.generateCSVExportURL = function() {
810 $scope.gridColumnPickerIsOpen = false;
812 // let the file name describe the grid
813 $scope.csvExportFileName =
814 ($scope.mainLabel || grid.persistKey || 'eg_grid_data')
815 .replace(/\s+/g, '_') + '_' + $scope.page();
817 // toss the CSV into a Blob and update the export URL
818 var csv = grid.generateCSV();
819 var blob = new Blob([csv], {type : 'text/plain'});
820 $scope.csvExportURL =
821 ($window.URL || $window.webkitURL).createObjectURL(blob);
824 $scope.printCSV = function() {
825 $scope.gridColumnPickerIsOpen = false;
828 content : grid.generateCSV(),
829 content_type : 'text/plain'
833 // generates CSV for the currently visible grid contents
834 grid.generateCSV = function() {
836 var colCount = grid.columnsProvider.columns.length;
839 angular.forEach(grid.columnsProvider.columns,
841 if (!col.visible) return;
842 csvStr += grid.csvDatum(col.label);
847 csvStr = csvStr.replace(/,$/,'\n');
850 angular.forEach($scope.items, function(item) {
851 angular.forEach(grid.columnsProvider.columns,
853 if (!col.visible) return;
855 var val = grid.dataProvider.itemFieldValue(item, col);
856 // filtered value (dates, etc.)
857 val = $filter('egGridValueFilter')(val, col);
858 csvStr += grid.csvDatum(val);
862 csvStr = csvStr.replace(/,$/,'\n');
868 // Interpolate the value for column.linkpath within the context
869 // of the row item to generate the final link URL.
870 $scope.generateLinkPath = function(col, item) {
871 return egCore.strings.$replace(col.linkpath, {item : item});
874 // If a column provides its own HTML template, translate it,
875 // using the current item for the template scope.
876 // note: $sce is required to avoid security restrictions and
877 // is OK here, since the template comes directly from a
878 // local HTML template (not user input).
879 $scope.translateCellTemplate = function(col, item) {
880 var html = egCore.strings.$replace(col.template, {item : item});
881 return $sce.trustAsHtml(html);
884 $scope.collect = function() { grid.collect() }
886 // asks the dataProvider for a page of data
887 grid.collect = function() {
889 // avoid firing the collect if there is nothing to collect.
890 if (grid.selfManagedData && !grid.dataProvider.query) return;
892 if (grid.collecting) return; // avoid parallel collect()
893 grid.collecting = true;
895 console.debug('egGrid.collect() offset='
896 + grid.offset + '; limit=' + grid.limit);
898 // ensure all of our dropdowns are closed
899 // TODO: git rid of these and just use dropdown-toggle,
900 // which is more reliable.
901 $scope.gridColumnPickerIsOpen = false;
902 $scope.gridRowCountIsOpen = false;
903 $scope.gridPageSelectIsOpen = false;
906 $scope.selected = {};
907 grid.dataProvider.get(grid.offset, grid.limit).then(
909 if (grid.controls.allItemsRetrieved)
910 grid.controls.allItemsRetrieved();
915 $scope.items.push(item)
916 if (grid.controls.itemRetrieved)
917 grid.controls.itemRetrieved(item);
919 }).finally(function() {
920 console.debug('egGrid.collect() complete');
921 grid.collecting = false
931 * eg-grid-field : used for collecting custom field data from the templates.
932 * This directive does not direct display, it just passes data up to the
935 .directive('egGridField', function() {
940 name : '@', // required; unique name
941 path : '@', // optional; flesh path
942 ignore: '@', // optional; fields to ignore when path is a wildcard
943 label : '@', // optional; display label
944 flex : '@', // optional; default flex width
945 align : '@', // optional; default alignment, left/center/right
946 dateformat : '@', // optional: passed down to egGridValueFilter
948 // if a field is part of an IDL object, but we are unable to
949 // determine the class, because it's nested within a hash
950 // (i.e. we can't navigate directly to the object via the IDL),
951 // idlClass lets us specify the class. This is particularly
952 // useful for nested wildcard fields.
953 parentIdlClass : '@',
955 // optional: for non-IDL columns, specifying a datatype
956 // lets the caller control which display filter is used.
957 // datatype should match the standard IDL datatypes.
960 link : function(scope, element, attrs, egGridCtrl) {
962 // boolean fields are presented as value-less attributes
971 'required' // if set, always fetch data for this column
974 if (angular.isDefined(attrs[field]))
979 // any HTML content within the field is its custom template
980 var tmpl = element.html();
981 if (tmpl && !tmpl.match(/^\s*$/))
982 scope.template = tmpl
984 egGridCtrl.columnsProvider.add(scope);
991 * eg-grid-action : used for specifying actions which may be applied
992 * to items within the grid.
994 .directive('egGridAction', function() {
1000 group : '@', // Action group, ungrouped if not set
1001 label : '@', // Action label
1002 handler : '=', // Action function handler
1006 link : function(scope, element, attrs, egGridCtrl) {
1007 egGridCtrl.addAction({
1009 group : scope.group,
1010 label : scope.label,
1011 divider : scope.divider,
1012 handler : scope.handler
1019 .factory('egGridColumnsProvider', ['egCore', function(egCore) {
1021 function ColumnsProvider(args) {
1024 cols.stockVisible = [];
1025 cols.idlClass = args.idlClass;
1026 cols.defaultToHidden = args.defaultToHidden;
1027 cols.defaultToNoSort = args.defaultToNoSort;
1028 cols.defaultToNoMultiSort = args.defaultToNoMultiSort;
1030 // resets column width, visibility, and sort behavior
1031 // Visibility resets to the visibility settings defined in the
1032 // template (i.e. the original egGridField values).
1033 cols.reset = function() {
1034 angular.forEach(cols.columns, function(col) {
1038 if (cols.stockVisible.indexOf(col.name) > -1) {
1041 col.visible = false;
1046 // returns true if any columns are sortable
1047 cols.hasSortableColumn = function() {
1048 return cols.columns.filter(
1050 return col.sortable || col.multisortable;
1055 cols.showAllColumns = function() {
1056 angular.forEach(cols.columns, function(column) {
1057 column.visible = true;
1061 cols.hideAllColumns = function() {
1062 angular.forEach(cols.columns, function(col) {
1067 cols.indexOf = function(name) {
1068 for (var i = 0; i < cols.columns.length; i++) {
1069 if (cols.columns[i].name == name)
1075 cols.findColumn = function(name) {
1076 return cols.columns[cols.indexOf(name)];
1079 cols.compileAutoColumns = function() {
1080 var idl_class = egCore.idl.classes[cols.idlClass];
1083 idl_class.fields.sort(
1084 function(a, b) { return a.name < b.name ? -1 : 1 }),
1086 if (field.virtual) return;
1087 if (field.datatype == 'link' || field.datatype == 'org_unit') {
1088 // if the field is a link and the linked class has a
1089 // "selector" field specified, use the selector field
1090 // as the display field for the columns.
1091 // flattener will take care of the fleshing.
1092 if (field['class']) {
1093 var selector_field = egCore.idl.classes[field['class']].fields
1094 .filter(function(f) { return Boolean(f.selector) })[0];
1095 if (selector_field) {
1096 field.path = field.name + '.' + selector_field.selector;
1100 cols.add(field, true);
1105 // if a column definition has a path with a wildcard, create
1106 // columns for all non-virtual fields at the specified
1107 // position in the path.
1108 cols.expandPath = function(colSpec) {
1110 var ignoreList = [];
1112 ignoreList = colSpec.ignore.split(' ');
1114 var dotpath = colSpec.path.replace(/\.?\*$/,'');
1118 if (colSpec.parentIdlClass) {
1119 class_obj = egCore.idl.classes[colSpec.parentIdlClass];
1121 class_obj = egCore.idl.classes[cols.idlClass];
1124 if (!class_obj) return;
1126 console.debug('egGrid: auto dotpath is: ' + dotpath);
1127 var path_parts = dotpath.split(/\./);
1129 // find the IDL class definition for the last element in the
1130 // path before the .*
1131 // an empty path_parts means expand the root class
1133 for (var path_idx in path_parts) {
1134 var part = path_parts[path_idx];
1135 idl_field = class_obj.field_map[part];
1137 // unless we're at the end of the list, this field should
1138 // link to another class.
1139 if (idl_field && idl_field['class'] && (
1140 idl_field.datatype == 'link' ||
1141 idl_field.datatype == 'org_unit')) {
1142 class_obj = egCore.idl.classes[idl_field['class']];
1144 if (path_idx < (path_parts.length - 1)) {
1145 // we ran out of classes to hop through before
1146 // we ran out of path components
1147 console.error("egGrid: invalid IDL path: " + dotpath);
1154 angular.forEach(class_obj.fields, function(field) {
1156 // Only show wildcard fields where we have data to show
1157 // Virtual and un-fleshed links will not have any data.
1158 if (field.virtual ||
1159 (field.datatype == 'link' || field.datatype == 'org_unit') ||
1160 ignoreList.indexOf(field.name) > -1
1164 var col = cols.cloneFromScope(colSpec);
1165 col.path = (dotpath ? dotpath + '.' + field.name : field.name);
1166 console.debug('egGrid: field: ' +field.name + '; parent field: ' + js2JSON(idl_field));
1167 cols.add(col, false, true,
1168 {idl_parent : idl_field, idl_field : field, idl_class : class_obj});
1171 cols.columns = cols.columns.sort(
1173 if (a.explicit) return -1;
1174 if (b.explicit) return 1;
1175 if (a.idlclass && b.idlclass) {
1176 return a.idlclass < b.idlclass ? -1 : 1;
1177 return a.idlclass > b.idlclass ? 1 : -1;
1179 if (a.path && b.path) {
1180 return a.path < b.path ? -1 : 1;
1181 return a.path > b.path ? 1 : -1;
1184 return a.label < b.label ? -1 : 1;
1191 "egGrid: wildcard path does not resolve to an object: "
1196 // angular.clone(scopeObject) is not permittable. Manually copy
1197 // the fields over that we need (so the scope object can go away).
1198 cols.cloneFromScope = function(colSpec) {
1200 name : colSpec.name,
1201 label : colSpec.label,
1202 path : colSpec.path,
1203 align : colSpec.align || 'left',
1204 flex : Number(colSpec.flex) || 2,
1205 sort : Number(colSpec.sort) || 0,
1206 required : colSpec.required,
1207 linkpath : colSpec.linkpath,
1208 template : colSpec.template,
1209 visible : colSpec.visible,
1210 hidden : colSpec.hidden,
1211 datatype : colSpec.datatype,
1212 sortable : colSpec.sortable,
1213 nonsortable : colSpec.nonsortable,
1214 multisortable : colSpec.multisortable,
1215 nonmultisortable : colSpec.nonmultisortable,
1216 dateformat : colSpec.dateformat,
1217 parentIdlClass : colSpec.parentIdlClass
1222 // Add a column to the columns collection.
1223 // Columns may come from a slim eg-columns-field or
1224 // directly from the IDL.
1225 cols.add = function(colSpec, fromIDL, fromExpand, idl_info) {
1227 // First added column with the specified path takes precedence.
1228 // This allows for specific definitions followed by wildcard
1229 // definitions. If a match is found, back out.
1230 if (cols.columns.filter(function(c) {
1231 return (c.path == colSpec.path) })[0]) {
1232 console.debug('skipping pre-existing column ' + colSpec.path);
1236 var column = fromExpand ? colSpec : cols.cloneFromScope(colSpec);
1238 if (column.path && column.path.match(/\*$/))
1239 return cols.expandPath(colSpec);
1241 if (!fromExpand) column.explicit = true;
1243 if (!column.name) column.name = column.path;
1244 if (!column.path) column.path = column.name;
1246 if (column.visible || (!cols.defaultToHidden && !column.hidden))
1247 column.visible = true;
1249 if (column.sortable || (!cols.defaultToNoSort && !column.nonsortable))
1250 column.sortable = true;
1252 if (column.multisortable ||
1253 (!cols.defaultToNoMultiSort && !column.nonmultisortable))
1254 column.multisortable = true;
1256 cols.columns.push(column);
1258 // Track which columns are visible by default in case we
1259 // need to reset column visibility
1261 cols.stockVisible.push(column.name);
1263 if (fromIDL) return; // directly from egIDL. nothing left to do.
1265 // lookup the matching IDL field
1266 if (!idl_info && cols.idlClass)
1267 idl_info = cols.idlFieldFromPath(column.path);
1270 // column is not represented within the IDL
1271 column.adhoc = true;
1275 column.datatype = idl_info.idl_field.datatype;
1277 if (!column.label) {
1278 column.label = idl_info.idl_field.label || column.name;
1281 if (fromExpand && idl_info.idl_class) {
1282 column.idlclass = '';
1283 if (idl_info.idl_parent) {
1284 column.idlclass = idl_info.idl_parent.label || idl_info.idl_parent.name;
1286 column.idlclass += idl_info.idl_class.label || idl_info.idl_class.name;
1291 // finds the IDL field from the dotpath, using the columns
1292 // idlClass as the base.
1293 cols.idlFieldFromPath = function(dotpath) {
1294 var class_obj = egCore.idl.classes[cols.idlClass];
1295 var path_parts = dotpath.split(/\./);
1299 for (var path_idx in path_parts) {
1300 var part = path_parts[path_idx];
1301 idl_parent = idl_field;
1302 idl_field = class_obj.field_map[part];
1304 if (idl_field && idl_field['class'] && (
1305 idl_field.datatype == 'link' ||
1306 idl_field.datatype == 'org_unit')) {
1307 class_obj = egCore.idl.classes[idl_field['class']];
1309 // else, path is not in the IDL, which is fine
1312 if (!idl_field) return null;
1315 idl_parent: idl_parent,
1316 idl_field : idl_field,
1317 idl_class : class_obj
1323 instance : function(args) { return new ColumnsProvider(args) }
1329 * Generic data provider template class. This is basically an abstract
1330 * class factory service whose instances can be locally modified to
1331 * meet the needs of each individual grid.
1333 .factory('egGridDataProvider',
1334 ['$q','$timeout','$filter','egCore',
1335 function($q , $timeout , $filter , egCore) {
1337 function GridDataProvider(args) {
1338 var gridData = this;
1339 if (!args) args = {};
1342 gridData.get = args.get;
1343 gridData.query = args.query;
1344 gridData.idlClass = args.idlClass;
1345 gridData.columnsProvider = args.columnsProvider;
1347 // Delivers a stream of array data via promise.notify()
1348 // Useful for passing an array of data to egGrid.get()
1349 // If a count is provided, the array will be trimmed to
1350 // the range defined by count and offset
1351 gridData.arrayNotifier = function(arr, offset, count) {
1352 if (!arr || arr.length == 0) return $q.when();
1353 if (count) arr = arr.slice(offset, offset + count);
1354 var def = $q.defer();
1355 // promise notifications are only witnessed when delivered
1356 // after the caller has his hands on the promise object
1357 $timeout(function() {
1358 angular.forEach(arr, def.notify);
1364 // Calls the grid refresh function. Once instantiated, the
1365 // grid will replace this function with it's own refresh()
1366 gridData.refresh = function(noReset) { }
1368 if (!gridData.get) {
1369 // returns a promise whose notify() delivers items
1370 gridData.get = function(index, count) {
1371 console.error("egGridDataProvider.get() not implemented");
1375 // attempts a flat field lookup first. If the column is not
1376 // found on the top-level object, attempts a nested lookup
1377 // TODO: consider a caching layer to speed up template
1378 // rendering, particularly for nested objects?
1379 gridData.itemFieldValue = function(item, column) {
1380 if (column.name in item) {
1381 if (typeof item[column.name] == 'function') {
1382 return item[column.name]();
1384 return item[column.name];
1387 return gridData.nestedItemFieldValue(item, column);
1391 // TODO: deprecate me
1392 gridData.flatItemFieldValue = function(item, column) {
1393 console.warn('gridData.flatItemFieldValue deprecated; '
1394 + 'leave provider.itemFieldValue unset');
1395 return item[column.name];
1398 // given an object and a dot-separated path to a field,
1399 // extract the value of the field. The path can refer
1400 // to function names or object attributes. If the final
1401 // value is an IDL field, run the value through its
1402 // corresponding output filter.
1403 gridData.nestedItemFieldValue = function(obj, column) {
1404 if (obj === null || obj === undefined || obj === '') return '';
1405 if (!column.path) return obj;
1408 var parts = column.path.split('.');
1410 angular.forEach(parts, function(step, idx) {
1411 // object is not fleshed to the expected extent
1412 if (!obj || typeof obj != 'object') {
1417 var cls = obj.classname;
1418 if (cls && (class_obj = egCore.idl.classes[cls])) {
1419 idl_field = class_obj.field_map[step];
1420 obj = obj[step] ? obj[step]() : '';
1422 if (angular.isFunction(obj[step])) {
1430 // We found a nested IDL object which may or may not have
1431 // been configured as a top-level column. Grab the datatype.
1432 if (idl_field && !column.datatype)
1433 column.datatype = idl_field.datatype;
1435 if (obj === null || obj === undefined || obj === '') return '';
1441 instance : function(args) {
1442 return new GridDataProvider(args);
1449 // Factory service for egGridDataManager instances, which are
1450 // responsible for collecting flattened grid data.
1451 .factory('egGridFlatDataProvider',
1452 ['$q','egCore','egGridDataProvider',
1453 function($q , egCore , egGridDataProvider) {
1456 instance : function(args) {
1457 var provider = egGridDataProvider.instance(args);
1459 provider.get = function(offset, count) {
1461 // no query means no call
1462 if (!provider.query ||
1463 angular.equals(provider.query, {}))
1466 // find all of the currently visible columns
1467 var queryFields = {}
1468 angular.forEach(provider.columnsProvider.columns,
1470 // only query IDL-tracked columns
1471 if (!col.adhoc && (col.required || col.visible))
1472 queryFields[col.name] = col.path;
1476 return egCore.net.request(
1478 'open-ils.fielder.flattened_search',
1479 egCore.auth.token(), provider.idlClass,
1480 queryFields, provider.query,
1481 { sort : provider.sort,
1487 //provider.itemFieldValue = provider.flatItemFieldValue;
1494 .directive('egGridColumnDragSource', function() {
1497 require : '^egGrid',
1498 link : function(scope, element, attrs, egGridCtrl) {
1499 angular.element(element).attr('draggable', 'true');
1501 element.bind('dragstart', function(e) {
1502 egGridCtrl.dragColumn = attrs.column;
1503 egGridCtrl.dragType = attrs.dragType || 'move'; // or resize
1504 egGridCtrl.colResizeDir = 0;
1506 if (egGridCtrl.dragType == 'move') {
1507 // style the column getting moved
1508 angular.element(e.target).addClass(
1509 'eg-grid-column-move-handle-active');
1513 element.bind('dragend', function(e) {
1514 if (egGridCtrl.dragType == 'move') {
1515 angular.element(e.target).removeClass(
1516 'eg-grid-column-move-handle-active');
1523 .directive('egGridColumnDragDest', function() {
1526 require : '^egGrid',
1527 link : function(scope, element, attrs, egGridCtrl) {
1529 element.bind('dragover', function(e) { // required for drop
1530 e.stopPropagation();
1532 e.dataTransfer.dropEffect = 'move';
1534 if (egGridCtrl.colResizeDir == 0) return; // move
1536 var cols = egGridCtrl.columnsProvider;
1537 var srcCol = egGridCtrl.dragColumn;
1538 var srcColIdx = cols.indexOf(srcCol);
1540 if (egGridCtrl.colResizeDir == -1) {
1541 if (cols.indexOf(attrs.column) <= srcColIdx) {
1542 egGridCtrl.modifyColumnFlex(
1543 egGridCtrl.columnsProvider.findColumn(
1544 egGridCtrl.dragColumn), -1);
1545 if (cols.columns[srcColIdx+1]) {
1546 // source column shrinks by one, column to the
1547 // right grows by one.
1548 egGridCtrl.modifyColumnFlex(
1549 cols.columns[srcColIdx+1], 1);
1554 if (cols.indexOf(attrs.column) > srcColIdx) {
1555 egGridCtrl.modifyColumnFlex(
1556 egGridCtrl.columnsProvider.findColumn(
1557 egGridCtrl.dragColumn), 1);
1558 if (cols.columns[srcColIdx+1]) {
1559 // source column grows by one, column to the
1560 // right grows by one.
1561 egGridCtrl.modifyColumnFlex(
1562 cols.columns[srcColIdx+1], -1);
1570 element.bind('dragenter', function(e) {
1571 e.stopPropagation();
1573 if (egGridCtrl.dragType == 'move') {
1574 angular.element(e.target).addClass('eg-grid-col-hover');
1576 // resize grips are on the right side of each column.
1577 // dragenter will either occur on the source column
1578 // (dragging left) or the column to the right.
1579 if (egGridCtrl.colResizeDir == 0) {
1580 if (egGridCtrl.dragColumn == attrs.column) {
1581 egGridCtrl.colResizeDir = -1; // west
1583 egGridCtrl.colResizeDir = 1; // east
1589 element.bind('dragleave', function(e) {
1590 e.stopPropagation();
1592 if (egGridCtrl.dragType == 'move') {
1593 angular.element(e.target).removeClass('eg-grid-col-hover');
1597 element.bind('drop', function(e) {
1598 e.stopPropagation();
1600 egGridCtrl.colResizeDir = 0;
1601 if (egGridCtrl.dragType == 'move') {
1602 angular.element(e.target).removeClass('eg-grid-col-hover');
1603 egGridCtrl.onColumnDrop(attrs.column); // move the column
1610 .directive('egGridMenuItem', function() {
1613 require : '^egGrid',
1619 handler : '=', // onclick handler function
1620 divider : '=', // if true, show a divider only
1621 handlerData : '=', // if set, passed as second argument to handler
1622 disabled : '=', // function
1623 hidden : '=' // function
1625 link : function(scope, element, attrs, egGridCtrl) {
1626 egGridCtrl.addMenuItem({
1627 checkbox : scope.checkbox,
1628 checked : scope.checked ? true : false,
1629 label : scope.label,
1630 standalone : scope.standalone ? true : false,
1631 handler : scope.handler,
1632 divider : scope.divider,
1633 disabled : scope.disabled,
1634 hidden : scope.hidden,
1635 handlerData : scope.handlerData
1645 * Translates bare IDL object values into display values.
1646 * 1. Passes dates through the angular date filter
1647 * 2. Translates bools to Booleans so the browser can display translated
1648 * value. (Though we could manually translate instead..)
1649 * Others likely to follow...
1651 .filter('egGridValueFilter', ['$filter', function($filter) {
1652 return function(value, column) {
1653 switch(column.datatype) {
1656 // Browser will translate true/false for us
1658 case '1' : // legacy
1662 case '0' : // legacy
1665 // value may be null, '', etc.
1666 default : return '';
1669 // canned angular date filter FTW
1670 if (!column.dateformat)
1671 column.dateformat = 'shortDate';
1672 return $filter('date')(value, column.dateformat);
1674 return $filter('currency')(value);