2 * Collection of grid related classses and interfaces.
4 import {TemplateRef, EventEmitter, QueryList} from '@angular/core';
5 import {Observable, Subscription, empty} from 'rxjs';
6 import {IdlService, IdlObject} from '@eg/core/idl.service';
7 import {OrgService} from '@eg/core/org.service';
8 import {ServerStoreService} from '@eg/core/server-store.service';
9 import {FormatService} from '@eg/core/format.service';
10 import {Pager} from '@eg/share/util/pager';
11 import {GridFilterControlComponent} from './grid-filter-control.component';
13 const MAX_ALL_ROW_COUNT = 10000;
15 export class GridColumn {
24 // IDL class of the object which contains this field.
25 // Not to be confused with the class of a linked object.
29 datePlusTime: boolean;
31 timezoneContextOrg: number;
32 cellTemplate: TemplateRef<any>;
33 dateOnlyIntervalField: string;
37 isDragTarget: boolean;
39 isFilterable: boolean;
41 isMultiSortable: boolean;
42 disableTooltip: boolean;
43 asyncSupportsEmptyTermClick: boolean;
44 comparator: (valueA: any, valueB: any) => number;
47 // True if the column was automatically generated.
52 filterOperator: string;
53 filterInputDisabled: boolean;
54 filterIncludeOrgAncestors: boolean;
55 filterIncludeOrgDescendants: boolean;
57 flesher: (obj: any, col: GridColumn, item: any) => any;
59 getCellContext(row: any) {
63 userContext: this.cellContext
72 this.isFiltered = false;
73 this.filterValue = undefined;
74 this.filterOperator = '=';
75 this.filterInputDisabled = false;
76 this.filterIncludeOrgAncestors = false;
77 this.filterIncludeOrgDescendants = false;
81 const col = new GridColumn();
85 col.label = this.label;
87 col.required = this.required;
88 col.hidden = this.hidden;
89 col.asyncSupportsEmptyTermClick = this.asyncSupportsEmptyTermClick;
90 col.isIndex = this.isIndex;
91 col.cellTemplate = this.cellTemplate;
92 col.cellContext = this.cellContext;
93 col.disableTooltip = this.disableTooltip;
94 col.isSortable = this.isSortable;
95 col.isFilterable = this.isFilterable;
96 col.isMultiSortable = this.isMultiSortable;
97 col.datatype = this.datatype;
98 col.datePlusTime = this.datePlusTime;
99 col.ternaryBool = this.ternaryBool;
100 col.timezoneContextOrg = this.timezoneContextOrg;
101 col.idlClass = this.idlClass;
102 col.isAuto = this.isAuto;
109 export class GridColumnSet {
110 columns: GridColumn[];
112 indexColumn: GridColumn;
114 isFilterable: boolean;
115 isMultiSortable: boolean;
116 stockVisible: string[];
118 defaultHiddenFields: string[];
119 defaultVisibleFields: string[];
121 constructor(idl: IdlService, idlClass?: string) {
124 this.stockVisible = [];
125 this.idlClass = idlClass;
128 add(col: GridColumn) {
130 if (col.path && col.path.match(/\*$/)) {
131 return this.generateWildcardColumns(col);
134 this.applyColumnDefaults(col);
136 if (!this.insertColumn(col)) {
137 // Column was rejected as a duplicate.
141 if (col.isIndex) { this.indexColumn = col; }
143 // track which fields are visible on page load.
145 this.stockVisible.push(col.name);
148 this.applyColumnSortability(col);
149 this.applyColumnFilterability(col);
152 generateWildcardColumns(col: GridColumn) {
154 const dotpath = col.path.replace(/\.?\*$/, '');
155 let classObj, idlField;
158 classObj = this.idl.classes[col.idlClass];
160 classObj = this.idl.classes[this.idlClass];
163 if (!classObj) { return; }
165 const pathParts = dotpath.split(/\./);
167 let oldFieldLabel = '';
169 // find the IDL class definition for the last element in the
170 // path before the .*
171 // An empty pathParts means expand the root class
172 pathParts.forEach((part, pathIdx) => {
174 idlField = classObj.field_map[part];
176 // unless we're at the end of the list, this field should
177 // link to another class.
178 if (idlField && idlField['class'] && (
179 idlField.datatype === 'link' || idlField.datatype === 'org_unit')) {
181 if (oldFieldLabel) { oldFieldLabel += ' : '; }
183 oldFieldLabel += idlField.label;
184 classObj = this.idl.classes[idlField['class']];
187 if (pathIdx < (pathParts.length - 1)) {
188 // we ran out of classes to hop through before
189 // we ran out of path components
190 console.warn('Grid: invalid IDL path: ' + dotpath);
197 'Grid: wildcard path does not resolve to an object:' + dotpath);
201 classObj.fields.forEach(field => {
203 // Only show wildcard fields where we have data to show
204 // Virtual and un-fleshed links will not have any data.
206 field.datatype === 'link' || field.datatype === 'org_unit') {
210 const newCol = col.clone();
211 newCol.isAuto = true;
212 newCol.path = dotpath ? dotpath + '.' + field.name : field.name;
213 newCol.label = dotpath ? classObj.label + ': ' + field.label : field.label;
219 // Returns true if the new column was inserted, false otherwise.
220 // Declared columns take precedence over auto-generated columns
221 // when collisions occur.
222 // Declared columns are inserted in front of auto columns.
223 insertColumn(col: GridColumn): boolean {
226 if (this.getColByName(col.name) || this.getColByPath(col.path)) {
227 // New auto-generated column conflicts with existing
231 // No collisions. Add to the end of the list
232 this.columns.push(col);
237 // Adding a declared column.
240 for (let idx = 0; idx < this.columns.length; idx++) {
241 const testCol = this.columns[idx];
242 if (testCol.name === col.name) { // match found
243 if (testCol.isAuto) {
244 // new column takes precedence, remove the existing column.
245 this.columns.splice(idx, 1);
248 // New column does not take precedence. Avoid
255 // Delcared columns are inserted just before the first auto-column
256 for (let idx = 0; idx < this.columns.length; idx++) {
257 const testCol = this.columns[idx];
258 if (testCol.isAuto) {
260 this.columns.unshift(col);
262 this.columns.splice(idx, 0, col);
268 // No insertion point found. Toss the new column on the end.
269 this.columns.push(col);
273 getColByName(name: string): GridColumn {
274 return this.columns.filter(c => c.name === name)[0];
277 getColByPath(path: string): GridColumn {
279 return this.columns.filter(c => c.path === path)[0];
283 idlInfoFromDotpath(dotpath: string): any {
284 if (!dotpath || !this.idlClass) { return null; }
289 let nextIdlClass = this.idl.classes[this.idlClass];
291 const pathParts = dotpath.split(/\./);
293 for (let i = 0; i < pathParts.length; i++) {
295 const part = pathParts[i];
296 idlParent = idlField;
297 idlClass = nextIdlClass;
298 idlField = idlClass.field_map[part];
300 if (!idlField) { return null; } // invalid IDL path
302 if (i === pathParts.length - 1) {
303 // No more links to process.
307 if (idlField['class'] && (
308 idlField.datatype === 'link' ||
309 idlField.datatype === 'org_unit')) {
310 // The link class on the current field refers to the
311 // class of the link destination, not the current field.
312 // Mark it for processing during the next iteration.
313 nextIdlClass = this.idl.classes[idlField['class']];
318 idlParent: idlParent,
326 this.columns.forEach(col => {
330 col.visible = this.stockVisible.includes(col.name);
334 applyColumnDefaults(col: GridColumn) {
336 if (!col.idlFieldDef) {
337 const idlInfo = this.idlInfoFromDotpath(col.path || col.name);
339 col.idlFieldDef = idlInfo.idlField;
340 col.idlClass = idlInfo.idlClass.name;
342 col.datatype = col.idlFieldDef.datatype;
345 col.label = col.idlFieldDef.label || col.idlFieldDef.name;
350 if (!col.name) { col.name = col.path; }
351 if (!col.flex) { col.flex = 2; }
352 if (!col.align) { col.align = 'left'; }
353 if (!col.label) { col.label = col.name; }
354 if (!col.datatype) { col.datatype = 'text'; }
356 col.visible = !col.hidden;
359 applyColumnSortability(col: GridColumn) {
360 // column sortability defaults to the sortability of the column set.
361 if (col.isSortable === undefined && this.isSortable) {
362 col.isSortable = true;
365 if (col.isMultiSortable === undefined && this.isMultiSortable) {
366 col.isMultiSortable = true;
369 if (col.isMultiSortable) {
370 col.isSortable = true;
373 applyColumnFilterability(col: GridColumn) {
374 // column filterability defaults to the afilterability of the column set.
375 if (col.isFilterable === undefined && this.isFilterable) {
376 col.isFilterable = true;
380 displayColumns(): GridColumn[] {
381 return this.columns.filter(c => c.visible);
384 // Sorted visible columns followed by sorted non-visible columns.
385 // Note we don't sort this.columns directly as it would impact
386 // grid column display ordering.
387 sortForColPicker(): GridColumn[] {
388 const visible = this.columns.filter(c => c.visible);
389 const invisible = this.columns.filter(c => !c.visible);
391 visible.sort((a, b) => a.label < b.label ? -1 : 1);
392 invisible.sort((a, b) => a.label < b.label ? -1 : 1);
394 return visible.concat(invisible);
397 requiredColumns(): GridColumn[] {
398 const visible = this.displayColumns();
399 return visible.concat(
400 this.columns.filter(c => c.required && !c.visible));
403 insertBefore(source: GridColumn, target: GridColumn) {
406 this.columns.forEach((col, idx) => {
407 if (col.name === target.name) { targetIdx = idx; }});
409 this.columns.forEach((col, idx) => {
410 if (col.name === source.name) { sourceIdx = idx; }});
412 if (sourceIdx >= 0) {
413 this.columns.splice(sourceIdx, 1);
416 this.columns.splice(targetIdx, 0, source);
419 // Move visible columns to the front of the list.
420 moveVisibleToFront() {
421 const newCols = this.displayColumns();
422 this.columns.forEach(col => {
423 if (!col.visible) { newCols.push(col); }});
424 this.columns = newCols;
427 moveColumn(col: GridColumn, diff: number) {
428 let srcIdx, targetIdx;
430 this.columns.forEach((c, i) => {
431 if (c.name === col.name) { srcIdx = i; }
434 targetIdx = srcIdx + diff;
437 } else if (targetIdx >= this.columns.length) {
438 // Target index follows the last visible column.
440 this.columns.forEach((c, idx) => {
441 if (c.visible) { lastVisible = idx; }
444 // When moving a column (down) causes one or more
445 // visible columns to shuffle forward, our column
446 // moves into the slot of the last visible column.
447 // Otherwise, put it into the slot directly following
448 // the last visible column.
449 targetIdx = srcIdx <= lastVisible ? lastVisible : lastVisible + 1;
452 // Splice column out of old position, insert at new position.
453 this.columns.splice(srcIdx, 1);
454 this.columns.splice(targetIdx, 0, col);
457 compileSaveObject(): GridColumnPersistConf[] {
458 // only store information about visible columns.
459 // scrunch the data down to just the needed info.
460 return this.displayColumns().map(col => {
461 const c: GridColumnPersistConf = {name : col.name};
462 if (col.align !== 'left') { c.align = col.align; }
463 if (col.flex !== 2) { c.flex = Number(col.flex); }
464 if (Number(col.sort)) { c.sort = Number(col.sort); }
469 applyColumnSettings(conf: GridColumnPersistConf[]) {
471 if (!conf || conf.length === 0) {
472 // No configuration is available, but we have a list of
473 // fields to show or hide by default
475 if (this.defaultVisibleFields) {
476 this.columns.forEach(col => {
477 if (this.defaultVisibleFields.includes(col.name)) {
484 } else if (this.defaultHiddenFields) {
485 this.defaultHiddenFields.forEach(name => {
486 const col = this.getColByName(name);
498 conf.forEach(colConf => {
499 const col = this.getColByName(colConf.name);
500 if (!col) { return; } // no such column in this grid.
503 if (colConf.align) { col.align = colConf.align; }
504 if (colConf.flex) { col.flex = Number(colConf.flex); }
505 if (colConf.sort) { col.sort = Number(colConf.sort); }
507 // Add to new columns array, avoid dupes.
508 if (newCols.filter(c => c.name === col.name).length === 0) {
513 // columns which are not expressed within the saved
514 // configuration are marked as non-visible and
515 // appended to the end of the new list of columns.
516 this.columns.forEach(c => {
517 if (conf.filter(cf => cf.name === c.name).length === 0) {
523 this.columns = newCols;
527 // Maps colunm names to functions which return plain text values for
528 // each mapped column on a given row. This is primarily useful for
529 // generating print-friendly content for grid cells rendered via
532 // USAGE NOTE: Since a cellTemplate can be passed arbitrary context
533 // but a GridCellTextGenerator only gets the row object,
534 // if it's important to include content that's not available
535 // by default in the row object, you may want to stick
536 // it in the row object as an additional attribute.
538 export interface GridCellTextGenerator {
539 [columnName: string]: (row: any) => string;
542 export class GridRowSelector {
543 indexes: {[string: string]: boolean};
545 // Track these so we can emit the selectionChange event
546 // only when the selection actually changes.
547 previousSelection: string[] = [];
549 // Emits the selected indexes on selection change
550 selectionChange: EventEmitter<string[]> = new EventEmitter<string[]>();
556 // Returns true if all of the requested indexes exist in the selector.
557 contains(index: string | string[]): boolean {
558 const indexes = [].concat(index);
559 for (let i = 0; i < indexes.length; i++) { // early exit
560 if (!this.indexes[indexes[i]]) {
568 const keys = this.selected();
570 if (keys.length === this.previousSelection.length &&
571 this.contains(this.previousSelection)) {
572 return; // No change has occurred
575 this.previousSelection = keys;
576 this.selectionChange.emit(keys);
579 select(index: string | string[]) {
580 const indexes = [].concat(index);
581 indexes.forEach(i => this.indexes[i] = true);
585 deselect(index: string | string[]) {
586 const indexes = [].concat(index);
587 indexes.forEach(i => delete this.indexes[i]);
591 toggle(index: string) {
592 if (this.indexes[index]) {
593 this.deselect(index);
599 selected(): string[] {
600 return Object.keys(this.indexes);
604 return this.selected().length === 0;
613 export interface GridRowFlairEntry {
614 icon: string; // name of material icon
615 title?: string; // tooltip string
618 export class GridColumnPersistConf {
625 export class GridPersistConf {
628 columns: GridColumnPersistConf[];
629 hideToolbarActions: string[];
632 export class GridContext {
637 isFilterable: boolean;
638 stickyGridHeader: boolean;
639 isMultiSortable: boolean;
640 useLocalSort: boolean;
642 disableMultiSelect: boolean;
643 disableSelect: boolean;
644 dataSource: GridDataSource;
645 columnSet: GridColumnSet;
646 autoGeneratedColumnOrder: string;
647 rowSelector: GridRowSelector;
648 toolbarLabel: string;
649 toolbarButtons: GridToolbarButton[];
650 toolbarCheckboxes: GridToolbarCheckbox[];
651 toolbarActions: GridToolbarAction[];
652 lastSelectedIndex: any;
653 pageChanges: Subscription;
654 rowFlairIsEnabled: boolean;
655 rowFlairCallback: (row: any) => GridRowFlairEntry;
656 rowClassCallback: (row: any) => string;
657 cellClassCallback: (row: any, col: GridColumn) => string;
658 defaultVisibleFields: string[];
659 defaultHiddenFields: string[];
660 ignoredFields: string[];
661 overflowCells: boolean;
662 disablePaging: boolean;
663 showDeclaredFieldsOnly: boolean;
664 cellTextGenerator: GridCellTextGenerator;
665 reloadOnColumnChange: boolean;
667 // Allow calling code to know when the select-all-rows-in-page
668 // action has occurred.
669 selectRowsInPageEmitter: EventEmitter<void>;
671 filterControls: QueryList<GridFilterControlComponent>;
673 // Services injected by our grid component
676 store: ServerStoreService;
677 format: FormatService;
682 store: ServerStoreService,
683 format: FormatService) {
688 this.format = format;
689 this.pager = new Pager();
690 this.rowSelector = new GridRowSelector();
691 this.toolbarButtons = [];
692 this.toolbarCheckboxes = [];
693 this.toolbarActions = [];
697 this.selectRowsInPageEmitter = new EventEmitter<void>();
698 this.columnSet = new GridColumnSet(this.idl, this.idlClass);
699 this.columnSet.isSortable = this.isSortable === true;
700 this.columnSet.isFilterable = this.isFilterable === true;
701 this.columnSet.isMultiSortable = this.isMultiSortable === true;
702 this.columnSet.defaultHiddenFields = this.defaultHiddenFields;
703 this.columnSet.defaultVisibleFields = this.defaultVisibleFields;
704 if (!this.pager.limit) {
705 this.pager.limit = this.disablePaging ? MAX_ALL_ROW_COUNT : 10;
707 this.generateColumns();
710 // Load initial settings and data.
712 this.applyGridConfig()
713 .then(ok => this.dataSource.requestPage(this.pager))
714 .then(ok => this.listenToPager());
721 applyGridConfig(): Promise<void> {
722 return this.getGridConfig(this.persistKey)
726 columns = conf.columns;
727 if (conf.limit && !this.disablePaging) {
728 this.pager.limit = conf.limit;
730 this.applyToolbarActionVisibility(conf.hideToolbarActions);
733 // This is called regardless of the presence of saved
734 // settings so defaults can be applied.
735 this.columnSet.applyColumnSettings(columns);
739 applyToolbarActionVisibility(hidden: string[]) {
740 if (!hidden || hidden.length === 0) { return; }
743 this.toolbarActions.forEach(action => {
744 if (action.isGroup) {
746 } else if (!action.isSeparator) {
747 action.hidden = hidden.includes(action.label);
751 // If all actions in a group are hidden, hide the group as well.
752 // Note the group may be marked as hidden in the configuration,
753 // but the addition of new entries within a group should cause
754 // it to be visible again.
755 groups.forEach(group => {
756 const visible = this.toolbarActions
757 .filter(action => action.group === group.label && !action.hidden);
758 group.hidden = visible.length === 0;
763 // Give the UI time to settle before reloading grid data.
764 // This can help when data retrieval depends on a value
765 // getting modified by an angular digest cycle.
768 this.dataSource.reset();
769 this.dataSource.requestPage(this.pager);
773 reloadWithoutPagerReset() {
775 this.dataSource.reset();
776 this.dataSource.requestPage(this.pager);
780 // Sort the existing data source instead of requesting sorted
781 // data from the client. Reset pager to page 1. As with reload(),
782 // give the client a chance to setting before redisplaying.
786 this.sortLocalData();
787 this.dataSource.requestPage(this.pager);
791 // Subscribe or unsubscribe to page-change events from the pager.
793 if (this.pageChanges) { return; }
794 this.pageChanges = this.pager.onChange$.subscribe(
795 val => this.dataSource.requestPage(this.pager));
799 if (!this.pageChanges) { return; }
800 this.pageChanges.unsubscribe();
801 this.pageChanges = null;
804 // Sort data in the data source array
807 const sortDefs = this.dataSource.sort.map(sort => {
808 const column = this.columnSet.getColByName(sort.name);
816 if (!def.col.comparator) {
817 switch (def.col.datatype) {
821 def.col.comparator = (a, b) => {
824 if (a < b) { return -1; }
825 if (a > b) { return 1; }
830 def.col.comparator = (a, b) => {
831 if (a < b) { return -1; }
832 if (a > b) { return 1; }
841 this.dataSource.data.sort((rowA, rowB) => {
843 for (let idx = 0; idx < sortDefs.length; idx++) {
844 const sortDef = sortDefs[idx];
846 const valueA = this.getRowColumnValue(rowA, sortDef.col);
847 const valueB = this.getRowColumnValue(rowB, sortDef.col);
849 if (valueA === '' && valueB === '') { continue; }
850 if (valueA === '' && valueB !== '') { return 1; }
851 if (valueA !== '' && valueB === '') { return -1; }
853 const diff = sortDef.col.comparator(valueA, valueB);
854 if (diff === 0) { continue; }
856 return sortDef.dir === 'DESC' ? -diff : diff;
859 return 0; // No differences found.
863 getRowIndex(row: any): any {
864 const col = this.columnSet.indexColumn;
866 throw new Error('grid index column required');
868 return this.getRowColumnValue(row, col);
871 // Returns position in the data source array of the row with
872 // the provided index.
873 getRowPosition(index: any): number {
874 // for-loop for early exit
875 for (let idx = 0; idx < this.dataSource.data.length; idx++) {
876 const row = this.dataSource.data[idx];
877 if (row !== undefined && index === this.getRowIndex(row)) {
883 // Return the row with the provided index.
884 getRowByIndex(index: any): any {
885 for (let idx = 0; idx < this.dataSource.data.length; idx++) {
886 const row = this.dataSource.data[idx];
887 if (row !== undefined && index === this.getRowIndex(row)) {
893 // Returns all selected rows, regardless of whether they are
894 // currently visible in the grid display.
895 // De-selects previously selected rows which are no longer
896 // present in the grid.
897 getSelectedRows(): any[] {
901 this.rowSelector.selected().forEach(index => {
902 const row = this.getRowByIndex(index);
910 this.rowSelector.deselect(deleted);
914 rowIsSelected(row: any): boolean {
915 const index = this.getRowIndex(row);
916 return this.rowSelector.selected().filter(
921 getRowColumnBareValue(row: any, col: GridColumn): any {
922 if (col.name in row) {
923 return this.getObjectFieldValue(row, col.name);
924 } else if (col.path) {
925 return this.nestedItemFieldValue(row, col);
929 getRowColumnValue(row: any, col: GridColumn): any {
930 const val = this.getRowColumnBareValue(row, col);
932 if (col.datatype === 'bool') {
933 // Avoid string-ifying bools so we can use an <eg-bool/>
934 // in the grid template.
939 const intField = col.dateOnlyIntervalField;
942 this.columnSet.columns.filter(c => c.path === intField)[0];
944 interval = this.getRowColumnBareValue(row, intCol);
948 return this.format.transform({
950 idlClass: col.idlClass,
951 idlField: col.idlFieldDef ? col.idlFieldDef.name : col.name,
952 datatype: col.datatype,
953 datePlusTime: Boolean(col.datePlusTime),
954 timezoneContextOrg: Number(col.timezoneContextOrg),
955 dateOnlyInterval: interval
959 getObjectFieldValue(obj: any, name: string): any {
960 if (typeof obj[name] === 'function') {
967 nestedItemFieldValue(obj: any, col: GridColumn): string {
971 const original = obj;
972 const steps = col.path.split('.');
974 for (let i = 0; i < steps.length; i++) {
975 const step = steps[i];
977 if (obj === null || obj === undefined || typeof obj !== 'object') {
978 // We have run out of data to step through before
979 // reaching the end of the path. Conclude fleshing via
980 // callback if provided then exit.
981 if (col.flesher && obj !== undefined) {
982 return col.flesher(obj, col, original);
987 const class_ = obj.classname;
988 if (class_ && (idlClassDef = this.idl.classes[class_])) {
989 idlField = idlClassDef.field_map[step];
992 obj = this.getObjectFieldValue(obj, step);
995 // We found a nested IDL object which may or may not have
996 // been configured as a top-level column. Flesh the column
997 // metadata with our newly found IDL info.
1000 col.datatype = idlField.datatype;
1002 if (!col.idlFieldDef) {
1003 idlField = col.idlFieldDef;
1005 if (!col.idlClass) {
1006 col.idlClass = idlClassDef.name;
1009 col.label = idlField.label || idlField.name;
1017 getColumnTextContent(row: any, col: GridColumn): string {
1018 if (this.columnHasTextGenerator(col)) {
1019 const str = this.cellTextGenerator[col.name](row);
1020 return (str === null || str === undefined) ? '' : str;
1022 if (col.cellTemplate) {
1023 return ''; // avoid 'undefined' values
1025 return this.getRowColumnValue(row, col);
1030 selectOneRow(index: any) {
1031 this.rowSelector.clear();
1032 this.rowSelector.select(index);
1033 this.lastSelectedIndex = index;
1036 selectMultipleRows(indexes: any[]) {
1037 this.rowSelector.clear();
1038 this.rowSelector.select(indexes);
1039 this.lastSelectedIndex = indexes[indexes.length - 1];
1042 // selects or deselects an item, without affecting the others.
1043 // returns true if the item is selected; false if de-selected.
1044 toggleSelectOneRow(index: any) {
1045 if (this.rowSelector.contains(index)) {
1046 this.rowSelector.deselect(index);
1050 this.rowSelector.select(index);
1051 this.lastSelectedIndex = index;
1055 selectRowByPos(pos: number) {
1056 const row = this.dataSource.data[pos];
1058 this.selectOneRow(this.getRowIndex(row));
1062 selectPreviousRow() {
1063 if (!this.lastSelectedIndex) { return; }
1064 const pos = this.getRowPosition(this.lastSelectedIndex);
1065 if (pos === this.pager.offset) {
1066 this.toPrevPage().then(ok => this.selectLastRow(), err => {});
1068 this.selectRowByPos(pos - 1);
1073 if (!this.lastSelectedIndex) { return; }
1074 const pos = this.getRowPosition(this.lastSelectedIndex);
1075 if (pos === (this.pager.offset + this.pager.limit - 1)) {
1076 this.toNextPage().then(ok => this.selectFirstRow(), err => {});
1078 this.selectRowByPos(pos + 1);
1083 // Select the previous row in addition to any currently selected row.
1084 // However, if the previous row is already selected, assume the user
1085 // has reversed direction and now wants to de-select the last selected row.
1086 selectMultiRowsPrevious() {
1087 if (!this.lastSelectedIndex) { return; }
1088 const pos = this.getRowPosition(this.lastSelectedIndex);
1089 const selectedIndexes = this.rowSelector.selected();
1091 const promise = // load the previous page of data if needed
1092 (pos === this.pager.offset) ? this.toPrevPage() : Promise.resolve();
1096 const row = this.dataSource.data[pos - 1];
1097 const newIndex = this.getRowIndex(row);
1098 if (selectedIndexes.filter(i => i === newIndex).length > 0) {
1099 // Prev row is already selected. User is reversing direction.
1100 this.rowSelector.deselect(this.lastSelectedIndex);
1101 this.lastSelectedIndex = newIndex;
1103 this.selectMultipleRows(selectedIndexes.concat(newIndex));
1110 // Select all rows between the previously selected row and
1111 // the provided row, including the provided row.
1112 // This is additive only -- rows are never de-selected.
1113 selectRowRange(index: any) {
1115 if (!this.lastSelectedIndex) {
1116 this.selectOneRow(index);
1120 const next = this.getRowPosition(index);
1121 const prev = this.getRowPosition(this.lastSelectedIndex);
1122 const start = Math.min(prev, next);
1123 const end = Math.max(prev, next);
1125 for (let idx = start; idx <= end; idx++) {
1126 const row = this.dataSource.data[idx];
1128 this.rowSelector.select(this.getRowIndex(row));
1132 this.lastSelectedIndex = index;
1136 // Select the next row in addition to any currently selected row.
1137 // However, if the next row is already selected, assume the user
1138 // has reversed direction and wants to de-select the last selected row.
1139 selectMultiRowsNext() {
1140 if (!this.lastSelectedIndex) { return; }
1141 const pos = this.getRowPosition(this.lastSelectedIndex);
1142 const selectedIndexes = this.rowSelector.selected();
1144 const promise = // load the next page of data if needed
1145 (pos === (this.pager.offset + this.pager.limit - 1)) ?
1146 this.toNextPage() : Promise.resolve();
1150 const row = this.dataSource.data[pos + 1];
1151 const newIndex = this.getRowIndex(row);
1152 if (selectedIndexes.filter(i => i === newIndex).length > 0) {
1153 // Next row is already selected. User is reversing direction.
1154 this.rowSelector.deselect(this.lastSelectedIndex);
1155 this.lastSelectedIndex = newIndex;
1157 this.selectMultipleRows(selectedIndexes.concat(newIndex));
1164 getFirstRowInPage(): any {
1165 return this.dataSource.data[this.pager.offset];
1168 getLastRowInPage(): any {
1169 return this.dataSource.data[this.pager.offset + this.pager.limit - 1];
1173 this.selectOneRow(this.getRowIndex(this.getFirstRowInPage()));
1177 this.selectOneRow(this.getRowIndex(this.getLastRowInPage()));
1180 selectRowsInPage() {
1181 const rows = this.dataSource.getPageOfRows(this.pager);
1182 const indexes = rows.map(r => this.getRowIndex(r));
1183 this.rowSelector.select(indexes);
1184 this.selectRowsInPageEmitter.emit();
1187 toPrevPage(): Promise<any> {
1188 if (this.pager.isFirstPage()) {
1189 return Promise.reject('on first');
1191 // temp ignore pager events since we're calling requestPage manually.
1193 this.pager.decrement();
1194 this.listenToPager();
1195 return this.dataSource.requestPage(this.pager);
1198 toNextPage(): Promise<any> {
1199 if (this.pager.isLastPage()) {
1200 return Promise.reject('on last');
1202 // temp ignore pager events since we're calling requestPage manually.
1204 this.pager.increment();
1205 this.listenToPager();
1206 return this.dataSource.requestPage(this.pager);
1209 getAllRows(): Promise<any> {
1210 const pager = new Pager();
1212 pager.limit = MAX_ALL_ROW_COUNT;
1213 return this.dataSource.requestPage(pager);
1216 // Returns a key/value pair object of visible column data as text.
1217 getRowAsFlatText(row: any): any {
1219 this.columnSet.displayColumns().forEach(col => {
1221 this.getColumnTextContent(row, col);
1226 getAllRowsAsText(): Observable<any> {
1227 return Observable.create(observer => {
1228 this.getAllRows().then(ok => {
1229 this.dataSource.data.forEach(row => {
1230 observer.next(this.getRowAsFlatText(row));
1232 observer.complete();
1237 removeFilters(): void {
1238 this.dataSource.filters = {};
1239 this.columnSet.displayColumns().forEach(col => { col.removeFilter(); });
1240 this.filterControls.forEach(ctl => ctl.reset());
1243 filtersSet(): boolean {
1244 return Object.keys(this.dataSource.filters).length > 0;
1247 gridToCsv(): Promise<string> {
1250 const columns = this.columnSet.displayColumns();
1253 columns.forEach(col => {
1254 csvStr += this.valueToCsv(col.label),
1258 csvStr = csvStr.replace(/,$/, '\n');
1260 return new Promise(resolve => {
1261 this.getAllRowsAsText().subscribe(
1263 columns.forEach(col => {
1264 csvStr += this.valueToCsv(row[col.name]);
1267 csvStr = csvStr.replace(/,$/, '\n');
1270 () => resolve(csvStr)
1276 // prepares a string for inclusion within a CSV document
1277 // by escaping commas and quotes and removing newlines.
1278 valueToCsv(str: string): string {
1280 if (!str) { return ''; }
1281 str = str.replace(/\n/g, '');
1282 if (str.match(/\,/) || str.match(/"/)) {
1283 str = str.replace(/"/g, '""');
1284 str = '"' + str + '"';
1290 if (!this.columnSet.idlClass) { return; }
1292 const pkeyField = this.idl.classes[this.columnSet.idlClass].pkey;
1293 const specifiedColumnOrder = this.autoGeneratedColumnOrder ?
1294 this.autoGeneratedColumnOrder.split(/,/) : [];
1296 // generate columns for all non-virtual fields on the IDL class
1297 const fields = this.idl.classes[this.columnSet.idlClass].fields
1298 .filter(field => !field.virtual);
1300 const sortedFields = this.autoGeneratedColumnOrder ?
1301 this.idl.sortIdlFields(fields, this.autoGeneratedColumnOrder.split(/,/)) :
1304 sortedFields.forEach(field => {
1305 if (!this.ignoredFields.filter(ignored => ignored === field.name).length) {
1306 const col = new GridColumn();
1307 col.name = field.name;
1308 col.label = field.label || field.name;
1309 col.idlFieldDef = field;
1310 col.idlClass = this.columnSet.idlClass;
1311 col.datatype = field.datatype;
1312 col.isIndex = (field.name === pkeyField);
1315 if (this.showDeclaredFieldsOnly) {
1319 this.columnSet.add(col);
1324 saveGridConfig(): Promise<any> {
1325 if (!this.persistKey) {
1326 throw new Error('Grid persistKey required to save columns');
1328 const conf = new GridPersistConf();
1330 conf.limit = this.pager.limit;
1331 conf.columns = this.columnSet.compileSaveObject();
1333 // Avoid persisting group visibility since that may change
1334 // with the addition of new columns. Always calculate that
1336 conf.hideToolbarActions = this.toolbarActions
1337 .filter(action => !action.isGroup && action.hidden)
1338 .map(action => action.label);
1340 return this.store.setItem('eg.grid.' + this.persistKey, conf);
1343 // TODO: saveGridConfigAsOrgSetting(...)
1345 getGridConfig(persistKey: string): Promise<GridPersistConf> {
1346 if (!persistKey) { return Promise.resolve(null); }
1347 return this.store.getItem('eg.grid.' + persistKey);
1350 columnHasTextGenerator(col: GridColumn): boolean {
1351 return this.cellTextGenerator && col.name in this.cellTextGenerator;
1356 // Actions apply to specific rows
1357 export class GridToolbarAction {
1359 onClick: EventEmitter<any []>;
1360 action: (rows: any[]) => any; // DEPRECATED
1363 isGroup: boolean; // used for group placeholder entries
1364 isSeparator: boolean;
1365 disableOnRows: (rows: any[]) => boolean;
1369 // Buttons are global actions
1370 export class GridToolbarButton {
1372 onClick: EventEmitter<any []>;
1373 action: () => any; // DEPRECATED
1378 export class GridToolbarCheckbox {
1381 onChange: EventEmitter<boolean>;
1384 export interface GridColumnSort {
1389 export class GridDataSource {
1392 sort: GridColumnSort[];
1394 allRowsRetrieved: boolean;
1395 requestingData: boolean;
1396 retrievalError: boolean;
1397 getRows: (pager: Pager, sort: GridColumnSort[]) => Observable<any>;
1407 this.allRowsRetrieved = false;
1410 // called from the template -- no data fetching
1411 getPageOfRows(pager: Pager): any[] {
1413 return this.data.slice(
1414 pager.offset, pager.limit + pager.offset
1415 ).filter(row => row !== undefined);
1420 // called on initial component load and user action (e.g. paging, sorting).
1421 requestPage(pager: Pager): Promise<any> {
1424 this.getPageOfRows(pager).length === pager.limit
1425 // already have all data
1426 || this.allRowsRetrieved
1427 // have no way to get more data.
1430 return Promise.resolve();
1433 // If we have to call out for data, set inFetch
1434 this.requestingData = true;
1435 this.retrievalError = false;
1437 return new Promise((resolve, reject) => {
1438 let idx = pager.offset;
1439 return this.getRows(pager, this.sort).subscribe(
1441 this.data[idx++] = row;
1442 // not updating this.requestingData, as having
1443 // retrieved one row doesn't mean we're done
1444 this.retrievalError = false;
1447 console.error(`grid getRows() error ${err}`);
1448 this.requestingData = false;
1449 this.retrievalError = true;
1453 this.checkAllRetrieved(pager, idx);
1454 this.requestingData = false;
1455 this.retrievalError = false;
1462 // See if the last getRows() call resulted in the final set of data.
1463 checkAllRetrieved(pager: Pager, idx: number) {
1464 if (this.allRowsRetrieved) { return; }
1466 if (idx === 0 || idx < (pager.limit + pager.offset)) {
1467 // last query returned nothing or less than one page.
1468 // confirm we have all of the preceding pages.
1469 if (!this.data.includes(undefined)) {
1470 this.allRowsRetrieved = true;
1471 pager.resultCount = this.data.length;