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.datatype = col.idlFieldDef.datatype;
237 col.label = col.idlFieldDef.label || col.idlFieldDef.name;
242 if (!col.name) { col.name = col.path; }
243 if (!col.flex) { col.flex = 2; }
244 if (!col.align) { col.align = 'left'; }
245 if (!col.label) { col.label = col.name; }
246 if (!col.datatype) { col.datatype = 'text'; }
248 col.visible = !col.hidden;
251 applyColumnSortability(col: GridColumn) {
252 // column sortability defaults to the sortability of the column set.
253 if (col.isSortable === undefined && this.isSortable) {
254 col.isSortable = true;
257 if (col.isMultiSortable === undefined && this.isMultiSortable) {
258 col.isMultiSortable = true;
261 if (col.isMultiSortable) {
262 col.isSortable = true;
265 applyColumnFilterability(col: GridColumn) {
266 // column filterability defaults to the afilterability of the column set.
267 if (col.isFilterable === undefined && this.isFilterable) {
268 col.isFilterable = true;
272 displayColumns(): GridColumn[] {
273 return this.columns.filter(c => c.visible);
276 insertBefore(source: GridColumn, target: GridColumn) {
279 this.columns.forEach((col, idx) => {
280 if (col.name === target.name) { targetIdx = idx; }});
282 this.columns.forEach((col, idx) => {
283 if (col.name === source.name) { sourceIdx = idx; }});
285 if (sourceIdx >= 0) {
286 this.columns.splice(sourceIdx, 1);
289 this.columns.splice(targetIdx, 0, source);
292 // Move visible columns to the front of the list.
293 moveVisibleToFront() {
294 const newCols = this.displayColumns();
295 this.columns.forEach(col => {
296 if (!col.visible) { newCols.push(col); }});
297 this.columns = newCols;
300 moveColumn(col: GridColumn, diff: number) {
301 let srcIdx, targetIdx;
303 this.columns.forEach((c, i) => {
304 if (c.name === col.name) { srcIdx = i; }
307 targetIdx = srcIdx + diff;
310 } else if (targetIdx >= this.columns.length) {
311 // Target index follows the last visible column.
313 this.columns.forEach((c, idx) => {
314 if (c.visible) { lastVisible = idx; }
317 // When moving a column (down) causes one or more
318 // visible columns to shuffle forward, our column
319 // moves into the slot of the last visible column.
320 // Otherwise, put it into the slot directly following
321 // the last visible column.
322 targetIdx = srcIdx <= lastVisible ? lastVisible : lastVisible + 1;
325 // Splice column out of old position, insert at new position.
326 this.columns.splice(srcIdx, 1);
327 this.columns.splice(targetIdx, 0, col);
330 compileSaveObject(): GridColumnPersistConf[] {
331 // only store information about visible columns.
332 // scrunch the data down to just the needed info.
333 return this.displayColumns().map(col => {
334 const c: GridColumnPersistConf = {name : col.name};
335 if (col.align !== 'left') { c.align = col.align; }
336 if (col.flex !== 2) { c.flex = Number(col.flex); }
337 if (Number(col.sort)) { c.sort = Number(col.sort); }
342 applyColumnSettings(conf: GridColumnPersistConf[]) {
344 if (!conf || conf.length === 0) {
345 // No configuration is available, but we have a list of
346 // fields to show or hide by default
348 if (this.defaultVisibleFields) {
349 this.columns.forEach(col => {
350 if (this.defaultVisibleFields.includes(col.name)) {
357 } else if (this.defaultHiddenFields) {
358 this.defaultHiddenFields.forEach(name => {
359 const col = this.getColByName(name);
371 conf.forEach(colConf => {
372 const col = this.getColByName(colConf.name);
373 if (!col) { return; } // no such column in this grid.
376 if (colConf.align) { col.align = colConf.align; }
377 if (colConf.flex) { col.flex = Number(colConf.flex); }
378 if (colConf.sort) { col.sort = Number(colConf.sort); }
380 // Add to new columns array, avoid dupes.
381 if (newCols.filter(c => c.name === col.name).length === 0) {
386 // columns which are not expressed within the saved
387 // configuration are marked as non-visible and
388 // appended to the end of the new list of columns.
389 this.columns.forEach(c => {
390 if (conf.filter(cf => cf.name === c.name).length === 0) {
396 this.columns = newCols;
400 // Maps colunm names to functions which return plain text values for
401 // each mapped column on a given row. This is primarily useful for
402 // generating print-friendly content for grid cells rendered via
405 // USAGE NOTE: Since a cellTemplate can be passed arbitrary context
406 // but a GridCellTextGenerator only gets the row object,
407 // if it's important to include content that's not available
408 // by default in the row object, you may want to stick
409 // it in the row object as an additional attribute.
411 export interface GridCellTextGenerator {
412 [columnName: string]: (row: any) => string;
415 export class GridRowSelector {
416 indexes: {[string: string]: boolean};
422 // Returns true if all of the requested indexes exist in the selector.
423 contains(index: string | string[]): boolean {
424 const indexes = [].concat(index);
425 for (let i = 0; i < indexes.length; i++) { // early exit
426 if (!this.indexes[indexes[i]]) {
433 select(index: string | string[]) {
434 const indexes = [].concat(index);
435 indexes.forEach(i => this.indexes[i] = true);
438 deselect(index: string | string[]) {
439 const indexes = [].concat(index);
440 indexes.forEach(i => delete this.indexes[i]);
443 // Returns the list of selected index values.
444 // In some contexts (template checkboxes) the value for an index is
445 // set to false to deselect instead of having it removed (via deselect()).
446 // NOTE GridRowSelector has no knowledge of when a row is no longer
447 // present in the grid. Use GridContext.getSelectedRows() to get
448 // list of selected rows that are still present in the grid.
450 return Object.keys(this.indexes).filter(
451 ind => Boolean(this.indexes[ind]));
455 return this.selected().length === 0;
463 export interface GridRowFlairEntry {
464 icon: string; // name of material icon
465 title?: string; // tooltip string
468 export class GridColumnPersistConf {
475 export class GridPersistConf {
478 columns: GridColumnPersistConf[];
481 export class GridContext {
486 isFilterable: boolean;
487 stickyGridHeader: boolean;
488 isMultiSortable: boolean;
489 useLocalSort: boolean;
491 disableMultiSelect: boolean;
492 disableSelect: boolean;
493 dataSource: GridDataSource;
494 columnSet: GridColumnSet;
495 rowSelector: GridRowSelector;
496 toolbarButtons: GridToolbarButton[];
497 toolbarCheckboxes: GridToolbarCheckbox[];
498 toolbarActions: GridToolbarAction[];
499 lastSelectedIndex: any;
500 pageChanges: Subscription;
501 rowFlairIsEnabled: boolean;
502 rowFlairCallback: (row: any) => GridRowFlairEntry;
503 rowClassCallback: (row: any) => string;
504 cellClassCallback: (row: any, col: GridColumn) => string;
505 defaultVisibleFields: string[];
506 defaultHiddenFields: string[];
507 overflowCells: boolean;
508 disablePaging: boolean;
509 showDeclaredFieldsOnly: boolean;
510 cellTextGenerator: GridCellTextGenerator;
512 // Allow calling code to know when the select-all-rows-in-page
513 // action has occurred.
514 selectRowsInPageEmitter: EventEmitter<void>;
516 filterControls: QueryList<GridFilterControlComponent>;
518 // Services injected by our grid component
521 store: ServerStoreService;
522 format: FormatService;
527 store: ServerStoreService,
528 format: FormatService) {
533 this.format = format;
534 this.pager = new Pager();
535 this.rowSelector = new GridRowSelector();
536 this.toolbarButtons = [];
537 this.toolbarCheckboxes = [];
538 this.toolbarActions = [];
542 this.selectRowsInPageEmitter = new EventEmitter<void>();
543 this.columnSet = new GridColumnSet(this.idl, this.idlClass);
544 this.columnSet.isSortable = this.isSortable === true;
545 this.columnSet.isFilterable = this.isFilterable === true;
546 this.columnSet.isMultiSortable = this.isMultiSortable === true;
547 this.columnSet.defaultHiddenFields = this.defaultHiddenFields;
548 this.columnSet.defaultVisibleFields = this.defaultVisibleFields;
549 if (!this.pager.limit) {
550 this.pager.limit = this.disablePaging ? MAX_ALL_ROW_COUNT : 10;
552 this.generateColumns();
555 // Load initial settings and data.
557 this.applyGridConfig()
558 .then(ok => this.dataSource.requestPage(this.pager))
559 .then(ok => this.listenToPager());
566 applyGridConfig(): Promise<void> {
567 return this.getGridConfig(this.persistKey)
571 columns = conf.columns;
573 this.pager.limit = conf.limit;
577 // This is called regardless of the presence of saved
578 // settings so defaults can be applied.
579 this.columnSet.applyColumnSettings(columns);
584 // Give the UI time to settle before reloading grid data.
585 // This can help when data retrieval depends on a value
586 // getting modified by an angular digest cycle.
589 this.dataSource.reset();
590 this.dataSource.requestPage(this.pager);
594 reloadWithoutPagerReset() {
596 this.dataSource.reset();
597 this.dataSource.requestPage(this.pager);
601 // Sort the existing data source instead of requesting sorted
602 // data from the client. Reset pager to page 1. As with reload(),
603 // give the client a chance to setting before redisplaying.
607 this.sortLocalData();
608 this.dataSource.requestPage(this.pager);
612 // Subscribe or unsubscribe to page-change events from the pager.
614 if (this.pageChanges) { return; }
615 this.pageChanges = this.pager.onChange$.subscribe(
616 val => this.dataSource.requestPage(this.pager));
620 if (!this.pageChanges) { return; }
621 this.pageChanges.unsubscribe();
622 this.pageChanges = null;
625 // Sort data in the data source array
628 const sortDefs = this.dataSource.sort.map(sort => {
629 const column = this.columnSet.getColByName(sort.name);
637 if (!def.col.comparator) {
638 switch (def.col.datatype) {
642 def.col.comparator = (a, b) => {
645 if (a < b) { return -1; }
646 if (a > b) { return 1; }
651 def.col.comparator = (a, b) => {
652 if (a < b) { return -1; }
653 if (a > b) { return 1; }
662 this.dataSource.data.sort((rowA, rowB) => {
664 for (let idx = 0; idx < sortDefs.length; idx++) {
665 const sortDef = sortDefs[idx];
667 const valueA = this.getRowColumnValue(rowA, sortDef.col);
668 const valueB = this.getRowColumnValue(rowB, sortDef.col);
670 if (valueA === '' && valueB === '') { continue; }
671 if (valueA === '' && valueB !== '') { return 1; }
672 if (valueA !== '' && valueB === '') { return -1; }
674 const diff = sortDef.col.comparator(valueA, valueB);
675 if (diff === 0) { continue; }
677 return sortDef.dir === 'DESC' ? -diff : diff;
680 return 0; // No differences found.
684 getRowIndex(row: any): any {
685 const col = this.columnSet.indexColumn;
687 throw new Error('grid index column required');
689 return this.getRowColumnValue(row, col);
692 // Returns position in the data source array of the row with
693 // the provided index.
694 getRowPosition(index: any): number {
695 // for-loop for early exit
696 for (let idx = 0; idx < this.dataSource.data.length; idx++) {
697 const row = this.dataSource.data[idx];
698 if (row !== undefined && index === this.getRowIndex(row)) {
704 // Return the row with the provided index.
705 getRowByIndex(index: any): any {
706 for (let idx = 0; idx < this.dataSource.data.length; idx++) {
707 const row = this.dataSource.data[idx];
708 if (row !== undefined && index === this.getRowIndex(row)) {
714 // Returns all selected rows, regardless of whether they are
715 // currently visible in the grid display.
716 // De-selects previously selected rows which are no longer
717 // present in the grid.
718 getSelectedRows(): any[] {
722 this.rowSelector.selected().forEach(index => {
723 const row = this.getRowByIndex(index);
731 this.rowSelector.deselect(deleted);
735 rowIsSelected(row: any): boolean {
736 const index = this.getRowIndex(row);
737 return this.rowSelector.selected().filter(
742 getRowColumnValue(row: any, col: GridColumn): string {
746 val = this.nestedItemFieldValue(row, col);
747 } else if (col.name in row) {
748 val = this.getObjectFieldValue(row, col.name);
751 if (col.datatype === 'bool') {
752 // Avoid string-ifying bools so we can use an <eg-bool/>
753 // in the grid template.
757 return this.format.transform({
759 idlClass: col.idlClass,
760 idlField: col.idlFieldDef ? col.idlFieldDef.name : col.name,
761 datatype: col.datatype,
762 datePlusTime: Boolean(col.datePlusTime),
763 timezoneContextOrg: Number(col.timezoneContextOrg)
767 getObjectFieldValue(obj: any, name: string): any {
768 if (typeof obj[name] === 'function') {
775 nestedItemFieldValue(obj: any, col: GridColumn): string {
779 const original = obj;
780 const steps = col.path.split('.');
782 for (let i = 0; i < steps.length; i++) {
783 const step = steps[i];
785 if (obj === null || obj === undefined || typeof obj !== 'object') {
786 // We have run out of data to step through before
787 // reaching the end of the path. Conclude fleshing via
788 // callback if provided then exit.
789 if (col.flesher && obj !== undefined) {
790 return col.flesher(obj, col, original);
795 const class_ = obj.classname;
796 if (class_ && (idlClassDef = this.idl.classes[class_])) {
797 idlField = idlClassDef.field_map[step];
800 obj = this.getObjectFieldValue(obj, step);
803 // We found a nested IDL object which may or may not have
804 // been configured as a top-level column. Flesh the column
805 // metadata with our newly found IDL info.
808 col.datatype = idlField.datatype;
810 if (!col.idlFieldDef) {
811 idlField = col.idlFieldDef;
814 col.idlClass = idlClassDef.name;
817 col.label = idlField.label || idlField.name;
825 getColumnTextContent(row: any, col: GridColumn): string {
826 if (this.columnHasTextGenerator(col)) {
827 const str = this.cellTextGenerator[col.name](row);
828 return (str === null || str === undefined) ? '' : str;
830 if (col.cellTemplate) {
831 return ''; // avoid 'undefined' values
833 return this.getRowColumnValue(row, col);
838 selectOneRow(index: any) {
839 this.rowSelector.clear();
840 this.rowSelector.select(index);
841 this.lastSelectedIndex = index;
844 selectMultipleRows(indexes: any[]) {
845 this.rowSelector.clear();
846 this.rowSelector.select(indexes);
847 this.lastSelectedIndex = indexes[indexes.length - 1];
850 // selects or deselects an item, without affecting the others.
851 // returns true if the item is selected; false if de-selected.
852 toggleSelectOneRow(index: any) {
853 if (this.rowSelector.contains(index)) {
854 this.rowSelector.deselect(index);
858 this.rowSelector.select(index);
859 this.lastSelectedIndex = index;
863 selectRowByPos(pos: number) {
864 const row = this.dataSource.data[pos];
866 this.selectOneRow(this.getRowIndex(row));
870 selectPreviousRow() {
871 if (!this.lastSelectedIndex) { return; }
872 const pos = this.getRowPosition(this.lastSelectedIndex);
873 if (pos === this.pager.offset) {
874 this.toPrevPage().then(ok => this.selectLastRow(), err => {});
876 this.selectRowByPos(pos - 1);
881 if (!this.lastSelectedIndex) { return; }
882 const pos = this.getRowPosition(this.lastSelectedIndex);
883 if (pos === (this.pager.offset + this.pager.limit - 1)) {
884 this.toNextPage().then(ok => this.selectFirstRow(), err => {});
886 this.selectRowByPos(pos + 1);
891 // Select the previous row in addition to any currently selected row.
892 // However, if the previous row is already selected, assume the user
893 // has reversed direction and now wants to de-select the last selected row.
894 selectMultiRowsPrevious() {
895 if (!this.lastSelectedIndex) { return; }
896 const pos = this.getRowPosition(this.lastSelectedIndex);
897 const selectedIndexes = this.rowSelector.selected();
899 const promise = // load the previous page of data if needed
900 (pos === this.pager.offset) ? this.toPrevPage() : Promise.resolve();
904 const row = this.dataSource.data[pos - 1];
905 const newIndex = this.getRowIndex(row);
906 if (selectedIndexes.filter(i => i === newIndex).length > 0) {
907 // Prev row is already selected. User is reversing direction.
908 this.rowSelector.deselect(this.lastSelectedIndex);
909 this.lastSelectedIndex = newIndex;
911 this.selectMultipleRows(selectedIndexes.concat(newIndex));
919 // Select the next row in addition to any currently selected row.
920 // However, if the next row is already selected, assume the user
921 // has reversed direction and wants to de-select the last selected row.
922 selectMultiRowsNext() {
923 if (!this.lastSelectedIndex) { return; }
924 const pos = this.getRowPosition(this.lastSelectedIndex);
925 const selectedIndexes = this.rowSelector.selected();
927 const promise = // load the next page of data if needed
928 (pos === (this.pager.offset + this.pager.limit - 1)) ?
929 this.toNextPage() : Promise.resolve();
933 const row = this.dataSource.data[pos + 1];
934 const newIndex = this.getRowIndex(row);
935 if (selectedIndexes.filter(i => i === newIndex).length > 0) {
936 // Next row is already selected. User is reversing direction.
937 this.rowSelector.deselect(this.lastSelectedIndex);
938 this.lastSelectedIndex = newIndex;
940 this.selectMultipleRows(selectedIndexes.concat(newIndex));
947 getFirstRowInPage(): any {
948 return this.dataSource.data[this.pager.offset];
951 getLastRowInPage(): any {
952 return this.dataSource.data[this.pager.offset + this.pager.limit - 1];
956 this.selectOneRow(this.getRowIndex(this.getFirstRowInPage()));
960 this.selectOneRow(this.getRowIndex(this.getLastRowInPage()));
964 const rows = this.dataSource.getPageOfRows(this.pager);
965 const indexes = rows.map(r => this.getRowIndex(r));
966 this.rowSelector.select(indexes);
967 this.selectRowsInPageEmitter.emit();
970 toPrevPage(): Promise<any> {
971 if (this.pager.isFirstPage()) {
972 return Promise.reject('on first');
974 // temp ignore pager events since we're calling requestPage manually.
976 this.pager.decrement();
977 this.listenToPager();
978 return this.dataSource.requestPage(this.pager);
981 toNextPage(): Promise<any> {
982 if (this.pager.isLastPage()) {
983 return Promise.reject('on last');
985 // temp ignore pager events since we're calling requestPage manually.
987 this.pager.increment();
988 this.listenToPager();
989 return this.dataSource.requestPage(this.pager);
992 getAllRows(): Promise<any> {
993 const pager = new Pager();
995 pager.limit = MAX_ALL_ROW_COUNT;
996 return this.dataSource.requestPage(pager);
999 // Returns a key/value pair object of visible column data as text.
1000 getRowAsFlatText(row: any): any {
1002 this.columnSet.displayColumns().forEach(col => {
1004 this.getColumnTextContent(row, col);
1009 getAllRowsAsText(): Observable<any> {
1010 return Observable.create(observer => {
1011 this.getAllRows().then(ok => {
1012 this.dataSource.data.forEach(row => {
1013 observer.next(this.getRowAsFlatText(row));
1015 observer.complete();
1020 removeFilters(): void {
1021 this.dataSource.filters = {};
1022 this.columnSet.displayColumns().forEach(col => { col.removeFilter(); });
1023 this.filterControls.forEach(ctl => ctl.reset());
1026 filtersSet(): boolean {
1027 return Object.keys(this.dataSource.filters).length > 0;
1030 gridToCsv(): Promise<string> {
1033 const columns = this.columnSet.displayColumns();
1036 columns.forEach(col => {
1037 csvStr += this.valueToCsv(col.label),
1041 csvStr = csvStr.replace(/,$/, '\n');
1043 return new Promise(resolve => {
1044 this.getAllRowsAsText().subscribe(
1046 columns.forEach(col => {
1047 csvStr += this.valueToCsv(row[col.name]);
1050 csvStr = csvStr.replace(/,$/, '\n');
1053 () => resolve(csvStr)
1059 // prepares a string for inclusion within a CSV document
1060 // by escaping commas and quotes and removing newlines.
1061 valueToCsv(str: string): string {
1063 if (!str) { return ''; }
1064 str = str.replace(/\n/g, '');
1065 if (str.match(/\,/) || str.match(/"/)) {
1066 str = str.replace(/"/g, '""');
1067 str = '"' + str + '"';
1073 if (!this.columnSet.idlClass) { return; }
1075 const pkeyField = this.idl.classes[this.columnSet.idlClass].pkey;
1077 // generate columns for all non-virtual fields on the IDL class
1078 this.idl.classes[this.columnSet.idlClass].fields
1079 .filter(field => !field.virtual)
1081 const col = new GridColumn();
1082 col.name = field.name;
1083 col.label = field.label || field.name;
1084 col.idlFieldDef = field;
1085 col.idlClass = this.columnSet.idlClass;
1086 col.datatype = field.datatype;
1087 col.isIndex = (field.name === pkeyField);
1090 if (this.showDeclaredFieldsOnly) {
1094 this.columnSet.add(col);
1098 saveGridConfig(): Promise<any> {
1099 if (!this.persistKey) {
1100 throw new Error('Grid persistKey required to save columns');
1102 const conf = new GridPersistConf();
1104 conf.limit = this.pager.limit;
1105 conf.columns = this.columnSet.compileSaveObject();
1107 return this.store.setItem('eg.grid.' + this.persistKey, conf);
1110 // TODO: saveGridConfigAsOrgSetting(...)
1112 getGridConfig(persistKey: string): Promise<GridPersistConf> {
1113 if (!persistKey) { return Promise.resolve(null); }
1114 return this.store.getItem('eg.grid.' + persistKey);
1117 columnHasTextGenerator(col: GridColumn): boolean {
1118 return this.cellTextGenerator && col.name in this.cellTextGenerator;
1123 // Actions apply to specific rows
1124 export class GridToolbarAction {
1126 onClick: EventEmitter<any []>;
1127 action: (rows: any[]) => any; // DEPRECATED
1130 isGroup: boolean; // used for group placeholder entries
1131 isSeparator: boolean;
1132 disableOnRows: (rows: any[]) => boolean;
1135 // Buttons are global actions
1136 export class GridToolbarButton {
1138 onClick: EventEmitter<any []>;
1139 action: () => any; // DEPRECATED
1143 export class GridToolbarCheckbox {
1146 onChange: EventEmitter<boolean>;
1149 export class GridDataSource {
1154 allRowsRetrieved: boolean;
1155 requestingData: boolean;
1156 getRows: (pager: Pager, sort: any[]) => Observable<any>;
1166 this.allRowsRetrieved = false;
1169 // called from the template -- no data fetching
1170 getPageOfRows(pager: Pager): any[] {
1172 return this.data.slice(
1173 pager.offset, pager.limit + pager.offset
1174 ).filter(row => row !== undefined);
1179 // called on initial component load and user action (e.g. paging, sorting).
1180 requestPage(pager: Pager): Promise<any> {
1183 this.getPageOfRows(pager).length === pager.limit
1184 // already have all data
1185 || this.allRowsRetrieved
1186 // have no way to get more data.
1189 return Promise.resolve();
1192 // If we have to call out for data, set inFetch
1193 this.requestingData = true;
1195 return new Promise((resolve, reject) => {
1196 let idx = pager.offset;
1197 return this.getRows(pager, this.sort).subscribe(
1199 this.data[idx++] = row;
1200 this.requestingData = false;
1203 console.error(`grid getRows() error ${err}`);
1207 this.checkAllRetrieved(pager, idx);
1208 this.requestingData = false;
1215 // See if the last getRows() call resulted in the final set of data.
1216 checkAllRetrieved(pager: Pager, idx: number) {
1217 if (this.allRowsRetrieved) { return; }
1219 if (idx === 0 || idx < (pager.limit + pager.offset)) {
1220 // last query returned nothing or less than one page.
1221 // confirm we have all of the preceding pages.
1222 if (!this.data.includes(undefined)) {
1223 this.allRowsRetrieved = true;
1224 pager.resultCount = this.data.length;