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>;
34 // Provide a way for cells that are generated via cellTemplate's
35 // to provide an alternate text value suitable for printing.
36 cellPrintValue: (row: any, cell: GridColumn) => string;
40 isDragTarget: boolean;
42 isFilterable: boolean;
44 isMultiSortable: boolean;
45 disableTooltip: boolean;
46 comparator: (valueA: any, valueB: any) => number;
48 // True if the column was automatically generated.
53 filterOperator: string;
54 filterInputDisabled: boolean;
55 filterIncludeOrgAncestors: boolean;
56 filterIncludeOrgDescendants: boolean;
58 flesher: (obj: any, col: GridColumn, item: any) => any;
60 getCellContext(row: any) {
64 userContext: this.cellContext
73 this.isFiltered = false;
74 this.filterValue = undefined;
75 this.filterOperator = '=';
76 this.filterInputDisabled = false;
77 this.filterIncludeOrgAncestors = false;
78 this.filterIncludeOrgDescendants = false;
82 export class GridColumnSet {
83 columns: GridColumn[];
85 indexColumn: GridColumn;
87 isFilterable: boolean;
88 isMultiSortable: boolean;
89 stockVisible: string[];
91 defaultHiddenFields: string[];
92 defaultVisibleFields: string[];
94 constructor(idl: IdlService, idlClass?: string) {
97 this.stockVisible = [];
98 this.idlClass = idlClass;
101 add(col: GridColumn) {
103 this.applyColumnDefaults(col);
105 if (!this.insertColumn(col)) {
106 // Column was rejected as a duplicate.
110 if (col.isIndex) { this.indexColumn = col; }
112 // track which fields are visible on page load.
114 this.stockVisible.push(col.name);
117 this.applyColumnSortability(col);
118 this.applyColumnFilterability(col);
121 // Returns true if the new column was inserted, false otherwise.
122 // Declared columns take precedence over auto-generated columns
123 // when collisions occur.
124 // Declared columns are inserted in front of auto columns.
125 insertColumn(col: GridColumn): boolean {
128 if (this.getColByName(col.name)) {
129 // New auto-generated column conflicts with existing
133 // No collisions. Add to the end of the list
134 this.columns.push(col);
139 // Adding a declared column.
142 for (let idx = 0; idx < this.columns.length; idx++) {
143 const testCol = this.columns[idx];
144 if (testCol.name === col.name) { // match found
145 if (testCol.isAuto) {
146 // new column takes precedence, remove the existing column.
147 this.columns.splice(idx, 1);
150 // New column does not take precedence. Avoid
157 // Delcared columns are inserted just before the first auto-column
158 for (let idx = 0; idx < this.columns.length; idx++) {
159 const testCol = this.columns[idx];
160 if (testCol.isAuto) {
162 this.columns.unshift(col);
164 this.columns.splice(idx, 0, col);
170 // No insertion point found. Toss the new column on the end.
171 this.columns.push(col);
175 getColByName(name: string): GridColumn {
176 return this.columns.filter(c => c.name === name)[0];
179 idlInfoFromDotpath(dotpath: string): any {
180 if (!dotpath || !this.idlClass) { return null; }
185 let nextIdlClass = this.idl.classes[this.idlClass];
187 const pathParts = dotpath.split(/\./);
189 for (let i = 0; i < pathParts.length; i++) {
191 const part = pathParts[i];
192 idlParent = idlField;
193 idlClass = nextIdlClass;
194 idlField = idlClass.field_map[part];
196 if (!idlField) { return null; } // invalid IDL path
198 if (i === pathParts.length - 1) {
199 // No more links to process.
203 if (idlField['class'] && (
204 idlField.datatype === 'link' ||
205 idlField.datatype === 'org_unit')) {
206 // The link class on the current field refers to the
207 // class of the link destination, not the current field.
208 // Mark it for processing during the next iteration.
209 nextIdlClass = this.idl.classes[idlField['class']];
214 idlParent: idlParent,
222 this.columns.forEach(col => {
226 col.visible = this.stockVisible.includes(col.name);
230 applyColumnDefaults(col: GridColumn) {
232 if (!col.idlFieldDef) {
233 const idlInfo = this.idlInfoFromDotpath(col.path || col.name);
235 col.idlFieldDef = idlInfo.idlField;
236 col.idlClass = idlInfo.idlClass.name;
238 col.label = col.idlFieldDef.label || col.idlFieldDef.name;
239 col.datatype = col.idlFieldDef.datatype;
244 if (!col.name) { col.name = col.path; }
245 if (!col.flex) { col.flex = 2; }
246 if (!col.align) { col.align = 'left'; }
247 if (!col.label) { col.label = col.name; }
248 if (!col.datatype) { col.datatype = 'text'; }
250 col.visible = !col.hidden;
253 applyColumnSortability(col: GridColumn) {
254 // column sortability defaults to the sortability of the column set.
255 if (col.isSortable === undefined && this.isSortable) {
256 col.isSortable = true;
259 if (col.isMultiSortable === undefined && this.isMultiSortable) {
260 col.isMultiSortable = true;
263 if (col.isMultiSortable) {
264 col.isSortable = true;
267 applyColumnFilterability(col: GridColumn) {
268 // column filterability defaults to the afilterability of the column set.
269 if (col.isFilterable === undefined && this.isFilterable) {
270 col.isFilterable = true;
274 displayColumns(): GridColumn[] {
275 return this.columns.filter(c => c.visible);
278 insertBefore(source: GridColumn, target: GridColumn) {
281 this.columns.forEach((col, idx) => {
282 if (col.name === target.name) { targetIdx = idx; }});
284 this.columns.forEach((col, idx) => {
285 if (col.name === source.name) { sourceIdx = idx; }});
287 if (sourceIdx >= 0) {
288 this.columns.splice(sourceIdx, 1);
291 this.columns.splice(targetIdx, 0, source);
294 // Move visible columns to the front of the list.
295 moveVisibleToFront() {
296 const newCols = this.displayColumns();
297 this.columns.forEach(col => {
298 if (!col.visible) { newCols.push(col); }});
299 this.columns = newCols;
302 moveColumn(col: GridColumn, diff: number) {
303 let srcIdx, targetIdx;
305 this.columns.forEach((c, i) => {
306 if (c.name === col.name) { srcIdx = i; }
309 targetIdx = srcIdx + diff;
312 } else if (targetIdx >= this.columns.length) {
313 // Target index follows the last visible column.
315 this.columns.forEach((c, idx) => {
316 if (c.visible) { lastVisible = idx; }
319 // When moving a column (down) causes one or more
320 // visible columns to shuffle forward, our column
321 // moves into the slot of the last visible column.
322 // Otherwise, put it into the slot directly following
323 // the last visible column.
324 targetIdx = srcIdx <= lastVisible ? lastVisible : lastVisible + 1;
327 // Splice column out of old position, insert at new position.
328 this.columns.splice(srcIdx, 1);
329 this.columns.splice(targetIdx, 0, col);
332 compileSaveObject(): GridColumnPersistConf[] {
333 // only store information about visible columns.
334 // scrunch the data down to just the needed info.
335 return this.displayColumns().map(col => {
336 const c: GridColumnPersistConf = {name : col.name};
337 if (col.align !== 'left') { c.align = col.align; }
338 if (col.flex !== 2) { c.flex = Number(col.flex); }
339 if (Number(col.sort)) { c.sort = Number(col.sort); }
344 applyColumnSettings(conf: GridColumnPersistConf[]) {
346 if (!conf || conf.length === 0) {
347 // No configuration is available, but we have a list of
348 // fields to show or hide by default
350 if (this.defaultVisibleFields) {
351 this.columns.forEach(col => {
352 if (this.defaultVisibleFields.includes(col.name)) {
359 } else if (this.defaultHiddenFields) {
360 this.defaultHiddenFields.forEach(name => {
361 const col = this.getColByName(name);
373 conf.forEach(colConf => {
374 const col = this.getColByName(colConf.name);
375 if (!col) { return; } // no such column in this grid.
378 if (colConf.align) { col.align = colConf.align; }
379 if (colConf.flex) { col.flex = Number(colConf.flex); }
380 if (colConf.sort) { col.sort = Number(colConf.sort); }
382 // Add to new columns array, avoid dupes.
383 if (newCols.filter(c => c.name === col.name).length === 0) {
388 // columns which are not expressed within the saved
389 // configuration are marked as non-visible and
390 // appended to the end of the new list of columns.
391 this.columns.forEach(c => {
392 if (conf.filter(cf => cf.name === c.name).length === 0) {
398 this.columns = newCols;
402 // Maps colunm names to functions which return plain text values for
403 // each mapped column on a given row. This is primarily useful for
404 // generating print-friendly content for grid cells rendered via
406 export interface GridCellTextGenerator {
407 [columnName: string]: (row: any) => string;
410 export class GridRowSelector {
411 indexes: {[string: string]: boolean};
417 // Returns true if all of the requested indexes exist in the selector.
418 contains(index: string | string[]): boolean {
419 const indexes = [].concat(index);
420 for (let i = 0; i < indexes.length; i++) { // early exit
421 if (!this.indexes[indexes[i]]) {
428 select(index: string | string[]) {
429 const indexes = [].concat(index);
430 indexes.forEach(i => this.indexes[i] = true);
433 deselect(index: string | string[]) {
434 const indexes = [].concat(index);
435 indexes.forEach(i => delete this.indexes[i]);
438 // Returns the list of selected index values.
439 // In some contexts (template checkboxes) the value for an index is
440 // set to false to deselect instead of having it removed (via deselect()).
441 // NOTE GridRowSelector has no knowledge of when a row is no longer
442 // present in the grid. Use GridContext.getSelectedRows() to get
443 // list of selected rows that are still present in the grid.
445 return Object.keys(this.indexes).filter(
446 ind => Boolean(this.indexes[ind]));
450 return this.selected().length === 0;
458 export interface GridRowFlairEntry {
459 icon: string; // name of material icon
460 title?: string; // tooltip string
463 export class GridColumnPersistConf {
470 export class GridPersistConf {
473 columns: GridColumnPersistConf[];
476 export class GridContext {
481 isFilterable: boolean;
482 stickyGridHeader: boolean;
483 isMultiSortable: boolean;
484 useLocalSort: boolean;
486 disableMultiSelect: boolean;
487 disableSelect: boolean;
488 dataSource: GridDataSource;
489 columnSet: GridColumnSet;
490 rowSelector: GridRowSelector;
491 toolbarButtons: GridToolbarButton[];
492 toolbarCheckboxes: GridToolbarCheckbox[];
493 toolbarActions: GridToolbarAction[];
494 lastSelectedIndex: any;
495 pageChanges: Subscription;
496 rowFlairIsEnabled: boolean;
497 rowFlairCallback: (row: any) => GridRowFlairEntry;
498 rowClassCallback: (row: any) => string;
499 cellClassCallback: (row: any, col: GridColumn) => string;
500 defaultVisibleFields: string[];
501 defaultHiddenFields: string[];
502 overflowCells: boolean;
503 disablePaging: boolean;
504 showDeclaredFieldsOnly: boolean;
505 cellTextGenerator: GridCellTextGenerator;
507 // Allow calling code to know when the select-all-rows-in-page
508 // action has occurred.
509 selectRowsInPageEmitter: EventEmitter<void>;
511 filterControls: QueryList<GridFilterControlComponent>;
513 // Services injected by our grid component
516 store: ServerStoreService;
517 format: FormatService;
522 store: ServerStoreService,
523 format: FormatService) {
528 this.format = format;
529 this.pager = new Pager();
530 this.rowSelector = new GridRowSelector();
531 this.toolbarButtons = [];
532 this.toolbarCheckboxes = [];
533 this.toolbarActions = [];
537 this.selectRowsInPageEmitter = new EventEmitter<void>();
538 this.columnSet = new GridColumnSet(this.idl, this.idlClass);
539 this.columnSet.isSortable = this.isSortable === true;
540 this.columnSet.isFilterable = this.isFilterable === true;
541 this.columnSet.isMultiSortable = this.isMultiSortable === true;
542 this.columnSet.defaultHiddenFields = this.defaultHiddenFields;
543 this.columnSet.defaultVisibleFields = this.defaultVisibleFields;
544 if (!this.pager.limit) {
545 this.pager.limit = this.disablePaging ? MAX_ALL_ROW_COUNT : 10;
547 this.generateColumns();
550 // Load initial settings and data.
552 this.applyGridConfig()
553 .then(ok => this.dataSource.requestPage(this.pager))
554 .then(ok => this.listenToPager());
561 applyGridConfig(): Promise<void> {
562 return this.getGridConfig(this.persistKey)
566 columns = conf.columns;
568 this.pager.limit = conf.limit;
572 // This is called regardless of the presence of saved
573 // settings so defaults can be applied.
574 this.columnSet.applyColumnSettings(columns);
579 // Give the UI time to settle before reloading grid data.
580 // This can help when data retrieval depends on a value
581 // getting modified by an angular digest cycle.
584 this.dataSource.reset();
585 this.dataSource.requestPage(this.pager);
589 reloadWithoutPagerReset() {
591 this.dataSource.reset();
592 this.dataSource.requestPage(this.pager);
596 // Sort the existing data source instead of requesting sorted
597 // data from the client. Reset pager to page 1. As with reload(),
598 // give the client a chance to setting before redisplaying.
602 this.sortLocalData();
603 this.dataSource.requestPage(this.pager);
607 // Subscribe or unsubscribe to page-change events from the pager.
609 if (this.pageChanges) { return; }
610 this.pageChanges = this.pager.onChange$.subscribe(
611 val => this.dataSource.requestPage(this.pager));
615 if (!this.pageChanges) { return; }
616 this.pageChanges.unsubscribe();
617 this.pageChanges = null;
620 // Sort data in the data source array
623 const sortDefs = this.dataSource.sort.map(sort => {
624 const column = this.columnSet.getColByName(sort.name);
632 if (!def.col.comparator) {
633 switch (def.col.datatype) {
637 def.col.comparator = (a, b) => {
640 if (a < b) { return -1; }
641 if (a > b) { return 1; }
646 def.col.comparator = (a, b) => {
647 if (a < b) { return -1; }
648 if (a > b) { return 1; }
657 this.dataSource.data.sort((rowA, rowB) => {
659 for (let idx = 0; idx < sortDefs.length; idx++) {
660 const sortDef = sortDefs[idx];
662 const valueA = this.getRowColumnValue(rowA, sortDef.col);
663 const valueB = this.getRowColumnValue(rowB, sortDef.col);
665 if (valueA === '' && valueB === '') { continue; }
666 if (valueA === '' && valueB !== '') { return 1; }
667 if (valueA !== '' && valueB === '') { return -1; }
669 const diff = sortDef.col.comparator(valueA, valueB);
670 if (diff === 0) { continue; }
672 return sortDef.dir === 'DESC' ? -diff : diff;
675 return 0; // No differences found.
679 getRowIndex(row: any): any {
680 const col = this.columnSet.indexColumn;
682 throw new Error('grid index column required');
684 return this.getRowColumnValue(row, col);
687 // Returns position in the data source array of the row with
688 // the provided index.
689 getRowPosition(index: any): number {
690 // for-loop for early exit
691 for (let idx = 0; idx < this.dataSource.data.length; idx++) {
692 const row = this.dataSource.data[idx];
693 if (row !== undefined && index === this.getRowIndex(row)) {
699 // Return the row with the provided index.
700 getRowByIndex(index: any): any {
701 for (let idx = 0; idx < this.dataSource.data.length; idx++) {
702 const row = this.dataSource.data[idx];
703 if (row !== undefined && index === this.getRowIndex(row)) {
709 // Returns all selected rows, regardless of whether they are
710 // currently visible in the grid display.
711 // De-selects previously selected rows which are no longer
712 // present in the grid.
713 getSelectedRows(): any[] {
717 this.rowSelector.selected().forEach(index => {
718 const row = this.getRowByIndex(index);
726 this.rowSelector.deselect(deleted);
730 rowIsSelected(row: any): boolean {
731 const index = this.getRowIndex(row);
732 return this.rowSelector.selected().filter(
737 getRowColumnValue(row: any, col: GridColumn): string {
741 val = this.nestedItemFieldValue(row, col);
742 } else if (col.name in row) {
743 val = this.getObjectFieldValue(row, col.name);
746 if (col.datatype === 'bool') {
747 // Avoid string-ifying bools so we can use an <eg-bool/>
748 // in the grid template.
752 return this.format.transform({
754 idlClass: col.idlClass,
755 idlField: col.idlFieldDef ? col.idlFieldDef.name : col.name,
756 datatype: col.datatype,
757 datePlusTime: Boolean(col.datePlusTime),
758 timezoneContextOrg: Number(col.timezoneContextOrg)
762 getObjectFieldValue(obj: any, name: string): any {
763 if (typeof obj[name] === 'function') {
770 nestedItemFieldValue(obj: any, col: GridColumn): string {
774 const original = obj;
775 const steps = col.path.split('.');
777 for (let i = 0; i < steps.length; i++) {
778 const step = steps[i];
780 if (obj === null || obj === undefined || typeof obj !== 'object') {
781 // We have run out of data to step through before
782 // reaching the end of the path. Conclude fleshing via
783 // callback if provided then exit.
784 if (col.flesher && obj !== undefined) {
785 return col.flesher(obj, col, original);
790 const class_ = obj.classname;
791 if (class_ && (idlClassDef = this.idl.classes[class_])) {
792 idlField = idlClassDef.field_map[step];
795 obj = this.getObjectFieldValue(obj, step);
798 // We found a nested IDL object which may or may not have
799 // been configured as a top-level column. Flesh the column
800 // metadata with our newly found IDL info.
803 col.datatype = idlField.datatype;
805 if (!col.idlFieldDef) {
806 idlField = col.idlFieldDef;
809 col.idlClass = idlClassDef.name;
812 col.label = idlField.label || idlField.name;
820 getColumnTextContent(row: any, col: GridColumn): string {
821 if (this.columnHasTextGenerator(col)) {
822 return this.cellTextGenerator[col.name](row);
824 if (col.cellTemplate) {
825 return ''; // avoid 'undefined' values
827 return this.getRowColumnValue(row, col);
832 selectOneRow(index: any) {
833 this.rowSelector.clear();
834 this.rowSelector.select(index);
835 this.lastSelectedIndex = index;
838 selectMultipleRows(indexes: any[]) {
839 this.rowSelector.clear();
840 this.rowSelector.select(indexes);
841 this.lastSelectedIndex = indexes[indexes.length - 1];
844 // selects or deselects an item, without affecting the others.
845 // returns true if the item is selected; false if de-selected.
846 toggleSelectOneRow(index: any) {
847 if (this.rowSelector.contains(index)) {
848 this.rowSelector.deselect(index);
852 this.rowSelector.select(index);
853 this.lastSelectedIndex = index;
857 selectRowByPos(pos: number) {
858 const row = this.dataSource.data[pos];
860 this.selectOneRow(this.getRowIndex(row));
864 selectPreviousRow() {
865 if (!this.lastSelectedIndex) { return; }
866 const pos = this.getRowPosition(this.lastSelectedIndex);
867 if (pos === this.pager.offset) {
868 this.toPrevPage().then(ok => this.selectLastRow(), err => {});
870 this.selectRowByPos(pos - 1);
875 if (!this.lastSelectedIndex) { return; }
876 const pos = this.getRowPosition(this.lastSelectedIndex);
877 if (pos === (this.pager.offset + this.pager.limit - 1)) {
878 this.toNextPage().then(ok => this.selectFirstRow(), err => {});
880 this.selectRowByPos(pos + 1);
885 // Select the previous row in addition to any currently selected row.
886 // However, if the previous row is already selected, assume the user
887 // has reversed direction and now wants to de-select the last selected row.
888 selectMultiRowsPrevious() {
889 if (!this.lastSelectedIndex) { return; }
890 const pos = this.getRowPosition(this.lastSelectedIndex);
891 const selectedIndexes = this.rowSelector.selected();
893 const promise = // load the previous page of data if needed
894 (pos === this.pager.offset) ? this.toPrevPage() : Promise.resolve();
898 const row = this.dataSource.data[pos - 1];
899 const newIndex = this.getRowIndex(row);
900 if (selectedIndexes.filter(i => i === newIndex).length > 0) {
901 // Prev row is already selected. User is reversing direction.
902 this.rowSelector.deselect(this.lastSelectedIndex);
903 this.lastSelectedIndex = newIndex;
905 this.selectMultipleRows(selectedIndexes.concat(newIndex));
913 // Select the next row in addition to any currently selected row.
914 // However, if the next row is already selected, assume the user
915 // has reversed direction and wants to de-select the last selected row.
916 selectMultiRowsNext() {
917 if (!this.lastSelectedIndex) { return; }
918 const pos = this.getRowPosition(this.lastSelectedIndex);
919 const selectedIndexes = this.rowSelector.selected();
921 const promise = // load the next page of data if needed
922 (pos === (this.pager.offset + this.pager.limit - 1)) ?
923 this.toNextPage() : Promise.resolve();
927 const row = this.dataSource.data[pos + 1];
928 const newIndex = this.getRowIndex(row);
929 if (selectedIndexes.filter(i => i === newIndex).length > 0) {
930 // Next row is already selected. User is reversing direction.
931 this.rowSelector.deselect(this.lastSelectedIndex);
932 this.lastSelectedIndex = newIndex;
934 this.selectMultipleRows(selectedIndexes.concat(newIndex));
941 getFirstRowInPage(): any {
942 return this.dataSource.data[this.pager.offset];
945 getLastRowInPage(): any {
946 return this.dataSource.data[this.pager.offset + this.pager.limit - 1];
950 this.selectOneRow(this.getRowIndex(this.getFirstRowInPage()));
954 this.selectOneRow(this.getRowIndex(this.getLastRowInPage()));
958 const rows = this.dataSource.getPageOfRows(this.pager);
959 const indexes = rows.map(r => this.getRowIndex(r));
960 this.rowSelector.select(indexes);
961 this.selectRowsInPageEmitter.emit();
964 toPrevPage(): Promise<any> {
965 if (this.pager.isFirstPage()) {
966 return Promise.reject('on first');
968 // temp ignore pager events since we're calling requestPage manually.
970 this.pager.decrement();
971 this.listenToPager();
972 return this.dataSource.requestPage(this.pager);
975 toNextPage(): Promise<any> {
976 if (this.pager.isLastPage()) {
977 return Promise.reject('on last');
979 // temp ignore pager events since we're calling requestPage manually.
981 this.pager.increment();
982 this.listenToPager();
983 return this.dataSource.requestPage(this.pager);
986 getAllRows(): Promise<any> {
987 const pager = new Pager();
989 pager.limit = MAX_ALL_ROW_COUNT;
990 return this.dataSource.requestPage(pager);
993 // Returns a key/value pair object of visible column data as text.
994 getRowAsFlatText(row: any): any {
996 this.columnSet.displayColumns().forEach(col => {
998 this.getColumnTextContent(row, col);
1003 getAllRowsAsText(): Observable<any> {
1004 return Observable.create(observer => {
1005 this.getAllRows().then(ok => {
1006 this.dataSource.data.forEach(row => {
1007 observer.next(this.getRowAsFlatText(row));
1009 observer.complete();
1014 removeFilters(): void {
1015 this.dataSource.filters = {};
1016 this.columnSet.displayColumns().forEach(col => { col.removeFilter(); });
1017 this.filterControls.forEach(ctl => ctl.reset());
1020 filtersSet(): boolean {
1021 return Object.keys(this.dataSource.filters).length > 0;
1024 gridToCsv(): Promise<string> {
1027 const columns = this.columnSet.displayColumns();
1030 columns.forEach(col => {
1031 csvStr += this.valueToCsv(col.label),
1035 csvStr = csvStr.replace(/,$/, '\n');
1037 return new Promise(resolve => {
1038 this.getAllRowsAsText().subscribe(
1040 columns.forEach(col => {
1041 csvStr += this.valueToCsv(row[col.name]);
1044 csvStr = csvStr.replace(/,$/, '\n');
1047 () => resolve(csvStr)
1053 // prepares a string for inclusion within a CSV document
1054 // by escaping commas and quotes and removing newlines.
1055 valueToCsv(str: string): string {
1057 if (!str) { return ''; }
1058 str = str.replace(/\n/g, '');
1059 if (str.match(/\,/) || str.match(/"/)) {
1060 str = str.replace(/"/g, '""');
1061 str = '"' + str + '"';
1067 if (!this.columnSet.idlClass) { return; }
1069 const pkeyField = this.idl.classes[this.columnSet.idlClass].pkey;
1071 // generate columns for all non-virtual fields on the IDL class
1072 this.idl.classes[this.columnSet.idlClass].fields
1073 .filter(field => !field.virtual)
1075 const col = new GridColumn();
1076 col.name = field.name;
1077 col.label = field.label || field.name;
1078 col.idlFieldDef = field;
1079 col.idlClass = this.columnSet.idlClass;
1080 col.datatype = field.datatype;
1081 col.isIndex = (field.name === pkeyField);
1084 if (this.showDeclaredFieldsOnly) {
1088 this.columnSet.add(col);
1092 saveGridConfig(): Promise<any> {
1093 if (!this.persistKey) {
1094 throw new Error('Grid persistKey required to save columns');
1096 const conf = new GridPersistConf();
1098 conf.limit = this.pager.limit;
1099 conf.columns = this.columnSet.compileSaveObject();
1101 return this.store.setItem('eg.grid.' + this.persistKey, conf);
1104 // TODO: saveGridConfigAsOrgSetting(...)
1106 getGridConfig(persistKey: string): Promise<GridPersistConf> {
1107 if (!persistKey) { return Promise.resolve(null); }
1108 return this.store.getItem('eg.grid.' + persistKey);
1111 columnHasTextGenerator(col: GridColumn): boolean {
1112 return this.cellTextGenerator && col.name in this.cellTextGenerator;
1117 // Actions apply to specific rows
1118 export class GridToolbarAction {
1120 onClick: EventEmitter<any []>;
1121 action: (rows: any[]) => any; // DEPRECATED
1124 isGroup: boolean; // used for group placeholder entries
1125 isSeparator: boolean;
1126 disableOnRows: (rows: any[]) => boolean;
1129 // Buttons are global actions
1130 export class GridToolbarButton {
1132 onClick: EventEmitter<any []>;
1133 action: () => any; // DEPRECATED
1137 export class GridToolbarCheckbox {
1140 onChange: EventEmitter<boolean>;
1143 export class GridDataSource {
1148 allRowsRetrieved: boolean;
1149 requestingData: boolean;
1150 getRows: (pager: Pager, sort: any[]) => Observable<any>;
1160 this.allRowsRetrieved = false;
1163 // called from the template -- no data fetching
1164 getPageOfRows(pager: Pager): any[] {
1166 return this.data.slice(
1167 pager.offset, pager.limit + pager.offset
1168 ).filter(row => row !== undefined);
1173 // called on initial component load and user action (e.g. paging, sorting).
1174 requestPage(pager: Pager): Promise<any> {
1177 this.getPageOfRows(pager).length === pager.limit
1178 // already have all data
1179 || this.allRowsRetrieved
1180 // have no way to get more data.
1183 return Promise.resolve();
1186 // If we have to call out for data, set inFetch
1187 this.requestingData = true;
1189 return new Promise((resolve, reject) => {
1190 let idx = pager.offset;
1191 return this.getRows(pager, this.sort).subscribe(
1193 this.data[idx++] = row;
1194 this.requestingData = false;
1197 console.error(`grid getRows() error ${err}`);
1201 this.checkAllRetrieved(pager, idx);
1202 this.requestingData = false;
1209 // See if the last getRows() call resulted in the final set of data.
1210 checkAllRetrieved(pager: Pager, idx: number) {
1211 if (this.allRowsRetrieved) { return; }
1213 if (idx === 0 || idx < (pager.limit + pager.offset)) {
1214 // last query returned nothing or less than one page.
1215 // confirm we have all of the preceding pages.
1216 if (!this.data.includes(undefined)) {
1217 this.allRowsRetrieved = true;
1218 pager.resultCount = this.data.length;