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 comparator: (valueA: any, valueB: any) => number;
44 // True if the column was automatically generated.
49 filterOperator: string;
50 filterInputDisabled: boolean;
51 filterIncludeOrgAncestors: boolean;
52 filterIncludeOrgDescendants: boolean;
54 flesher: (obj: any, col: GridColumn, item: any) => any;
56 getCellContext(row: any) {
60 userContext: this.cellContext
69 this.isFiltered = false;
70 this.filterValue = undefined;
71 this.filterOperator = '=';
72 this.filterInputDisabled = false;
73 this.filterIncludeOrgAncestors = false;
74 this.filterIncludeOrgDescendants = false;
78 export class GridColumnSet {
79 columns: GridColumn[];
81 indexColumn: GridColumn;
83 isFilterable: boolean;
84 isMultiSortable: boolean;
85 stockVisible: string[];
87 defaultHiddenFields: string[];
88 defaultVisibleFields: string[];
90 constructor(idl: IdlService, idlClass?: string) {
93 this.stockVisible = [];
94 this.idlClass = idlClass;
97 add(col: GridColumn) {
99 this.applyColumnDefaults(col);
101 if (!this.insertColumn(col)) {
102 // Column was rejected as a duplicate.
106 if (col.isIndex) { this.indexColumn = col; }
108 // track which fields are visible on page load.
110 this.stockVisible.push(col.name);
113 this.applyColumnSortability(col);
114 this.applyColumnFilterability(col);
117 // Returns true if the new column was inserted, false otherwise.
118 // Declared columns take precedence over auto-generated columns
119 // when collisions occur.
120 // Declared columns are inserted in front of auto columns.
121 insertColumn(col: GridColumn): boolean {
124 if (this.getColByName(col.name)) {
125 // New auto-generated column conflicts with existing
129 // No collisions. Add to the end of the list
130 this.columns.push(col);
135 // Adding a declared column.
138 for (let idx = 0; idx < this.columns.length; idx++) {
139 const testCol = this.columns[idx];
140 if (testCol.name === col.name) { // match found
141 if (testCol.isAuto) {
142 // new column takes precedence, remove the existing column.
143 this.columns.splice(idx, 1);
146 // New column does not take precedence. Avoid
153 // Delcared columns are inserted just before the first auto-column
154 for (let idx = 0; idx < this.columns.length; idx++) {
155 const testCol = this.columns[idx];
156 if (testCol.isAuto) {
158 this.columns.unshift(col);
160 this.columns.splice(idx, 0, col);
166 // No insertion point found. Toss the new column on the end.
167 this.columns.push(col);
171 getColByName(name: string): GridColumn {
172 return this.columns.filter(c => c.name === name)[0];
175 idlInfoFromDotpath(dotpath: string): any {
176 if (!dotpath || !this.idlClass) { return null; }
181 let nextIdlClass = this.idl.classes[this.idlClass];
183 const pathParts = dotpath.split(/\./);
185 for (let i = 0; i < pathParts.length; i++) {
187 const part = pathParts[i];
188 idlParent = idlField;
189 idlClass = nextIdlClass;
190 idlField = idlClass.field_map[part];
192 if (!idlField) { return null; } // invalid IDL path
194 if (i === pathParts.length - 1) {
195 // No more links to process.
199 if (idlField['class'] && (
200 idlField.datatype === 'link' ||
201 idlField.datatype === 'org_unit')) {
202 // The link class on the current field refers to the
203 // class of the link destination, not the current field.
204 // Mark it for processing during the next iteration.
205 nextIdlClass = this.idl.classes[idlField['class']];
210 idlParent: idlParent,
218 this.columns.forEach(col => {
222 col.visible = this.stockVisible.includes(col.name);
226 applyColumnDefaults(col: GridColumn) {
228 if (!col.idlFieldDef) {
229 const idlInfo = this.idlInfoFromDotpath(col.path || col.name);
231 col.idlFieldDef = idlInfo.idlField;
232 col.idlClass = idlInfo.idlClass.name;
234 col.label = col.idlFieldDef.label || col.idlFieldDef.name;
235 col.datatype = col.idlFieldDef.datatype;
240 if (!col.name) { col.name = col.path; }
241 if (!col.flex) { col.flex = 2; }
242 if (!col.align) { col.align = 'left'; }
243 if (!col.label) { col.label = col.name; }
244 if (!col.datatype) { col.datatype = 'text'; }
246 col.visible = !col.hidden;
249 applyColumnSortability(col: GridColumn) {
250 // column sortability defaults to the sortability of the column set.
251 if (col.isSortable === undefined && this.isSortable) {
252 col.isSortable = true;
255 if (col.isMultiSortable === undefined && this.isMultiSortable) {
256 col.isMultiSortable = true;
259 if (col.isMultiSortable) {
260 col.isSortable = true;
263 applyColumnFilterability(col: GridColumn) {
264 // column filterability defaults to the afilterability of the column set.
265 if (col.isFilterable === undefined && this.isFilterable) {
266 col.isFilterable = true;
270 displayColumns(): GridColumn[] {
271 return this.columns.filter(c => c.visible);
274 insertBefore(source: GridColumn, target: GridColumn) {
277 this.columns.forEach((col, idx) => {
278 if (col.name === target.name) { targetIdx = idx; }});
280 this.columns.forEach((col, idx) => {
281 if (col.name === source.name) { sourceIdx = idx; }});
283 if (sourceIdx >= 0) {
284 this.columns.splice(sourceIdx, 1);
287 this.columns.splice(targetIdx, 0, source);
290 // Move visible columns to the front of the list.
291 moveVisibleToFront() {
292 const newCols = this.displayColumns();
293 this.columns.forEach(col => {
294 if (!col.visible) { newCols.push(col); }});
295 this.columns = newCols;
298 moveColumn(col: GridColumn, diff: number) {
299 let srcIdx, targetIdx;
301 this.columns.forEach((c, i) => {
302 if (c.name === col.name) { srcIdx = i; }
305 targetIdx = srcIdx + diff;
308 } else if (targetIdx >= this.columns.length) {
309 // Target index follows the last visible column.
311 this.columns.forEach((c, idx) => {
312 if (c.visible) { lastVisible = idx; }
315 // When moving a column (down) causes one or more
316 // visible columns to shuffle forward, our column
317 // moves into the slot of the last visible column.
318 // Otherwise, put it into the slot directly following
319 // the last visible column.
320 targetIdx = srcIdx <= lastVisible ? lastVisible : lastVisible + 1;
323 // Splice column out of old position, insert at new position.
324 this.columns.splice(srcIdx, 1);
325 this.columns.splice(targetIdx, 0, col);
328 compileSaveObject(): GridColumnPersistConf[] {
329 // only store information about visible columns.
330 // scrunch the data down to just the needed info.
331 return this.displayColumns().map(col => {
332 const c: GridColumnPersistConf = {name : col.name};
333 if (col.align !== 'left') { c.align = col.align; }
334 if (col.flex !== 2) { c.flex = Number(col.flex); }
335 if (Number(col.sort)) { c.sort = Number(col.sort); }
340 applyColumnSettings(conf: GridColumnPersistConf[]) {
342 if (!conf || conf.length === 0) {
343 // No configuration is available, but we have a list of
344 // fields to show or hide by default
346 if (this.defaultVisibleFields) {
347 this.columns.forEach(col => {
348 if (this.defaultVisibleFields.includes(col.name)) {
355 } else if (this.defaultHiddenFields) {
356 this.defaultHiddenFields.forEach(name => {
357 const col = this.getColByName(name);
369 conf.forEach(colConf => {
370 const col = this.getColByName(colConf.name);
371 if (!col) { return; } // no such column in this grid.
374 if (colConf.align) { col.align = colConf.align; }
375 if (colConf.flex) { col.flex = Number(colConf.flex); }
376 if (colConf.sort) { col.sort = Number(colConf.sort); }
378 // Add to new columns array, avoid dupes.
379 if (newCols.filter(c => c.name === col.name).length === 0) {
384 // columns which are not expressed within the saved
385 // configuration are marked as non-visible and
386 // appended to the end of the new list of columns.
387 this.columns.forEach(c => {
388 if (conf.filter(cf => cf.name === c.name).length === 0) {
394 this.columns = newCols;
398 // Maps colunm names to functions which return plain text values for
399 // each mapped column on a given row. This is primarily useful for
400 // generating print-friendly content for grid cells rendered via
403 // USAGE NOTE: Since a cellTemplate can be passed arbitrary context
404 // but a GridCellTextGenerator only gets the row object,
405 // if it's important to include content that's not available
406 // by default in the row object, you may want to stick
407 // it in the row object as an additional attribute.
409 export interface GridCellTextGenerator {
410 [columnName: string]: (row: any) => string;
413 export class GridRowSelector {
414 indexes: {[string: string]: boolean};
420 // Returns true if all of the requested indexes exist in the selector.
421 contains(index: string | string[]): boolean {
422 const indexes = [].concat(index);
423 for (let i = 0; i < indexes.length; i++) { // early exit
424 if (!this.indexes[indexes[i]]) {
431 select(index: string | string[]) {
432 const indexes = [].concat(index);
433 indexes.forEach(i => this.indexes[i] = true);
436 deselect(index: string | string[]) {
437 const indexes = [].concat(index);
438 indexes.forEach(i => delete this.indexes[i]);
441 // Returns the list of selected index values.
442 // In some contexts (template checkboxes) the value for an index is
443 // set to false to deselect instead of having it removed (via deselect()).
444 // NOTE GridRowSelector has no knowledge of when a row is no longer
445 // present in the grid. Use GridContext.getSelectedRows() to get
446 // list of selected rows that are still present in the grid.
448 return Object.keys(this.indexes).filter(
449 ind => Boolean(this.indexes[ind]));
453 return this.selected().length === 0;
461 export interface GridRowFlairEntry {
462 icon: string; // name of material icon
463 title?: string; // tooltip string
466 export class GridColumnPersistConf {
473 export class GridPersistConf {
476 columns: GridColumnPersistConf[];
479 export class GridContext {
484 isFilterable: boolean;
485 stickyGridHeader: boolean;
486 isMultiSortable: boolean;
487 useLocalSort: boolean;
489 disableMultiSelect: boolean;
490 disableSelect: boolean;
491 dataSource: GridDataSource;
492 columnSet: GridColumnSet;
493 rowSelector: GridRowSelector;
494 toolbarButtons: GridToolbarButton[];
495 toolbarCheckboxes: GridToolbarCheckbox[];
496 toolbarActions: GridToolbarAction[];
497 lastSelectedIndex: any;
498 pageChanges: Subscription;
499 rowFlairIsEnabled: boolean;
500 rowFlairCallback: (row: any) => GridRowFlairEntry;
501 rowClassCallback: (row: any) => string;
502 cellClassCallback: (row: any, col: GridColumn) => string;
503 defaultVisibleFields: string[];
504 defaultHiddenFields: string[];
505 overflowCells: boolean;
506 disablePaging: boolean;
507 showDeclaredFieldsOnly: boolean;
508 cellTextGenerator: GridCellTextGenerator;
510 // Allow calling code to know when the select-all-rows-in-page
511 // action has occurred.
512 selectRowsInPageEmitter: EventEmitter<void>;
514 filterControls: QueryList<GridFilterControlComponent>;
516 // Services injected by our grid component
519 store: ServerStoreService;
520 format: FormatService;
525 store: ServerStoreService,
526 format: FormatService) {
531 this.format = format;
532 this.pager = new Pager();
533 this.rowSelector = new GridRowSelector();
534 this.toolbarButtons = [];
535 this.toolbarCheckboxes = [];
536 this.toolbarActions = [];
540 this.selectRowsInPageEmitter = new EventEmitter<void>();
541 this.columnSet = new GridColumnSet(this.idl, this.idlClass);
542 this.columnSet.isSortable = this.isSortable === true;
543 this.columnSet.isFilterable = this.isFilterable === true;
544 this.columnSet.isMultiSortable = this.isMultiSortable === true;
545 this.columnSet.defaultHiddenFields = this.defaultHiddenFields;
546 this.columnSet.defaultVisibleFields = this.defaultVisibleFields;
547 if (!this.pager.limit) {
548 this.pager.limit = this.disablePaging ? MAX_ALL_ROW_COUNT : 10;
550 this.generateColumns();
553 // Load initial settings and data.
555 this.applyGridConfig()
556 .then(ok => this.dataSource.requestPage(this.pager))
557 .then(ok => this.listenToPager());
564 applyGridConfig(): Promise<void> {
565 return this.getGridConfig(this.persistKey)
569 columns = conf.columns;
571 this.pager.limit = conf.limit;
575 // This is called regardless of the presence of saved
576 // settings so defaults can be applied.
577 this.columnSet.applyColumnSettings(columns);
582 // Give the UI time to settle before reloading grid data.
583 // This can help when data retrieval depends on a value
584 // getting modified by an angular digest cycle.
587 this.dataSource.reset();
588 this.dataSource.requestPage(this.pager);
592 reloadWithoutPagerReset() {
594 this.dataSource.reset();
595 this.dataSource.requestPage(this.pager);
599 // Sort the existing data source instead of requesting sorted
600 // data from the client. Reset pager to page 1. As with reload(),
601 // give the client a chance to setting before redisplaying.
605 this.sortLocalData();
606 this.dataSource.requestPage(this.pager);
610 // Subscribe or unsubscribe to page-change events from the pager.
612 if (this.pageChanges) { return; }
613 this.pageChanges = this.pager.onChange$.subscribe(
614 val => this.dataSource.requestPage(this.pager));
618 if (!this.pageChanges) { return; }
619 this.pageChanges.unsubscribe();
620 this.pageChanges = null;
623 // Sort data in the data source array
626 const sortDefs = this.dataSource.sort.map(sort => {
627 const column = this.columnSet.getColByName(sort.name);
635 if (!def.col.comparator) {
636 switch (def.col.datatype) {
640 def.col.comparator = (a, b) => {
643 if (a < b) { return -1; }
644 if (a > b) { return 1; }
649 def.col.comparator = (a, b) => {
650 if (a < b) { return -1; }
651 if (a > b) { return 1; }
660 this.dataSource.data.sort((rowA, rowB) => {
662 for (let idx = 0; idx < sortDefs.length; idx++) {
663 const sortDef = sortDefs[idx];
665 const valueA = this.getRowColumnValue(rowA, sortDef.col);
666 const valueB = this.getRowColumnValue(rowB, sortDef.col);
668 if (valueA === '' && valueB === '') { continue; }
669 if (valueA === '' && valueB !== '') { return 1; }
670 if (valueA !== '' && valueB === '') { return -1; }
672 const diff = sortDef.col.comparator(valueA, valueB);
673 if (diff === 0) { continue; }
675 return sortDef.dir === 'DESC' ? -diff : diff;
678 return 0; // No differences found.
682 getRowIndex(row: any): any {
683 const col = this.columnSet.indexColumn;
685 throw new Error('grid index column required');
687 return this.getRowColumnValue(row, col);
690 // Returns position in the data source array of the row with
691 // the provided index.
692 getRowPosition(index: any): number {
693 // for-loop for early exit
694 for (let idx = 0; idx < this.dataSource.data.length; idx++) {
695 const row = this.dataSource.data[idx];
696 if (row !== undefined && index === this.getRowIndex(row)) {
702 // Return the row with the provided index.
703 getRowByIndex(index: any): any {
704 for (let idx = 0; idx < this.dataSource.data.length; idx++) {
705 const row = this.dataSource.data[idx];
706 if (row !== undefined && index === this.getRowIndex(row)) {
712 // Returns all selected rows, regardless of whether they are
713 // currently visible in the grid display.
714 // De-selects previously selected rows which are no longer
715 // present in the grid.
716 getSelectedRows(): any[] {
720 this.rowSelector.selected().forEach(index => {
721 const row = this.getRowByIndex(index);
729 this.rowSelector.deselect(deleted);
733 rowIsSelected(row: any): boolean {
734 const index = this.getRowIndex(row);
735 return this.rowSelector.selected().filter(
740 getRowColumnValue(row: any, col: GridColumn): string {
744 val = this.nestedItemFieldValue(row, col);
745 } else if (col.name in row) {
746 val = this.getObjectFieldValue(row, col.name);
749 if (col.datatype === 'bool') {
750 // Avoid string-ifying bools so we can use an <eg-bool/>
751 // in the grid template.
755 return this.format.transform({
757 idlClass: col.idlClass,
758 idlField: col.idlFieldDef ? col.idlFieldDef.name : col.name,
759 datatype: col.datatype,
760 datePlusTime: Boolean(col.datePlusTime),
761 timezoneContextOrg: Number(col.timezoneContextOrg)
765 getObjectFieldValue(obj: any, name: string): any {
766 if (typeof obj[name] === 'function') {
773 nestedItemFieldValue(obj: any, col: GridColumn): string {
777 const original = obj;
778 const steps = col.path.split('.');
780 for (let i = 0; i < steps.length; i++) {
781 const step = steps[i];
783 if (obj === null || obj === undefined || typeof obj !== 'object') {
784 // We have run out of data to step through before
785 // reaching the end of the path. Conclude fleshing via
786 // callback if provided then exit.
787 if (col.flesher && obj !== undefined) {
788 return col.flesher(obj, col, original);
793 const class_ = obj.classname;
794 if (class_ && (idlClassDef = this.idl.classes[class_])) {
795 idlField = idlClassDef.field_map[step];
798 obj = this.getObjectFieldValue(obj, step);
801 // We found a nested IDL object which may or may not have
802 // been configured as a top-level column. Flesh the column
803 // metadata with our newly found IDL info.
806 col.datatype = idlField.datatype;
808 if (!col.idlFieldDef) {
809 idlField = col.idlFieldDef;
812 col.idlClass = idlClassDef.name;
815 col.label = idlField.label || idlField.name;
823 getColumnTextContent(row: any, col: GridColumn): string {
824 if (this.columnHasTextGenerator(col)) {
825 return this.cellTextGenerator[col.name](row);
827 if (col.cellTemplate) {
828 return ''; // avoid 'undefined' values
830 return this.getRowColumnValue(row, col);
835 selectOneRow(index: any) {
836 this.rowSelector.clear();
837 this.rowSelector.select(index);
838 this.lastSelectedIndex = index;
841 selectMultipleRows(indexes: any[]) {
842 this.rowSelector.clear();
843 this.rowSelector.select(indexes);
844 this.lastSelectedIndex = indexes[indexes.length - 1];
847 // selects or deselects an item, without affecting the others.
848 // returns true if the item is selected; false if de-selected.
849 toggleSelectOneRow(index: any) {
850 if (this.rowSelector.contains(index)) {
851 this.rowSelector.deselect(index);
855 this.rowSelector.select(index);
856 this.lastSelectedIndex = index;
860 selectRowByPos(pos: number) {
861 const row = this.dataSource.data[pos];
863 this.selectOneRow(this.getRowIndex(row));
867 selectPreviousRow() {
868 if (!this.lastSelectedIndex) { return; }
869 const pos = this.getRowPosition(this.lastSelectedIndex);
870 if (pos === this.pager.offset) {
871 this.toPrevPage().then(ok => this.selectLastRow(), err => {});
873 this.selectRowByPos(pos - 1);
878 if (!this.lastSelectedIndex) { return; }
879 const pos = this.getRowPosition(this.lastSelectedIndex);
880 if (pos === (this.pager.offset + this.pager.limit - 1)) {
881 this.toNextPage().then(ok => this.selectFirstRow(), err => {});
883 this.selectRowByPos(pos + 1);
888 // Select the previous row in addition to any currently selected row.
889 // However, if the previous row is already selected, assume the user
890 // has reversed direction and now wants to de-select the last selected row.
891 selectMultiRowsPrevious() {
892 if (!this.lastSelectedIndex) { return; }
893 const pos = this.getRowPosition(this.lastSelectedIndex);
894 const selectedIndexes = this.rowSelector.selected();
896 const promise = // load the previous page of data if needed
897 (pos === this.pager.offset) ? this.toPrevPage() : Promise.resolve();
901 const row = this.dataSource.data[pos - 1];
902 const newIndex = this.getRowIndex(row);
903 if (selectedIndexes.filter(i => i === newIndex).length > 0) {
904 // Prev row is already selected. User is reversing direction.
905 this.rowSelector.deselect(this.lastSelectedIndex);
906 this.lastSelectedIndex = newIndex;
908 this.selectMultipleRows(selectedIndexes.concat(newIndex));
916 // Select the next row in addition to any currently selected row.
917 // However, if the next row is already selected, assume the user
918 // has reversed direction and wants to de-select the last selected row.
919 selectMultiRowsNext() {
920 if (!this.lastSelectedIndex) { return; }
921 const pos = this.getRowPosition(this.lastSelectedIndex);
922 const selectedIndexes = this.rowSelector.selected();
924 const promise = // load the next page of data if needed
925 (pos === (this.pager.offset + this.pager.limit - 1)) ?
926 this.toNextPage() : Promise.resolve();
930 const row = this.dataSource.data[pos + 1];
931 const newIndex = this.getRowIndex(row);
932 if (selectedIndexes.filter(i => i === newIndex).length > 0) {
933 // Next row is already selected. User is reversing direction.
934 this.rowSelector.deselect(this.lastSelectedIndex);
935 this.lastSelectedIndex = newIndex;
937 this.selectMultipleRows(selectedIndexes.concat(newIndex));
944 getFirstRowInPage(): any {
945 return this.dataSource.data[this.pager.offset];
948 getLastRowInPage(): any {
949 return this.dataSource.data[this.pager.offset + this.pager.limit - 1];
953 this.selectOneRow(this.getRowIndex(this.getFirstRowInPage()));
957 this.selectOneRow(this.getRowIndex(this.getLastRowInPage()));
961 const rows = this.dataSource.getPageOfRows(this.pager);
962 const indexes = rows.map(r => this.getRowIndex(r));
963 this.rowSelector.select(indexes);
964 this.selectRowsInPageEmitter.emit();
967 toPrevPage(): Promise<any> {
968 if (this.pager.isFirstPage()) {
969 return Promise.reject('on first');
971 // temp ignore pager events since we're calling requestPage manually.
973 this.pager.decrement();
974 this.listenToPager();
975 return this.dataSource.requestPage(this.pager);
978 toNextPage(): Promise<any> {
979 if (this.pager.isLastPage()) {
980 return Promise.reject('on last');
982 // temp ignore pager events since we're calling requestPage manually.
984 this.pager.increment();
985 this.listenToPager();
986 return this.dataSource.requestPage(this.pager);
989 getAllRows(): Promise<any> {
990 const pager = new Pager();
992 pager.limit = MAX_ALL_ROW_COUNT;
993 return this.dataSource.requestPage(pager);
996 // Returns a key/value pair object of visible column data as text.
997 getRowAsFlatText(row: any): any {
999 this.columnSet.displayColumns().forEach(col => {
1001 this.getColumnTextContent(row, col);
1006 getAllRowsAsText(): Observable<any> {
1007 return Observable.create(observer => {
1008 this.getAllRows().then(ok => {
1009 this.dataSource.data.forEach(row => {
1010 observer.next(this.getRowAsFlatText(row));
1012 observer.complete();
1017 removeFilters(): void {
1018 this.dataSource.filters = {};
1019 this.columnSet.displayColumns().forEach(col => { col.removeFilter(); });
1020 this.filterControls.forEach(ctl => ctl.reset());
1023 filtersSet(): boolean {
1024 return Object.keys(this.dataSource.filters).length > 0;
1027 gridToCsv(): Promise<string> {
1030 const columns = this.columnSet.displayColumns();
1033 columns.forEach(col => {
1034 csvStr += this.valueToCsv(col.label),
1038 csvStr = csvStr.replace(/,$/, '\n');
1040 return new Promise(resolve => {
1041 this.getAllRowsAsText().subscribe(
1043 columns.forEach(col => {
1044 csvStr += this.valueToCsv(row[col.name]);
1047 csvStr = csvStr.replace(/,$/, '\n');
1050 () => resolve(csvStr)
1056 // prepares a string for inclusion within a CSV document
1057 // by escaping commas and quotes and removing newlines.
1058 valueToCsv(str: string): string {
1060 if (!str) { return ''; }
1061 str = str.replace(/\n/g, '');
1062 if (str.match(/\,/) || str.match(/"/)) {
1063 str = str.replace(/"/g, '""');
1064 str = '"' + str + '"';
1070 if (!this.columnSet.idlClass) { return; }
1072 const pkeyField = this.idl.classes[this.columnSet.idlClass].pkey;
1074 // generate columns for all non-virtual fields on the IDL class
1075 this.idl.classes[this.columnSet.idlClass].fields
1076 .filter(field => !field.virtual)
1078 const col = new GridColumn();
1079 col.name = field.name;
1080 col.label = field.label || field.name;
1081 col.idlFieldDef = field;
1082 col.idlClass = this.columnSet.idlClass;
1083 col.datatype = field.datatype;
1084 col.isIndex = (field.name === pkeyField);
1087 if (this.showDeclaredFieldsOnly) {
1091 this.columnSet.add(col);
1095 saveGridConfig(): Promise<any> {
1096 if (!this.persistKey) {
1097 throw new Error('Grid persistKey required to save columns');
1099 const conf = new GridPersistConf();
1101 conf.limit = this.pager.limit;
1102 conf.columns = this.columnSet.compileSaveObject();
1104 return this.store.setItem('eg.grid.' + this.persistKey, conf);
1107 // TODO: saveGridConfigAsOrgSetting(...)
1109 getGridConfig(persistKey: string): Promise<GridPersistConf> {
1110 if (!persistKey) { return Promise.resolve(null); }
1111 return this.store.getItem('eg.grid.' + persistKey);
1114 columnHasTextGenerator(col: GridColumn): boolean {
1115 return this.cellTextGenerator && col.name in this.cellTextGenerator;
1120 // Actions apply to specific rows
1121 export class GridToolbarAction {
1123 onClick: EventEmitter<any []>;
1124 action: (rows: any[]) => any; // DEPRECATED
1127 isGroup: boolean; // used for group placeholder entries
1128 isSeparator: boolean;
1129 disableOnRows: (rows: any[]) => boolean;
1132 // Buttons are global actions
1133 export class GridToolbarButton {
1135 onClick: EventEmitter<any []>;
1136 action: () => any; // DEPRECATED
1140 export class GridToolbarCheckbox {
1143 onChange: EventEmitter<boolean>;
1146 export class GridDataSource {
1151 allRowsRetrieved: boolean;
1152 requestingData: boolean;
1153 getRows: (pager: Pager, sort: any[]) => Observable<any>;
1163 this.allRowsRetrieved = false;
1166 // called from the template -- no data fetching
1167 getPageOfRows(pager: Pager): any[] {
1169 return this.data.slice(
1170 pager.offset, pager.limit + pager.offset
1171 ).filter(row => row !== undefined);
1176 // called on initial component load and user action (e.g. paging, sorting).
1177 requestPage(pager: Pager): Promise<any> {
1180 this.getPageOfRows(pager).length === pager.limit
1181 // already have all data
1182 || this.allRowsRetrieved
1183 // have no way to get more data.
1186 return Promise.resolve();
1189 // If we have to call out for data, set inFetch
1190 this.requestingData = true;
1192 return new Promise((resolve, reject) => {
1193 let idx = pager.offset;
1194 return this.getRows(pager, this.sort).subscribe(
1196 this.data[idx++] = row;
1197 this.requestingData = false;
1200 console.error(`grid getRows() error ${err}`);
1204 this.checkAllRetrieved(pager, idx);
1205 this.requestingData = false;
1212 // See if the last getRows() call resulted in the final set of data.
1213 checkAllRetrieved(pager: Pager, idx: number) {
1214 if (this.allRowsRetrieved) { return; }
1216 if (idx === 0 || idx < (pager.limit + pager.offset)) {
1217 // last query returned nothing or less than one page.
1218 // confirm we have all of the preceding pages.
1219 if (!this.data.includes(undefined)) {
1220 this.allRowsRetrieved = true;
1221 pager.resultCount = this.data.length;