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 insertBefore(source: GridColumn, target: GridColumn) {
280 this.columns.forEach((col, idx) => {
281 if (col.name === target.name) { targetIdx = idx; }});
283 this.columns.forEach((col, idx) => {
284 if (col.name === source.name) { sourceIdx = idx; }});
286 if (sourceIdx >= 0) {
287 this.columns.splice(sourceIdx, 1);
290 this.columns.splice(targetIdx, 0, source);
293 // Move visible columns to the front of the list.
294 moveVisibleToFront() {
295 const newCols = this.displayColumns();
296 this.columns.forEach(col => {
297 if (!col.visible) { newCols.push(col); }});
298 this.columns = newCols;
301 moveColumn(col: GridColumn, diff: number) {
302 let srcIdx, targetIdx;
304 this.columns.forEach((c, i) => {
305 if (c.name === col.name) { srcIdx = i; }
308 targetIdx = srcIdx + diff;
311 } else if (targetIdx >= this.columns.length) {
312 // Target index follows the last visible column.
314 this.columns.forEach((c, idx) => {
315 if (c.visible) { lastVisible = idx; }
318 // When moving a column (down) causes one or more
319 // visible columns to shuffle forward, our column
320 // moves into the slot of the last visible column.
321 // Otherwise, put it into the slot directly following
322 // the last visible column.
323 targetIdx = srcIdx <= lastVisible ? lastVisible : lastVisible + 1;
326 // Splice column out of old position, insert at new position.
327 this.columns.splice(srcIdx, 1);
328 this.columns.splice(targetIdx, 0, col);
331 compileSaveObject(): GridColumnPersistConf[] {
332 // only store information about visible columns.
333 // scrunch the data down to just the needed info.
334 return this.displayColumns().map(col => {
335 const c: GridColumnPersistConf = {name : col.name};
336 if (col.align !== 'left') { c.align = col.align; }
337 if (col.flex !== 2) { c.flex = Number(col.flex); }
338 if (Number(col.sort)) { c.sort = Number(col.sort); }
343 applyColumnSettings(conf: GridColumnPersistConf[]) {
345 if (!conf || conf.length === 0) {
346 // No configuration is available, but we have a list of
347 // fields to show or hide by default
349 if (this.defaultVisibleFields) {
350 this.columns.forEach(col => {
351 if (this.defaultVisibleFields.includes(col.name)) {
358 } else if (this.defaultHiddenFields) {
359 this.defaultHiddenFields.forEach(name => {
360 const col = this.getColByName(name);
372 conf.forEach(colConf => {
373 const col = this.getColByName(colConf.name);
374 if (!col) { return; } // no such column in this grid.
377 if (colConf.align) { col.align = colConf.align; }
378 if (colConf.flex) { col.flex = Number(colConf.flex); }
379 if (colConf.sort) { col.sort = Number(colConf.sort); }
381 // Add to new columns array, avoid dupes.
382 if (newCols.filter(c => c.name === col.name).length === 0) {
387 // columns which are not expressed within the saved
388 // configuration are marked as non-visible and
389 // appended to the end of the new list of columns.
390 this.columns.forEach(c => {
391 if (conf.filter(cf => cf.name === c.name).length === 0) {
397 this.columns = newCols;
401 // Maps colunm names to functions which return plain text values for
402 // each mapped column on a given row. This is primarily useful for
403 // generating print-friendly content for grid cells rendered via
406 // USAGE NOTE: Since a cellTemplate can be passed arbitrary context
407 // but a GridCellTextGenerator only gets the row object,
408 // if it's important to include content that's not available
409 // by default in the row object, you may want to stick
410 // it in the row object as an additional attribute.
412 export interface GridCellTextGenerator {
413 [columnName: string]: (row: any) => string;
416 export class GridRowSelector {
417 indexes: {[string: string]: boolean};
423 // Returns true if all of the requested indexes exist in the selector.
424 contains(index: string | string[]): boolean {
425 const indexes = [].concat(index);
426 for (let i = 0; i < indexes.length; i++) { // early exit
427 if (!this.indexes[indexes[i]]) {
434 select(index: string | string[]) {
435 const indexes = [].concat(index);
436 indexes.forEach(i => this.indexes[i] = true);
439 deselect(index: string | string[]) {
440 const indexes = [].concat(index);
441 indexes.forEach(i => delete this.indexes[i]);
444 // Returns the list of selected index values.
445 // In some contexts (template checkboxes) the value for an index is
446 // set to false to deselect instead of having it removed (via deselect()).
447 // NOTE GridRowSelector has no knowledge of when a row is no longer
448 // present in the grid. Use GridContext.getSelectedRows() to get
449 // list of selected rows that are still present in the grid.
451 return Object.keys(this.indexes).filter(
452 ind => Boolean(this.indexes[ind]));
456 return this.selected().length === 0;
464 export interface GridRowFlairEntry {
465 icon: string; // name of material icon
466 title?: string; // tooltip string
469 export class GridColumnPersistConf {
476 export class GridPersistConf {
479 columns: GridColumnPersistConf[];
482 export class GridContext {
487 isFilterable: boolean;
488 stickyGridHeader: boolean;
489 isMultiSortable: boolean;
490 useLocalSort: boolean;
492 disableMultiSelect: boolean;
493 disableSelect: boolean;
494 dataSource: GridDataSource;
495 columnSet: GridColumnSet;
496 autoGeneratedColumnOrder: string;
497 rowSelector: GridRowSelector;
498 toolbarButtons: GridToolbarButton[];
499 toolbarCheckboxes: GridToolbarCheckbox[];
500 toolbarActions: GridToolbarAction[];
501 lastSelectedIndex: any;
502 pageChanges: Subscription;
503 rowFlairIsEnabled: boolean;
504 rowFlairCallback: (row: any) => GridRowFlairEntry;
505 rowClassCallback: (row: any) => string;
506 cellClassCallback: (row: any, col: GridColumn) => string;
507 defaultVisibleFields: string[];
508 defaultHiddenFields: string[];
509 ignoredFields: string[];
510 overflowCells: boolean;
511 disablePaging: boolean;
512 showDeclaredFieldsOnly: boolean;
513 cellTextGenerator: GridCellTextGenerator;
515 // Allow calling code to know when the select-all-rows-in-page
516 // action has occurred.
517 selectRowsInPageEmitter: EventEmitter<void>;
519 filterControls: QueryList<GridFilterControlComponent>;
521 // Services injected by our grid component
524 store: ServerStoreService;
525 format: FormatService;
530 store: ServerStoreService,
531 format: FormatService) {
536 this.format = format;
537 this.pager = new Pager();
538 this.rowSelector = new GridRowSelector();
539 this.toolbarButtons = [];
540 this.toolbarCheckboxes = [];
541 this.toolbarActions = [];
545 this.selectRowsInPageEmitter = new EventEmitter<void>();
546 this.columnSet = new GridColumnSet(this.idl, this.idlClass);
547 this.columnSet.isSortable = this.isSortable === true;
548 this.columnSet.isFilterable = this.isFilterable === true;
549 this.columnSet.isMultiSortable = this.isMultiSortable === true;
550 this.columnSet.defaultHiddenFields = this.defaultHiddenFields;
551 this.columnSet.defaultVisibleFields = this.defaultVisibleFields;
552 if (!this.pager.limit) {
553 this.pager.limit = this.disablePaging ? MAX_ALL_ROW_COUNT : 10;
555 this.generateColumns();
558 // Load initial settings and data.
560 this.applyGridConfig()
561 .then(ok => this.dataSource.requestPage(this.pager))
562 .then(ok => this.listenToPager());
569 applyGridConfig(): Promise<void> {
570 return this.getGridConfig(this.persistKey)
574 columns = conf.columns;
575 if (conf.limit && !this.disablePaging) {
576 this.pager.limit = conf.limit;
580 // This is called regardless of the presence of saved
581 // settings so defaults can be applied.
582 this.columnSet.applyColumnSettings(columns);
587 // Give the UI time to settle before reloading grid data.
588 // This can help when data retrieval depends on a value
589 // getting modified by an angular digest cycle.
592 this.dataSource.reset();
593 this.dataSource.requestPage(this.pager);
597 reloadWithoutPagerReset() {
599 this.dataSource.reset();
600 this.dataSource.requestPage(this.pager);
604 // Sort the existing data source instead of requesting sorted
605 // data from the client. Reset pager to page 1. As with reload(),
606 // give the client a chance to setting before redisplaying.
610 this.sortLocalData();
611 this.dataSource.requestPage(this.pager);
615 // Subscribe or unsubscribe to page-change events from the pager.
617 if (this.pageChanges) { return; }
618 this.pageChanges = this.pager.onChange$.subscribe(
619 val => this.dataSource.requestPage(this.pager));
623 if (!this.pageChanges) { return; }
624 this.pageChanges.unsubscribe();
625 this.pageChanges = null;
628 // Sort data in the data source array
631 const sortDefs = this.dataSource.sort.map(sort => {
632 const column = this.columnSet.getColByName(sort.name);
640 if (!def.col.comparator) {
641 switch (def.col.datatype) {
645 def.col.comparator = (a, b) => {
648 if (a < b) { return -1; }
649 if (a > b) { return 1; }
654 def.col.comparator = (a, b) => {
655 if (a < b) { return -1; }
656 if (a > b) { return 1; }
665 this.dataSource.data.sort((rowA, rowB) => {
667 for (let idx = 0; idx < sortDefs.length; idx++) {
668 const sortDef = sortDefs[idx];
670 const valueA = this.getRowColumnValue(rowA, sortDef.col);
671 const valueB = this.getRowColumnValue(rowB, sortDef.col);
673 if (valueA === '' && valueB === '') { continue; }
674 if (valueA === '' && valueB !== '') { return 1; }
675 if (valueA !== '' && valueB === '') { return -1; }
677 const diff = sortDef.col.comparator(valueA, valueB);
678 if (diff === 0) { continue; }
680 return sortDef.dir === 'DESC' ? -diff : diff;
683 return 0; // No differences found.
687 getRowIndex(row: any): any {
688 const col = this.columnSet.indexColumn;
690 throw new Error('grid index column required');
692 return this.getRowColumnValue(row, col);
695 // Returns position in the data source array of the row with
696 // the provided index.
697 getRowPosition(index: any): number {
698 // for-loop for early exit
699 for (let idx = 0; idx < this.dataSource.data.length; idx++) {
700 const row = this.dataSource.data[idx];
701 if (row !== undefined && index === this.getRowIndex(row)) {
707 // Return the row with the provided index.
708 getRowByIndex(index: any): any {
709 for (let idx = 0; idx < this.dataSource.data.length; idx++) {
710 const row = this.dataSource.data[idx];
711 if (row !== undefined && index === this.getRowIndex(row)) {
717 // Returns all selected rows, regardless of whether they are
718 // currently visible in the grid display.
719 // De-selects previously selected rows which are no longer
720 // present in the grid.
721 getSelectedRows(): any[] {
725 this.rowSelector.selected().forEach(index => {
726 const row = this.getRowByIndex(index);
734 this.rowSelector.deselect(deleted);
738 rowIsSelected(row: any): boolean {
739 const index = this.getRowIndex(row);
740 return this.rowSelector.selected().filter(
745 getRowColumnValue(row: any, col: GridColumn): string {
749 val = this.nestedItemFieldValue(row, col);
750 } else if (col.name in row) {
751 val = this.getObjectFieldValue(row, col.name);
754 if (col.datatype === 'bool') {
755 // Avoid string-ifying bools so we can use an <eg-bool/>
756 // in the grid template.
760 return this.format.transform({
762 idlClass: col.idlClass,
763 idlField: col.idlFieldDef ? col.idlFieldDef.name : col.name,
764 datatype: col.datatype,
765 datePlusTime: Boolean(col.datePlusTime),
766 timezoneContextOrg: Number(col.timezoneContextOrg)
770 getObjectFieldValue(obj: any, name: string): any {
771 if (typeof obj[name] === 'function') {
778 nestedItemFieldValue(obj: any, col: GridColumn): string {
782 const original = obj;
783 const steps = col.path.split('.');
785 for (let i = 0; i < steps.length; i++) {
786 const step = steps[i];
788 if (obj === null || obj === undefined || typeof obj !== 'object') {
789 // We have run out of data to step through before
790 // reaching the end of the path. Conclude fleshing via
791 // callback if provided then exit.
792 if (col.flesher && obj !== undefined) {
793 return col.flesher(obj, col, original);
798 const class_ = obj.classname;
799 if (class_ && (idlClassDef = this.idl.classes[class_])) {
800 idlField = idlClassDef.field_map[step];
803 obj = this.getObjectFieldValue(obj, step);
806 // We found a nested IDL object which may or may not have
807 // been configured as a top-level column. Flesh the column
808 // metadata with our newly found IDL info.
811 col.datatype = idlField.datatype;
813 if (!col.idlFieldDef) {
814 idlField = col.idlFieldDef;
817 col.idlClass = idlClassDef.name;
820 col.label = idlField.label || idlField.name;
828 getColumnTextContent(row: any, col: GridColumn): string {
829 if (this.columnHasTextGenerator(col)) {
830 const str = this.cellTextGenerator[col.name](row);
831 return (str === null || str === undefined) ? '' : str;
833 if (col.cellTemplate) {
834 return ''; // avoid 'undefined' values
836 return this.getRowColumnValue(row, col);
841 selectOneRow(index: any) {
842 this.rowSelector.clear();
843 this.rowSelector.select(index);
844 this.lastSelectedIndex = index;
847 selectMultipleRows(indexes: any[]) {
848 this.rowSelector.clear();
849 this.rowSelector.select(indexes);
850 this.lastSelectedIndex = indexes[indexes.length - 1];
853 // selects or deselects an item, without affecting the others.
854 // returns true if the item is selected; false if de-selected.
855 toggleSelectOneRow(index: any) {
856 if (this.rowSelector.contains(index)) {
857 this.rowSelector.deselect(index);
861 this.rowSelector.select(index);
862 this.lastSelectedIndex = index;
866 selectRowByPos(pos: number) {
867 const row = this.dataSource.data[pos];
869 this.selectOneRow(this.getRowIndex(row));
873 selectPreviousRow() {
874 if (!this.lastSelectedIndex) { return; }
875 const pos = this.getRowPosition(this.lastSelectedIndex);
876 if (pos === this.pager.offset) {
877 this.toPrevPage().then(ok => this.selectLastRow(), err => {});
879 this.selectRowByPos(pos - 1);
884 if (!this.lastSelectedIndex) { return; }
885 const pos = this.getRowPosition(this.lastSelectedIndex);
886 if (pos === (this.pager.offset + this.pager.limit - 1)) {
887 this.toNextPage().then(ok => this.selectFirstRow(), err => {});
889 this.selectRowByPos(pos + 1);
894 // Select the previous row in addition to any currently selected row.
895 // However, if the previous row is already selected, assume the user
896 // has reversed direction and now wants to de-select the last selected row.
897 selectMultiRowsPrevious() {
898 if (!this.lastSelectedIndex) { return; }
899 const pos = this.getRowPosition(this.lastSelectedIndex);
900 const selectedIndexes = this.rowSelector.selected();
902 const promise = // load the previous page of data if needed
903 (pos === this.pager.offset) ? this.toPrevPage() : Promise.resolve();
907 const row = this.dataSource.data[pos - 1];
908 const newIndex = this.getRowIndex(row);
909 if (selectedIndexes.filter(i => i === newIndex).length > 0) {
910 // Prev row is already selected. User is reversing direction.
911 this.rowSelector.deselect(this.lastSelectedIndex);
912 this.lastSelectedIndex = newIndex;
914 this.selectMultipleRows(selectedIndexes.concat(newIndex));
922 // Select the next row in addition to any currently selected row.
923 // However, if the next row is already selected, assume the user
924 // has reversed direction and wants to de-select the last selected row.
925 selectMultiRowsNext() {
926 if (!this.lastSelectedIndex) { return; }
927 const pos = this.getRowPosition(this.lastSelectedIndex);
928 const selectedIndexes = this.rowSelector.selected();
930 const promise = // load the next page of data if needed
931 (pos === (this.pager.offset + this.pager.limit - 1)) ?
932 this.toNextPage() : Promise.resolve();
936 const row = this.dataSource.data[pos + 1];
937 const newIndex = this.getRowIndex(row);
938 if (selectedIndexes.filter(i => i === newIndex).length > 0) {
939 // Next row is already selected. User is reversing direction.
940 this.rowSelector.deselect(this.lastSelectedIndex);
941 this.lastSelectedIndex = newIndex;
943 this.selectMultipleRows(selectedIndexes.concat(newIndex));
950 getFirstRowInPage(): any {
951 return this.dataSource.data[this.pager.offset];
954 getLastRowInPage(): any {
955 return this.dataSource.data[this.pager.offset + this.pager.limit - 1];
959 this.selectOneRow(this.getRowIndex(this.getFirstRowInPage()));
963 this.selectOneRow(this.getRowIndex(this.getLastRowInPage()));
967 const rows = this.dataSource.getPageOfRows(this.pager);
968 const indexes = rows.map(r => this.getRowIndex(r));
969 this.rowSelector.select(indexes);
970 this.selectRowsInPageEmitter.emit();
973 toPrevPage(): Promise<any> {
974 if (this.pager.isFirstPage()) {
975 return Promise.reject('on first');
977 // temp ignore pager events since we're calling requestPage manually.
979 this.pager.decrement();
980 this.listenToPager();
981 return this.dataSource.requestPage(this.pager);
984 toNextPage(): Promise<any> {
985 if (this.pager.isLastPage()) {
986 return Promise.reject('on last');
988 // temp ignore pager events since we're calling requestPage manually.
990 this.pager.increment();
991 this.listenToPager();
992 return this.dataSource.requestPage(this.pager);
995 getAllRows(): Promise<any> {
996 const pager = new Pager();
998 pager.limit = MAX_ALL_ROW_COUNT;
999 return this.dataSource.requestPage(pager);
1002 // Returns a key/value pair object of visible column data as text.
1003 getRowAsFlatText(row: any): any {
1005 this.columnSet.displayColumns().forEach(col => {
1007 this.getColumnTextContent(row, col);
1012 getAllRowsAsText(): Observable<any> {
1013 return Observable.create(observer => {
1014 this.getAllRows().then(ok => {
1015 this.dataSource.data.forEach(row => {
1016 observer.next(this.getRowAsFlatText(row));
1018 observer.complete();
1023 removeFilters(): void {
1024 this.dataSource.filters = {};
1025 this.columnSet.displayColumns().forEach(col => { col.removeFilter(); });
1026 this.filterControls.forEach(ctl => ctl.reset());
1029 filtersSet(): boolean {
1030 return Object.keys(this.dataSource.filters).length > 0;
1033 gridToCsv(): Promise<string> {
1036 const columns = this.columnSet.displayColumns();
1039 columns.forEach(col => {
1040 csvStr += this.valueToCsv(col.label),
1044 csvStr = csvStr.replace(/,$/, '\n');
1046 return new Promise(resolve => {
1047 this.getAllRowsAsText().subscribe(
1049 columns.forEach(col => {
1050 csvStr += this.valueToCsv(row[col.name]);
1053 csvStr = csvStr.replace(/,$/, '\n');
1056 () => resolve(csvStr)
1062 // prepares a string for inclusion within a CSV document
1063 // by escaping commas and quotes and removing newlines.
1064 valueToCsv(str: string): string {
1066 if (!str) { return ''; }
1067 str = str.replace(/\n/g, '');
1068 if (str.match(/\,/) || str.match(/"/)) {
1069 str = str.replace(/"/g, '""');
1070 str = '"' + str + '"';
1076 if (!this.columnSet.idlClass) { return; }
1078 const pkeyField = this.idl.classes[this.columnSet.idlClass].pkey;
1079 const specifiedColumnOrder = this.autoGeneratedColumnOrder ?
1080 this.autoGeneratedColumnOrder.split(/,/) : [];
1082 // generate columns for all non-virtual fields on the IDL class
1083 const fields = this.idl.classes[this.columnSet.idlClass].fields
1084 .filter(field => !field.virtual);
1086 const sortedFields = this.autoGeneratedColumnOrder ?
1087 this.idl.sortIdlFields(fields, this.autoGeneratedColumnOrder.split(/,/)) :
1090 sortedFields.forEach(field => {
1091 if (!this.ignoredFields.filter(ignored => ignored === field.name).length) {
1092 const col = new GridColumn();
1093 col.name = field.name;
1094 col.label = field.label || field.name;
1095 col.idlFieldDef = field;
1096 col.idlClass = this.columnSet.idlClass;
1097 col.datatype = field.datatype;
1098 col.isIndex = (field.name === pkeyField);
1101 if (this.showDeclaredFieldsOnly) {
1105 this.columnSet.add(col);
1110 saveGridConfig(): Promise<any> {
1111 if (!this.persistKey) {
1112 throw new Error('Grid persistKey required to save columns');
1114 const conf = new GridPersistConf();
1116 conf.limit = this.pager.limit;
1117 conf.columns = this.columnSet.compileSaveObject();
1119 return this.store.setItem('eg.grid.' + this.persistKey, conf);
1122 // TODO: saveGridConfigAsOrgSetting(...)
1124 getGridConfig(persistKey: string): Promise<GridPersistConf> {
1125 if (!persistKey) { return Promise.resolve(null); }
1126 return this.store.getItem('eg.grid.' + persistKey);
1129 columnHasTextGenerator(col: GridColumn): boolean {
1130 return this.cellTextGenerator && col.name in this.cellTextGenerator;
1135 // Actions apply to specific rows
1136 export class GridToolbarAction {
1138 onClick: EventEmitter<any []>;
1139 action: (rows: any[]) => any; // DEPRECATED
1142 isGroup: boolean; // used for group placeholder entries
1143 isSeparator: boolean;
1144 disableOnRows: (rows: any[]) => boolean;
1147 // Buttons are global actions
1148 export class GridToolbarButton {
1150 onClick: EventEmitter<any []>;
1151 action: () => any; // DEPRECATED
1155 export class GridToolbarCheckbox {
1158 onChange: EventEmitter<boolean>;
1161 export class GridDataSource {
1166 allRowsRetrieved: boolean;
1167 requestingData: boolean;
1168 retrievalError: boolean;
1169 getRows: (pager: Pager, sort: any[]) => Observable<any>;
1179 this.allRowsRetrieved = false;
1182 // called from the template -- no data fetching
1183 getPageOfRows(pager: Pager): any[] {
1185 return this.data.slice(
1186 pager.offset, pager.limit + pager.offset
1187 ).filter(row => row !== undefined);
1192 // called on initial component load and user action (e.g. paging, sorting).
1193 requestPage(pager: Pager): Promise<any> {
1196 this.getPageOfRows(pager).length === pager.limit
1197 // already have all data
1198 || this.allRowsRetrieved
1199 // have no way to get more data.
1202 return Promise.resolve();
1205 // If we have to call out for data, set inFetch
1206 this.requestingData = true;
1207 this.retrievalError = false;
1209 return new Promise((resolve, reject) => {
1210 let idx = pager.offset;
1211 return this.getRows(pager, this.sort).subscribe(
1213 this.data[idx++] = row;
1214 // not updating this.requestingData, as having
1215 // retrieved one row doesn't mean we're done
1216 this.retrievalError = false;
1219 console.error(`grid getRows() error ${err}`);
1220 this.requestingData = false;
1221 this.retrievalError = true;
1225 this.checkAllRetrieved(pager, idx);
1226 this.requestingData = false;
1227 this.retrievalError = false;
1234 // See if the last getRows() call resulted in the final set of data.
1235 checkAllRetrieved(pager: Pager, idx: number) {
1236 if (this.allRowsRetrieved) { return; }
1238 if (idx === 0 || idx < (pager.limit + pager.offset)) {
1239 // last query returned nothing or less than one page.
1240 // confirm we have all of the preceding pages.
1241 if (!this.data.includes(undefined)) {
1242 this.allRowsRetrieved = true;
1243 pager.resultCount = this.data.length;