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 rowSelector: GridRowSelector;
497 toolbarButtons: GridToolbarButton[];
498 toolbarCheckboxes: GridToolbarCheckbox[];
499 toolbarActions: GridToolbarAction[];
500 lastSelectedIndex: any;
501 pageChanges: Subscription;
502 rowFlairIsEnabled: boolean;
503 rowFlairCallback: (row: any) => GridRowFlairEntry;
504 rowClassCallback: (row: any) => string;
505 cellClassCallback: (row: any, col: GridColumn) => string;
506 defaultVisibleFields: string[];
507 defaultHiddenFields: string[];
508 overflowCells: boolean;
509 disablePaging: boolean;
510 showDeclaredFieldsOnly: boolean;
511 cellTextGenerator: GridCellTextGenerator;
513 // Allow calling code to know when the select-all-rows-in-page
514 // action has occurred.
515 selectRowsInPageEmitter: EventEmitter<void>;
517 filterControls: QueryList<GridFilterControlComponent>;
519 // Services injected by our grid component
522 store: ServerStoreService;
523 format: FormatService;
528 store: ServerStoreService,
529 format: FormatService) {
534 this.format = format;
535 this.pager = new Pager();
536 this.rowSelector = new GridRowSelector();
537 this.toolbarButtons = [];
538 this.toolbarCheckboxes = [];
539 this.toolbarActions = [];
543 this.selectRowsInPageEmitter = new EventEmitter<void>();
544 this.columnSet = new GridColumnSet(this.idl, this.idlClass);
545 this.columnSet.isSortable = this.isSortable === true;
546 this.columnSet.isFilterable = this.isFilterable === true;
547 this.columnSet.isMultiSortable = this.isMultiSortable === true;
548 this.columnSet.defaultHiddenFields = this.defaultHiddenFields;
549 this.columnSet.defaultVisibleFields = this.defaultVisibleFields;
550 if (!this.pager.limit) {
551 this.pager.limit = this.disablePaging ? MAX_ALL_ROW_COUNT : 10;
553 this.generateColumns();
556 // Load initial settings and data.
558 this.applyGridConfig()
559 .then(ok => this.dataSource.requestPage(this.pager))
560 .then(ok => this.listenToPager());
567 applyGridConfig(): Promise<void> {
568 return this.getGridConfig(this.persistKey)
572 columns = conf.columns;
573 if (conf.limit && !this.disablePaging) {
574 this.pager.limit = conf.limit;
578 // This is called regardless of the presence of saved
579 // settings so defaults can be applied.
580 this.columnSet.applyColumnSettings(columns);
585 // Give the UI time to settle before reloading grid data.
586 // This can help when data retrieval depends on a value
587 // getting modified by an angular digest cycle.
590 this.dataSource.reset();
591 this.dataSource.requestPage(this.pager);
595 reloadWithoutPagerReset() {
597 this.dataSource.reset();
598 this.dataSource.requestPage(this.pager);
602 // Sort the existing data source instead of requesting sorted
603 // data from the client. Reset pager to page 1. As with reload(),
604 // give the client a chance to setting before redisplaying.
608 this.sortLocalData();
609 this.dataSource.requestPage(this.pager);
613 // Subscribe or unsubscribe to page-change events from the pager.
615 if (this.pageChanges) { return; }
616 this.pageChanges = this.pager.onChange$.subscribe(
617 val => this.dataSource.requestPage(this.pager));
621 if (!this.pageChanges) { return; }
622 this.pageChanges.unsubscribe();
623 this.pageChanges = null;
626 // Sort data in the data source array
629 const sortDefs = this.dataSource.sort.map(sort => {
630 const column = this.columnSet.getColByName(sort.name);
638 if (!def.col.comparator) {
639 switch (def.col.datatype) {
643 def.col.comparator = (a, b) => {
646 if (a < b) { return -1; }
647 if (a > b) { return 1; }
652 def.col.comparator = (a, b) => {
653 if (a < b) { return -1; }
654 if (a > b) { return 1; }
663 this.dataSource.data.sort((rowA, rowB) => {
665 for (let idx = 0; idx < sortDefs.length; idx++) {
666 const sortDef = sortDefs[idx];
668 const valueA = this.getRowColumnValue(rowA, sortDef.col);
669 const valueB = this.getRowColumnValue(rowB, sortDef.col);
671 if (valueA === '' && valueB === '') { continue; }
672 if (valueA === '' && valueB !== '') { return 1; }
673 if (valueA !== '' && valueB === '') { return -1; }
675 const diff = sortDef.col.comparator(valueA, valueB);
676 if (diff === 0) { continue; }
678 return sortDef.dir === 'DESC' ? -diff : diff;
681 return 0; // No differences found.
685 getRowIndex(row: any): any {
686 const col = this.columnSet.indexColumn;
688 throw new Error('grid index column required');
690 return this.getRowColumnValue(row, col);
693 // Returns position in the data source array of the row with
694 // the provided index.
695 getRowPosition(index: any): number {
696 // for-loop for early exit
697 for (let idx = 0; idx < this.dataSource.data.length; idx++) {
698 const row = this.dataSource.data[idx];
699 if (row !== undefined && index === this.getRowIndex(row)) {
705 // Return the row with the provided index.
706 getRowByIndex(index: any): any {
707 for (let idx = 0; idx < this.dataSource.data.length; idx++) {
708 const row = this.dataSource.data[idx];
709 if (row !== undefined && index === this.getRowIndex(row)) {
715 // Returns all selected rows, regardless of whether they are
716 // currently visible in the grid display.
717 // De-selects previously selected rows which are no longer
718 // present in the grid.
719 getSelectedRows(): any[] {
723 this.rowSelector.selected().forEach(index => {
724 const row = this.getRowByIndex(index);
732 this.rowSelector.deselect(deleted);
736 rowIsSelected(row: any): boolean {
737 const index = this.getRowIndex(row);
738 return this.rowSelector.selected().filter(
743 getRowColumnValue(row: any, col: GridColumn): string {
747 val = this.nestedItemFieldValue(row, col);
748 } else if (col.name in row) {
749 val = this.getObjectFieldValue(row, col.name);
752 if (col.datatype === 'bool') {
753 // Avoid string-ifying bools so we can use an <eg-bool/>
754 // in the grid template.
758 return this.format.transform({
760 idlClass: col.idlClass,
761 idlField: col.idlFieldDef ? col.idlFieldDef.name : col.name,
762 datatype: col.datatype,
763 datePlusTime: Boolean(col.datePlusTime),
764 timezoneContextOrg: Number(col.timezoneContextOrg)
768 getObjectFieldValue(obj: any, name: string): any {
769 if (typeof obj[name] === 'function') {
776 nestedItemFieldValue(obj: any, col: GridColumn): string {
780 const original = obj;
781 const steps = col.path.split('.');
783 for (let i = 0; i < steps.length; i++) {
784 const step = steps[i];
786 if (obj === null || obj === undefined || typeof obj !== 'object') {
787 // We have run out of data to step through before
788 // reaching the end of the path. Conclude fleshing via
789 // callback if provided then exit.
790 if (col.flesher && obj !== undefined) {
791 return col.flesher(obj, col, original);
796 const class_ = obj.classname;
797 if (class_ && (idlClassDef = this.idl.classes[class_])) {
798 idlField = idlClassDef.field_map[step];
801 obj = this.getObjectFieldValue(obj, step);
804 // We found a nested IDL object which may or may not have
805 // been configured as a top-level column. Flesh the column
806 // metadata with our newly found IDL info.
809 col.datatype = idlField.datatype;
811 if (!col.idlFieldDef) {
812 idlField = col.idlFieldDef;
815 col.idlClass = idlClassDef.name;
818 col.label = idlField.label || idlField.name;
826 getColumnTextContent(row: any, col: GridColumn): string {
827 if (this.columnHasTextGenerator(col)) {
828 const str = this.cellTextGenerator[col.name](row);
829 return (str === null || str === undefined) ? '' : str;
831 if (col.cellTemplate) {
832 return ''; // avoid 'undefined' values
834 return this.getRowColumnValue(row, col);
839 selectOneRow(index: any) {
840 this.rowSelector.clear();
841 this.rowSelector.select(index);
842 this.lastSelectedIndex = index;
845 selectMultipleRows(indexes: any[]) {
846 this.rowSelector.clear();
847 this.rowSelector.select(indexes);
848 this.lastSelectedIndex = indexes[indexes.length - 1];
851 // selects or deselects an item, without affecting the others.
852 // returns true if the item is selected; false if de-selected.
853 toggleSelectOneRow(index: any) {
854 if (this.rowSelector.contains(index)) {
855 this.rowSelector.deselect(index);
859 this.rowSelector.select(index);
860 this.lastSelectedIndex = index;
864 selectRowByPos(pos: number) {
865 const row = this.dataSource.data[pos];
867 this.selectOneRow(this.getRowIndex(row));
871 selectPreviousRow() {
872 if (!this.lastSelectedIndex) { return; }
873 const pos = this.getRowPosition(this.lastSelectedIndex);
874 if (pos === this.pager.offset) {
875 this.toPrevPage().then(ok => this.selectLastRow(), err => {});
877 this.selectRowByPos(pos - 1);
882 if (!this.lastSelectedIndex) { return; }
883 const pos = this.getRowPosition(this.lastSelectedIndex);
884 if (pos === (this.pager.offset + this.pager.limit - 1)) {
885 this.toNextPage().then(ok => this.selectFirstRow(), err => {});
887 this.selectRowByPos(pos + 1);
892 // Select the previous row in addition to any currently selected row.
893 // However, if the previous row is already selected, assume the user
894 // has reversed direction and now wants to de-select the last selected row.
895 selectMultiRowsPrevious() {
896 if (!this.lastSelectedIndex) { return; }
897 const pos = this.getRowPosition(this.lastSelectedIndex);
898 const selectedIndexes = this.rowSelector.selected();
900 const promise = // load the previous page of data if needed
901 (pos === this.pager.offset) ? this.toPrevPage() : Promise.resolve();
905 const row = this.dataSource.data[pos - 1];
906 const newIndex = this.getRowIndex(row);
907 if (selectedIndexes.filter(i => i === newIndex).length > 0) {
908 // Prev row is already selected. User is reversing direction.
909 this.rowSelector.deselect(this.lastSelectedIndex);
910 this.lastSelectedIndex = newIndex;
912 this.selectMultipleRows(selectedIndexes.concat(newIndex));
920 // Select the next row in addition to any currently selected row.
921 // However, if the next row is already selected, assume the user
922 // has reversed direction and wants to de-select the last selected row.
923 selectMultiRowsNext() {
924 if (!this.lastSelectedIndex) { return; }
925 const pos = this.getRowPosition(this.lastSelectedIndex);
926 const selectedIndexes = this.rowSelector.selected();
928 const promise = // load the next page of data if needed
929 (pos === (this.pager.offset + this.pager.limit - 1)) ?
930 this.toNextPage() : Promise.resolve();
934 const row = this.dataSource.data[pos + 1];
935 const newIndex = this.getRowIndex(row);
936 if (selectedIndexes.filter(i => i === newIndex).length > 0) {
937 // Next row is already selected. User is reversing direction.
938 this.rowSelector.deselect(this.lastSelectedIndex);
939 this.lastSelectedIndex = newIndex;
941 this.selectMultipleRows(selectedIndexes.concat(newIndex));
948 getFirstRowInPage(): any {
949 return this.dataSource.data[this.pager.offset];
952 getLastRowInPage(): any {
953 return this.dataSource.data[this.pager.offset + this.pager.limit - 1];
957 this.selectOneRow(this.getRowIndex(this.getFirstRowInPage()));
961 this.selectOneRow(this.getRowIndex(this.getLastRowInPage()));
965 const rows = this.dataSource.getPageOfRows(this.pager);
966 const indexes = rows.map(r => this.getRowIndex(r));
967 this.rowSelector.select(indexes);
968 this.selectRowsInPageEmitter.emit();
971 toPrevPage(): Promise<any> {
972 if (this.pager.isFirstPage()) {
973 return Promise.reject('on first');
975 // temp ignore pager events since we're calling requestPage manually.
977 this.pager.decrement();
978 this.listenToPager();
979 return this.dataSource.requestPage(this.pager);
982 toNextPage(): Promise<any> {
983 if (this.pager.isLastPage()) {
984 return Promise.reject('on last');
986 // temp ignore pager events since we're calling requestPage manually.
988 this.pager.increment();
989 this.listenToPager();
990 return this.dataSource.requestPage(this.pager);
993 getAllRows(): Promise<any> {
994 const pager = new Pager();
996 pager.limit = MAX_ALL_ROW_COUNT;
997 return this.dataSource.requestPage(pager);
1000 // Returns a key/value pair object of visible column data as text.
1001 getRowAsFlatText(row: any): any {
1003 this.columnSet.displayColumns().forEach(col => {
1005 this.getColumnTextContent(row, col);
1010 getAllRowsAsText(): Observable<any> {
1011 return Observable.create(observer => {
1012 this.getAllRows().then(ok => {
1013 this.dataSource.data.forEach(row => {
1014 observer.next(this.getRowAsFlatText(row));
1016 observer.complete();
1021 removeFilters(): void {
1022 this.dataSource.filters = {};
1023 this.columnSet.displayColumns().forEach(col => { col.removeFilter(); });
1024 this.filterControls.forEach(ctl => ctl.reset());
1027 filtersSet(): boolean {
1028 return Object.keys(this.dataSource.filters).length > 0;
1031 gridToCsv(): Promise<string> {
1034 const columns = this.columnSet.displayColumns();
1037 columns.forEach(col => {
1038 csvStr += this.valueToCsv(col.label),
1042 csvStr = csvStr.replace(/,$/, '\n');
1044 return new Promise(resolve => {
1045 this.getAllRowsAsText().subscribe(
1047 columns.forEach(col => {
1048 csvStr += this.valueToCsv(row[col.name]);
1051 csvStr = csvStr.replace(/,$/, '\n');
1054 () => resolve(csvStr)
1060 // prepares a string for inclusion within a CSV document
1061 // by escaping commas and quotes and removing newlines.
1062 valueToCsv(str: string): string {
1064 if (!str) { return ''; }
1065 str = str.replace(/\n/g, '');
1066 if (str.match(/\,/) || str.match(/"/)) {
1067 str = str.replace(/"/g, '""');
1068 str = '"' + str + '"';
1074 if (!this.columnSet.idlClass) { return; }
1076 const pkeyField = this.idl.classes[this.columnSet.idlClass].pkey;
1078 // generate columns for all non-virtual fields on the IDL class
1079 this.idl.classes[this.columnSet.idlClass].fields
1080 .filter(field => !field.virtual)
1082 const col = new GridColumn();
1083 col.name = field.name;
1084 col.label = field.label || field.name;
1085 col.idlFieldDef = field;
1086 col.idlClass = this.columnSet.idlClass;
1087 col.datatype = field.datatype;
1088 col.isIndex = (field.name === pkeyField);
1091 if (this.showDeclaredFieldsOnly) {
1095 this.columnSet.add(col);
1099 saveGridConfig(): Promise<any> {
1100 if (!this.persistKey) {
1101 throw new Error('Grid persistKey required to save columns');
1103 const conf = new GridPersistConf();
1105 conf.limit = this.pager.limit;
1106 conf.columns = this.columnSet.compileSaveObject();
1108 return this.store.setItem('eg.grid.' + this.persistKey, conf);
1111 // TODO: saveGridConfigAsOrgSetting(...)
1113 getGridConfig(persistKey: string): Promise<GridPersistConf> {
1114 if (!persistKey) { return Promise.resolve(null); }
1115 return this.store.getItem('eg.grid.' + persistKey);
1118 columnHasTextGenerator(col: GridColumn): boolean {
1119 return this.cellTextGenerator && col.name in this.cellTextGenerator;
1124 // Actions apply to specific rows
1125 export class GridToolbarAction {
1127 onClick: EventEmitter<any []>;
1128 action: (rows: any[]) => any; // DEPRECATED
1131 isGroup: boolean; // used for group placeholder entries
1132 isSeparator: boolean;
1133 disableOnRows: (rows: any[]) => boolean;
1136 // Buttons are global actions
1137 export class GridToolbarButton {
1139 onClick: EventEmitter<any []>;
1140 action: () => any; // DEPRECATED
1144 export class GridToolbarCheckbox {
1147 onChange: EventEmitter<boolean>;
1150 export class GridDataSource {
1155 allRowsRetrieved: boolean;
1156 requestingData: boolean;
1157 retrievalError: boolean;
1158 getRows: (pager: Pager, sort: any[]) => Observable<any>;
1168 this.allRowsRetrieved = false;
1171 // called from the template -- no data fetching
1172 getPageOfRows(pager: Pager): any[] {
1174 return this.data.slice(
1175 pager.offset, pager.limit + pager.offset
1176 ).filter(row => row !== undefined);
1181 // called on initial component load and user action (e.g. paging, sorting).
1182 requestPage(pager: Pager): Promise<any> {
1185 this.getPageOfRows(pager).length === pager.limit
1186 // already have all data
1187 || this.allRowsRetrieved
1188 // have no way to get more data.
1191 return Promise.resolve();
1194 // If we have to call out for data, set inFetch
1195 this.requestingData = true;
1196 this.retrievalError = false;
1198 return new Promise((resolve, reject) => {
1199 let idx = pager.offset;
1200 return this.getRows(pager, this.sort).subscribe(
1202 this.data[idx++] = row;
1203 this.requestingData = false;
1204 this.retrievalError = false;
1207 console.error(`grid getRows() error ${err}`);
1208 this.requestingData = false;
1209 this.retrievalError = true;
1213 this.checkAllRetrieved(pager, idx);
1214 this.requestingData = false;
1215 this.retrievalError = false;
1222 // See if the last getRows() call resulted in the final set of data.
1223 checkAllRetrieved(pager: Pager, idx: number) {
1224 if (this.allRowsRetrieved) { return; }
1226 if (idx === 0 || idx < (pager.limit + pager.offset)) {
1227 // last query returned nothing or less than one page.
1228 // confirm we have all of the preceding pages.
1229 if (!this.data.includes(undefined)) {
1230 this.allRowsRetrieved = true;
1231 pager.resultCount = this.data.length;