2 * Collection of grid related classses and interfaces.
4 import {TemplateRef, EventEmitter, QueryList} from '@angular/core';
5 import {Observable, Subscription} 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>;
36 isDragTarget: boolean;
38 isFilterable: boolean;
40 isMultiSortable: boolean;
41 disableTooltip: boolean;
42 asyncSupportsEmptyTermClick: boolean;
43 comparator: (valueA: any, valueB: any) => number;
45 // True if the column was automatically generated.
50 filterOperator: string;
51 filterInputDisabled: boolean;
52 filterIncludeOrgAncestors: boolean;
53 filterIncludeOrgDescendants: boolean;
55 flesher: (obj: any, col: GridColumn, item: any) => any;
57 getCellContext(row: any) {
61 userContext: this.cellContext
70 this.isFiltered = false;
71 this.filterValue = undefined;
72 this.filterOperator = '=';
73 this.filterInputDisabled = false;
74 this.filterIncludeOrgAncestors = false;
75 this.filterIncludeOrgDescendants = false;
79 export class GridColumnSet {
80 columns: GridColumn[];
82 indexColumn: GridColumn;
84 isFilterable: boolean;
85 isMultiSortable: boolean;
86 stockVisible: string[];
88 defaultHiddenFields: string[];
89 defaultVisibleFields: string[];
91 constructor(idl: IdlService, idlClass?: string) {
94 this.stockVisible = [];
95 this.idlClass = idlClass;
98 add(col: GridColumn) {
100 this.applyColumnDefaults(col);
102 if (!this.insertColumn(col)) {
103 // Column was rejected as a duplicate.
107 if (col.isIndex) { this.indexColumn = col; }
109 // track which fields are visible on page load.
111 this.stockVisible.push(col.name);
114 this.applyColumnSortability(col);
115 this.applyColumnFilterability(col);
118 // Returns true if the new column was inserted, false otherwise.
119 // Declared columns take precedence over auto-generated columns
120 // when collisions occur.
121 // Declared columns are inserted in front of auto columns.
122 insertColumn(col: GridColumn): boolean {
125 if (this.getColByName(col.name)) {
126 // New auto-generated column conflicts with existing
130 // No collisions. Add to the end of the list
131 this.columns.push(col);
136 // Adding a declared column.
139 for (let idx = 0; idx < this.columns.length; idx++) {
140 const testCol = this.columns[idx];
141 if (testCol.name === col.name) { // match found
142 if (testCol.isAuto) {
143 // new column takes precedence, remove the existing column.
144 this.columns.splice(idx, 1);
147 // New column does not take precedence. Avoid
154 // Delcared columns are inserted just before the first auto-column
155 for (let idx = 0; idx < this.columns.length; idx++) {
156 const testCol = this.columns[idx];
157 if (testCol.isAuto) {
159 this.columns.unshift(col);
161 this.columns.splice(idx, 0, col);
167 // No insertion point found. Toss the new column on the end.
168 this.columns.push(col);
172 getColByName(name: string): GridColumn {
173 return this.columns.filter(c => c.name === name)[0];
176 idlInfoFromDotpath(dotpath: string): any {
177 if (!dotpath || !this.idlClass) { return null; }
182 let nextIdlClass = this.idl.classes[this.idlClass];
184 const pathParts = dotpath.split(/\./);
186 for (let i = 0; i < pathParts.length; i++) {
188 const part = pathParts[i];
189 idlParent = idlField;
190 idlClass = nextIdlClass;
191 idlField = idlClass.field_map[part];
193 if (!idlField) { return null; } // invalid IDL path
195 if (i === pathParts.length - 1) {
196 // No more links to process.
200 if (idlField['class'] && (
201 idlField.datatype === 'link' ||
202 idlField.datatype === 'org_unit')) {
203 // The link class on the current field refers to the
204 // class of the link destination, not the current field.
205 // Mark it for processing during the next iteration.
206 nextIdlClass = this.idl.classes[idlField['class']];
211 idlParent: idlParent,
219 this.columns.forEach(col => {
223 col.visible = this.stockVisible.includes(col.name);
227 applyColumnDefaults(col: GridColumn) {
229 if (!col.idlFieldDef) {
230 const idlInfo = this.idlInfoFromDotpath(col.path || col.name);
232 col.idlFieldDef = idlInfo.idlField;
233 col.idlClass = idlInfo.idlClass.name;
235 col.datatype = col.idlFieldDef.datatype;
238 col.label = col.idlFieldDef.label || col.idlFieldDef.name;
243 if (!col.name) { col.name = col.path; }
244 if (!col.flex) { col.flex = 2; }
245 if (!col.align) { col.align = 'left'; }
246 if (!col.label) { col.label = col.name; }
247 if (!col.datatype) { col.datatype = 'text'; }
249 col.visible = !col.hidden;
252 applyColumnSortability(col: GridColumn) {
253 // column sortability defaults to the sortability of the column set.
254 if (col.isSortable === undefined && this.isSortable) {
255 col.isSortable = true;
258 if (col.isMultiSortable === undefined && this.isMultiSortable) {
259 col.isMultiSortable = true;
262 if (col.isMultiSortable) {
263 col.isSortable = true;
266 applyColumnFilterability(col: GridColumn) {
267 // column filterability defaults to the afilterability of the column set.
268 if (col.isFilterable === undefined && this.isFilterable) {
269 col.isFilterable = true;
273 displayColumns(): GridColumn[] {
274 return this.columns.filter(c => c.visible);
277 // Sorted visible columns followed by sorted non-visible columns.
278 // Note we don't sort this.columns directly as it would impact
279 // grid column display ordering.
280 sortForColPicker(): GridColumn[] {
281 const visible = this.columns.filter(c => c.visible);
282 const invisible = this.columns.filter(c => !c.visible);
284 visible.sort((a, b) => a.label < b.label ? -1 : 1);
285 invisible.sort((a, b) => a.label < b.label ? -1 : 1);
287 return visible.concat(invisible);
290 insertBefore(source: GridColumn, target: GridColumn) {
293 this.columns.forEach((col, idx) => {
294 if (col.name === target.name) { targetIdx = idx; }});
296 this.columns.forEach((col, idx) => {
297 if (col.name === source.name) { sourceIdx = idx; }});
299 if (sourceIdx >= 0) {
300 this.columns.splice(sourceIdx, 1);
303 this.columns.splice(targetIdx, 0, source);
306 // Move visible columns to the front of the list.
307 moveVisibleToFront() {
308 const newCols = this.displayColumns();
309 this.columns.forEach(col => {
310 if (!col.visible) { newCols.push(col); }});
311 this.columns = newCols;
314 moveColumn(col: GridColumn, diff: number) {
315 let srcIdx, targetIdx;
317 this.columns.forEach((c, i) => {
318 if (c.name === col.name) { srcIdx = i; }
321 targetIdx = srcIdx + diff;
324 } else if (targetIdx >= this.columns.length) {
325 // Target index follows the last visible column.
327 this.columns.forEach((c, idx) => {
328 if (c.visible) { lastVisible = idx; }
331 // When moving a column (down) causes one or more
332 // visible columns to shuffle forward, our column
333 // moves into the slot of the last visible column.
334 // Otherwise, put it into the slot directly following
335 // the last visible column.
336 targetIdx = srcIdx <= lastVisible ? lastVisible : lastVisible + 1;
339 // Splice column out of old position, insert at new position.
340 this.columns.splice(srcIdx, 1);
341 this.columns.splice(targetIdx, 0, col);
344 compileSaveObject(): GridColumnPersistConf[] {
345 // only store information about visible columns.
346 // scrunch the data down to just the needed info.
347 return this.displayColumns().map(col => {
348 const c: GridColumnPersistConf = {name : col.name};
349 if (col.align !== 'left') { c.align = col.align; }
350 if (col.flex !== 2) { c.flex = Number(col.flex); }
351 if (Number(col.sort)) { c.sort = Number(col.sort); }
356 applyColumnSettings(conf: GridColumnPersistConf[]) {
358 if (!conf || conf.length === 0) {
359 // No configuration is available, but we have a list of
360 // fields to show or hide by default
362 if (this.defaultVisibleFields) {
363 this.columns.forEach(col => {
364 if (this.defaultVisibleFields.includes(col.name)) {
371 } else if (this.defaultHiddenFields) {
372 this.defaultHiddenFields.forEach(name => {
373 const col = this.getColByName(name);
385 conf.forEach(colConf => {
386 const col = this.getColByName(colConf.name);
387 if (!col) { return; } // no such column in this grid.
390 if (colConf.align) { col.align = colConf.align; }
391 if (colConf.flex) { col.flex = Number(colConf.flex); }
392 if (colConf.sort) { col.sort = Number(colConf.sort); }
394 // Add to new columns array, avoid dupes.
395 if (newCols.filter(c => c.name === col.name).length === 0) {
400 // columns which are not expressed within the saved
401 // configuration are marked as non-visible and
402 // appended to the end of the new list of columns.
403 this.columns.forEach(c => {
404 if (conf.filter(cf => cf.name === c.name).length === 0) {
410 this.columns = newCols;
414 // Maps colunm names to functions which return plain text values for
415 // each mapped column on a given row. This is primarily useful for
416 // generating print-friendly content for grid cells rendered via
419 // USAGE NOTE: Since a cellTemplate can be passed arbitrary context
420 // but a GridCellTextGenerator only gets the row object,
421 // if it's important to include content that's not available
422 // by default in the row object, you may want to stick
423 // it in the row object as an additional attribute.
425 export interface GridCellTextGenerator {
426 [columnName: string]: (row: any) => string;
429 export class GridRowSelector {
430 indexes: {[string: string]: boolean};
436 // Returns true if all of the requested indexes exist in the selector.
437 contains(index: string | string[]): boolean {
438 const indexes = [].concat(index);
439 for (let i = 0; i < indexes.length; i++) { // early exit
440 if (!this.indexes[indexes[i]]) {
447 select(index: string | string[]) {
448 const indexes = [].concat(index);
449 indexes.forEach(i => this.indexes[i] = true);
452 deselect(index: string | string[]) {
453 const indexes = [].concat(index);
454 indexes.forEach(i => delete this.indexes[i]);
457 // Returns the list of selected index values.
458 // In some contexts (template checkboxes) the value for an index is
459 // set to false to deselect instead of having it removed (via deselect()).
460 // NOTE GridRowSelector has no knowledge of when a row is no longer
461 // present in the grid. Use GridContext.getSelectedRows() to get
462 // list of selected rows that are still present in the grid.
464 return Object.keys(this.indexes).filter(
465 ind => Boolean(this.indexes[ind]));
469 return this.selected().length === 0;
477 export interface GridRowFlairEntry {
478 icon: string; // name of material icon
479 title?: string; // tooltip string
482 export class GridColumnPersistConf {
489 export class GridPersistConf {
492 columns: GridColumnPersistConf[];
495 export class GridContext {
500 isFilterable: boolean;
501 stickyGridHeader: boolean;
502 isMultiSortable: boolean;
503 useLocalSort: boolean;
505 disableMultiSelect: boolean;
506 disableSelect: boolean;
507 dataSource: GridDataSource;
508 columnSet: GridColumnSet;
509 autoGeneratedColumnOrder: string;
510 rowSelector: GridRowSelector;
511 toolbarButtons: GridToolbarButton[];
512 toolbarCheckboxes: GridToolbarCheckbox[];
513 toolbarActions: GridToolbarAction[];
514 lastSelectedIndex: any;
515 pageChanges: Subscription;
516 rowFlairIsEnabled: boolean;
517 rowFlairCallback: (row: any) => GridRowFlairEntry;
518 rowClassCallback: (row: any) => string;
519 cellClassCallback: (row: any, col: GridColumn) => string;
520 defaultVisibleFields: string[];
521 defaultHiddenFields: string[];
522 ignoredFields: string[];
523 overflowCells: boolean;
524 disablePaging: boolean;
525 showDeclaredFieldsOnly: boolean;
526 cellTextGenerator: GridCellTextGenerator;
528 // Allow calling code to know when the select-all-rows-in-page
529 // action has occurred.
530 selectRowsInPageEmitter: EventEmitter<void>;
532 filterControls: QueryList<GridFilterControlComponent>;
534 // Services injected by our grid component
537 store: ServerStoreService;
538 format: FormatService;
543 store: ServerStoreService,
544 format: FormatService) {
549 this.format = format;
550 this.pager = new Pager();
551 this.rowSelector = new GridRowSelector();
552 this.toolbarButtons = [];
553 this.toolbarCheckboxes = [];
554 this.toolbarActions = [];
558 this.selectRowsInPageEmitter = new EventEmitter<void>();
559 this.columnSet = new GridColumnSet(this.idl, this.idlClass);
560 this.columnSet.isSortable = this.isSortable === true;
561 this.columnSet.isFilterable = this.isFilterable === true;
562 this.columnSet.isMultiSortable = this.isMultiSortable === true;
563 this.columnSet.defaultHiddenFields = this.defaultHiddenFields;
564 this.columnSet.defaultVisibleFields = this.defaultVisibleFields;
565 if (!this.pager.limit) {
566 this.pager.limit = this.disablePaging ? MAX_ALL_ROW_COUNT : 10;
568 this.generateColumns();
571 // Load initial settings and data.
573 this.applyGridConfig()
574 .then(ok => this.dataSource.requestPage(this.pager))
575 .then(ok => this.listenToPager());
582 applyGridConfig(): Promise<void> {
583 return this.getGridConfig(this.persistKey)
587 columns = conf.columns;
588 if (conf.limit && !this.disablePaging) {
589 this.pager.limit = conf.limit;
593 // This is called regardless of the presence of saved
594 // settings so defaults can be applied.
595 this.columnSet.applyColumnSettings(columns);
600 // Give the UI time to settle before reloading grid data.
601 // This can help when data retrieval depends on a value
602 // getting modified by an angular digest cycle.
605 this.dataSource.reset();
606 this.dataSource.requestPage(this.pager);
610 reloadWithoutPagerReset() {
612 this.dataSource.reset();
613 this.dataSource.requestPage(this.pager);
617 // Sort the existing data source instead of requesting sorted
618 // data from the client. Reset pager to page 1. As with reload(),
619 // give the client a chance to setting before redisplaying.
623 this.sortLocalData();
624 this.dataSource.requestPage(this.pager);
628 // Subscribe or unsubscribe to page-change events from the pager.
630 if (this.pageChanges) { return; }
631 this.pageChanges = this.pager.onChange$.subscribe(
632 val => this.dataSource.requestPage(this.pager));
636 if (!this.pageChanges) { return; }
637 this.pageChanges.unsubscribe();
638 this.pageChanges = null;
641 // Sort data in the data source array
644 const sortDefs = this.dataSource.sort.map(sort => {
645 const column = this.columnSet.getColByName(sort.name);
653 if (!def.col.comparator) {
654 switch (def.col.datatype) {
658 def.col.comparator = (a, b) => {
661 if (a < b) { return -1; }
662 if (a > b) { return 1; }
667 def.col.comparator = (a, b) => {
668 if (a < b) { return -1; }
669 if (a > b) { return 1; }
678 this.dataSource.data.sort((rowA, rowB) => {
680 for (let idx = 0; idx < sortDefs.length; idx++) {
681 const sortDef = sortDefs[idx];
683 const valueA = this.getRowColumnValue(rowA, sortDef.col);
684 const valueB = this.getRowColumnValue(rowB, sortDef.col);
686 if (valueA === '' && valueB === '') { continue; }
687 if (valueA === '' && valueB !== '') { return 1; }
688 if (valueA !== '' && valueB === '') { return -1; }
690 const diff = sortDef.col.comparator(valueA, valueB);
691 if (diff === 0) { continue; }
693 return sortDef.dir === 'DESC' ? -diff : diff;
696 return 0; // No differences found.
700 getRowIndex(row: any): any {
701 const col = this.columnSet.indexColumn;
703 throw new Error('grid index column required');
705 return this.getRowColumnValue(row, col);
708 // Returns position in the data source array of the row with
709 // the provided index.
710 getRowPosition(index: any): number {
711 // for-loop for early exit
712 for (let idx = 0; idx < this.dataSource.data.length; idx++) {
713 const row = this.dataSource.data[idx];
714 if (row !== undefined && index === this.getRowIndex(row)) {
720 // Return the row with the provided index.
721 getRowByIndex(index: any): any {
722 for (let idx = 0; idx < this.dataSource.data.length; idx++) {
723 const row = this.dataSource.data[idx];
724 if (row !== undefined && index === this.getRowIndex(row)) {
730 // Returns all selected rows, regardless of whether they are
731 // currently visible in the grid display.
732 // De-selects previously selected rows which are no longer
733 // present in the grid.
734 getSelectedRows(): any[] {
738 this.rowSelector.selected().forEach(index => {
739 const row = this.getRowByIndex(index);
747 this.rowSelector.deselect(deleted);
751 rowIsSelected(row: any): boolean {
752 const index = this.getRowIndex(row);
753 return this.rowSelector.selected().filter(
758 getRowColumnValue(row: any, col: GridColumn): string {
762 val = this.nestedItemFieldValue(row, col);
763 } else if (col.name in row) {
764 val = this.getObjectFieldValue(row, col.name);
767 if (col.datatype === 'bool') {
768 // Avoid string-ifying bools so we can use an <eg-bool/>
769 // in the grid template.
773 return this.format.transform({
775 idlClass: col.idlClass,
776 idlField: col.idlFieldDef ? col.idlFieldDef.name : col.name,
777 datatype: col.datatype,
778 datePlusTime: Boolean(col.datePlusTime),
779 timezoneContextOrg: Number(col.timezoneContextOrg)
783 getObjectFieldValue(obj: any, name: string): any {
784 if (typeof obj[name] === 'function') {
791 nestedItemFieldValue(obj: any, col: GridColumn): string {
795 const original = obj;
796 const steps = col.path.split('.');
798 for (let i = 0; i < steps.length; i++) {
799 const step = steps[i];
801 if (obj === null || obj === undefined || typeof obj !== 'object') {
802 // We have run out of data to step through before
803 // reaching the end of the path. Conclude fleshing via
804 // callback if provided then exit.
805 if (col.flesher && obj !== undefined) {
806 return col.flesher(obj, col, original);
811 const class_ = obj.classname;
812 if (class_ && (idlClassDef = this.idl.classes[class_])) {
813 idlField = idlClassDef.field_map[step];
816 obj = this.getObjectFieldValue(obj, step);
819 // We found a nested IDL object which may or may not have
820 // been configured as a top-level column. Flesh the column
821 // metadata with our newly found IDL info.
824 col.datatype = idlField.datatype;
826 if (!col.idlFieldDef) {
827 idlField = col.idlFieldDef;
830 col.idlClass = idlClassDef.name;
833 col.label = idlField.label || idlField.name;
841 getColumnTextContent(row: any, col: GridColumn): string {
842 if (this.columnHasTextGenerator(col)) {
843 const str = this.cellTextGenerator[col.name](row);
844 return (str === null || str === undefined) ? '' : str;
846 if (col.cellTemplate) {
847 return ''; // avoid 'undefined' values
849 return this.getRowColumnValue(row, col);
854 selectOneRow(index: any) {
855 this.rowSelector.clear();
856 this.rowSelector.select(index);
857 this.lastSelectedIndex = index;
860 selectMultipleRows(indexes: any[]) {
861 this.rowSelector.clear();
862 this.rowSelector.select(indexes);
863 this.lastSelectedIndex = indexes[indexes.length - 1];
866 // selects or deselects an item, without affecting the others.
867 // returns true if the item is selected; false if de-selected.
868 toggleSelectOneRow(index: any) {
869 if (this.rowSelector.contains(index)) {
870 this.rowSelector.deselect(index);
874 this.rowSelector.select(index);
875 this.lastSelectedIndex = index;
879 selectRowByPos(pos: number) {
880 const row = this.dataSource.data[pos];
882 this.selectOneRow(this.getRowIndex(row));
886 selectPreviousRow() {
887 if (!this.lastSelectedIndex) { return; }
888 const pos = this.getRowPosition(this.lastSelectedIndex);
889 if (pos === this.pager.offset) {
890 this.toPrevPage().then(ok => this.selectLastRow(), err => {});
892 this.selectRowByPos(pos - 1);
897 if (!this.lastSelectedIndex) { return; }
898 const pos = this.getRowPosition(this.lastSelectedIndex);
899 if (pos === (this.pager.offset + this.pager.limit - 1)) {
900 this.toNextPage().then(ok => this.selectFirstRow(), err => {});
902 this.selectRowByPos(pos + 1);
907 // Select the previous row in addition to any currently selected row.
908 // However, if the previous row is already selected, assume the user
909 // has reversed direction and now wants to de-select the last selected row.
910 selectMultiRowsPrevious() {
911 if (!this.lastSelectedIndex) { return; }
912 const pos = this.getRowPosition(this.lastSelectedIndex);
913 const selectedIndexes = this.rowSelector.selected();
915 const promise = // load the previous page of data if needed
916 (pos === this.pager.offset) ? this.toPrevPage() : Promise.resolve();
920 const row = this.dataSource.data[pos - 1];
921 const newIndex = this.getRowIndex(row);
922 if (selectedIndexes.filter(i => i === newIndex).length > 0) {
923 // Prev row is already selected. User is reversing direction.
924 this.rowSelector.deselect(this.lastSelectedIndex);
925 this.lastSelectedIndex = newIndex;
927 this.selectMultipleRows(selectedIndexes.concat(newIndex));
934 // Select all rows between the previously selected row and
935 // the provided row, including the provided row.
936 // This is additive only -- rows are never de-selected.
937 selectRowRange(index: any) {
939 if (!this.lastSelectedIndex) {
940 this.selectOneRow(index);
944 const next = this.getRowPosition(index);
945 const prev = this.getRowPosition(this.lastSelectedIndex);
946 const start = Math.min(prev, next);
947 const end = Math.max(prev, next);
949 for (let idx = start; idx <= end; idx++) {
950 const row = this.dataSource.data[idx];
952 this.rowSelector.select(this.getRowIndex(row));
956 this.lastSelectedIndex = index;
960 // Select the next row in addition to any currently selected row.
961 // However, if the next row is already selected, assume the user
962 // has reversed direction and wants to de-select the last selected row.
963 selectMultiRowsNext() {
964 if (!this.lastSelectedIndex) { return; }
965 const pos = this.getRowPosition(this.lastSelectedIndex);
966 const selectedIndexes = this.rowSelector.selected();
968 const promise = // load the next page of data if needed
969 (pos === (this.pager.offset + this.pager.limit - 1)) ?
970 this.toNextPage() : Promise.resolve();
974 const row = this.dataSource.data[pos + 1];
975 const newIndex = this.getRowIndex(row);
976 if (selectedIndexes.filter(i => i === newIndex).length > 0) {
977 // Next row is already selected. User is reversing direction.
978 this.rowSelector.deselect(this.lastSelectedIndex);
979 this.lastSelectedIndex = newIndex;
981 this.selectMultipleRows(selectedIndexes.concat(newIndex));
988 getFirstRowInPage(): any {
989 return this.dataSource.data[this.pager.offset];
992 getLastRowInPage(): any {
993 return this.dataSource.data[this.pager.offset + this.pager.limit - 1];
997 this.selectOneRow(this.getRowIndex(this.getFirstRowInPage()));
1001 this.selectOneRow(this.getRowIndex(this.getLastRowInPage()));
1004 selectRowsInPage() {
1005 const rows = this.dataSource.getPageOfRows(this.pager);
1006 const indexes = rows.map(r => this.getRowIndex(r));
1007 this.rowSelector.select(indexes);
1008 this.selectRowsInPageEmitter.emit();
1011 toPrevPage(): Promise<any> {
1012 if (this.pager.isFirstPage()) {
1013 return Promise.reject('on first');
1015 // temp ignore pager events since we're calling requestPage manually.
1017 this.pager.decrement();
1018 this.listenToPager();
1019 return this.dataSource.requestPage(this.pager);
1022 toNextPage(): Promise<any> {
1023 if (this.pager.isLastPage()) {
1024 return Promise.reject('on last');
1026 // temp ignore pager events since we're calling requestPage manually.
1028 this.pager.increment();
1029 this.listenToPager();
1030 return this.dataSource.requestPage(this.pager);
1033 getAllRows(): Promise<any> {
1034 const pager = new Pager();
1036 pager.limit = MAX_ALL_ROW_COUNT;
1037 return this.dataSource.requestPage(pager);
1040 // Returns a key/value pair object of visible column data as text.
1041 getRowAsFlatText(row: any): any {
1043 this.columnSet.displayColumns().forEach(col => {
1045 this.getColumnTextContent(row, col);
1050 getAllRowsAsText(): Observable<any> {
1051 return Observable.create(observer => {
1052 this.getAllRows().then(ok => {
1053 this.dataSource.data.forEach(row => {
1054 observer.next(this.getRowAsFlatText(row));
1056 observer.complete();
1061 removeFilters(): void {
1062 this.dataSource.filters = {};
1063 this.columnSet.displayColumns().forEach(col => { col.removeFilter(); });
1064 this.filterControls.forEach(ctl => ctl.reset());
1067 filtersSet(): boolean {
1068 return Object.keys(this.dataSource.filters).length > 0;
1071 gridToCsv(): Promise<string> {
1074 const columns = this.columnSet.displayColumns();
1077 columns.forEach(col => {
1078 csvStr += this.valueToCsv(col.label),
1082 csvStr = csvStr.replace(/,$/, '\n');
1084 return new Promise(resolve => {
1085 this.getAllRowsAsText().subscribe(
1087 columns.forEach(col => {
1088 csvStr += this.valueToCsv(row[col.name]);
1091 csvStr = csvStr.replace(/,$/, '\n');
1094 () => resolve(csvStr)
1100 // prepares a string for inclusion within a CSV document
1101 // by escaping commas and quotes and removing newlines.
1102 valueToCsv(str: string): string {
1104 if (!str) { return ''; }
1105 str = str.replace(/\n/g, '');
1106 if (str.match(/\,/) || str.match(/"/)) {
1107 str = str.replace(/"/g, '""');
1108 str = '"' + str + '"';
1114 if (!this.columnSet.idlClass) { return; }
1116 const pkeyField = this.idl.classes[this.columnSet.idlClass].pkey;
1117 const specifiedColumnOrder = this.autoGeneratedColumnOrder ?
1118 this.autoGeneratedColumnOrder.split(/,/) : [];
1120 // generate columns for all non-virtual fields on the IDL class
1121 const fields = this.idl.classes[this.columnSet.idlClass].fields
1122 .filter(field => !field.virtual);
1124 const sortedFields = this.autoGeneratedColumnOrder ?
1125 this.idl.sortIdlFields(fields, this.autoGeneratedColumnOrder.split(/,/)) :
1128 sortedFields.forEach(field => {
1129 if (!this.ignoredFields.filter(ignored => ignored === field.name).length) {
1130 const col = new GridColumn();
1131 col.name = field.name;
1132 col.label = field.label || field.name;
1133 col.idlFieldDef = field;
1134 col.idlClass = this.columnSet.idlClass;
1135 col.datatype = field.datatype;
1136 col.isIndex = (field.name === pkeyField);
1139 if (this.showDeclaredFieldsOnly) {
1143 this.columnSet.add(col);
1148 saveGridConfig(): Promise<any> {
1149 if (!this.persistKey) {
1150 throw new Error('Grid persistKey required to save columns');
1152 const conf = new GridPersistConf();
1154 conf.limit = this.pager.limit;
1155 conf.columns = this.columnSet.compileSaveObject();
1157 return this.store.setItem('eg.grid.' + this.persistKey, conf);
1160 // TODO: saveGridConfigAsOrgSetting(...)
1162 getGridConfig(persistKey: string): Promise<GridPersistConf> {
1163 if (!persistKey) { return Promise.resolve(null); }
1164 return this.store.getItem('eg.grid.' + persistKey);
1167 columnHasTextGenerator(col: GridColumn): boolean {
1168 return this.cellTextGenerator && col.name in this.cellTextGenerator;
1173 // Actions apply to specific rows
1174 export class GridToolbarAction {
1176 onClick: EventEmitter<any []>;
1177 action: (rows: any[]) => any; // DEPRECATED
1180 isGroup: boolean; // used for group placeholder entries
1181 isSeparator: boolean;
1182 disableOnRows: (rows: any[]) => boolean;
1185 // Buttons are global actions
1186 export class GridToolbarButton {
1188 onClick: EventEmitter<any []>;
1189 action: () => any; // DEPRECATED
1193 export class GridToolbarCheckbox {
1196 onChange: EventEmitter<boolean>;
1199 export class GridDataSource {
1204 allRowsRetrieved: boolean;
1205 requestingData: boolean;
1206 retrievalError: boolean;
1207 getRows: (pager: Pager, sort: any[]) => Observable<any>;
1217 this.allRowsRetrieved = false;
1220 // called from the template -- no data fetching
1221 getPageOfRows(pager: Pager): any[] {
1223 return this.data.slice(
1224 pager.offset, pager.limit + pager.offset
1225 ).filter(row => row !== undefined);
1230 // called on initial component load and user action (e.g. paging, sorting).
1231 requestPage(pager: Pager): Promise<any> {
1234 this.getPageOfRows(pager).length === pager.limit
1235 // already have all data
1236 || this.allRowsRetrieved
1237 // have no way to get more data.
1240 return Promise.resolve();
1243 // If we have to call out for data, set inFetch
1244 this.requestingData = true;
1245 this.retrievalError = false;
1247 return new Promise((resolve, reject) => {
1248 let idx = pager.offset;
1249 return this.getRows(pager, this.sort).subscribe(
1251 this.data[idx++] = row;
1252 // not updating this.requestingData, as having
1253 // retrieved one row doesn't mean we're done
1254 this.retrievalError = false;
1257 console.error(`grid getRows() error ${err}`);
1258 this.requestingData = false;
1259 this.retrievalError = true;
1263 this.checkAllRetrieved(pager, idx);
1264 this.requestingData = false;
1265 this.retrievalError = false;
1272 // See if the last getRows() call resulted in the final set of data.
1273 checkAllRetrieved(pager: Pager, idx: number) {
1274 if (this.allRowsRetrieved) { return; }
1276 if (idx === 0 || idx < (pager.limit + pager.offset)) {
1277 // last query returned nothing or less than one page.
1278 // confirm we have all of the preceding pages.
1279 if (!this.data.includes(undefined)) {
1280 this.allRowsRetrieved = true;
1281 pager.resultCount = this.data.length;