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 ignoredFields: string[];
509 overflowCells: boolean;
510 disablePaging: boolean;
511 showDeclaredFieldsOnly: boolean;
512 cellTextGenerator: GridCellTextGenerator;
514 // Allow calling code to know when the select-all-rows-in-page
515 // action has occurred.
516 selectRowsInPageEmitter: EventEmitter<void>;
518 filterControls: QueryList<GridFilterControlComponent>;
520 // Services injected by our grid component
523 store: ServerStoreService;
524 format: FormatService;
529 store: ServerStoreService,
530 format: FormatService) {
535 this.format = format;
536 this.pager = new Pager();
537 this.rowSelector = new GridRowSelector();
538 this.toolbarButtons = [];
539 this.toolbarCheckboxes = [];
540 this.toolbarActions = [];
544 this.selectRowsInPageEmitter = new EventEmitter<void>();
545 this.columnSet = new GridColumnSet(this.idl, this.idlClass);
546 this.columnSet.isSortable = this.isSortable === true;
547 this.columnSet.isFilterable = this.isFilterable === true;
548 this.columnSet.isMultiSortable = this.isMultiSortable === true;
549 this.columnSet.defaultHiddenFields = this.defaultHiddenFields;
550 this.columnSet.defaultVisibleFields = this.defaultVisibleFields;
551 if (!this.pager.limit) {
552 this.pager.limit = this.disablePaging ? MAX_ALL_ROW_COUNT : 10;
554 this.generateColumns();
557 // Load initial settings and data.
559 this.applyGridConfig()
560 .then(ok => this.dataSource.requestPage(this.pager))
561 .then(ok => this.listenToPager());
568 applyGridConfig(): Promise<void> {
569 return this.getGridConfig(this.persistKey)
573 columns = conf.columns;
574 if (conf.limit && !this.disablePaging) {
575 this.pager.limit = conf.limit;
579 // This is called regardless of the presence of saved
580 // settings so defaults can be applied.
581 this.columnSet.applyColumnSettings(columns);
586 // Give the UI time to settle before reloading grid data.
587 // This can help when data retrieval depends on a value
588 // getting modified by an angular digest cycle.
591 this.dataSource.reset();
592 this.dataSource.requestPage(this.pager);
596 reloadWithoutPagerReset() {
598 this.dataSource.reset();
599 this.dataSource.requestPage(this.pager);
603 // Sort the existing data source instead of requesting sorted
604 // data from the client. Reset pager to page 1. As with reload(),
605 // give the client a chance to setting before redisplaying.
609 this.sortLocalData();
610 this.dataSource.requestPage(this.pager);
614 // Subscribe or unsubscribe to page-change events from the pager.
616 if (this.pageChanges) { return; }
617 this.pageChanges = this.pager.onChange$.subscribe(
618 val => this.dataSource.requestPage(this.pager));
622 if (!this.pageChanges) { return; }
623 this.pageChanges.unsubscribe();
624 this.pageChanges = null;
627 // Sort data in the data source array
630 const sortDefs = this.dataSource.sort.map(sort => {
631 const column = this.columnSet.getColByName(sort.name);
639 if (!def.col.comparator) {
640 switch (def.col.datatype) {
644 def.col.comparator = (a, b) => {
647 if (a < b) { return -1; }
648 if (a > b) { return 1; }
653 def.col.comparator = (a, b) => {
654 if (a < b) { return -1; }
655 if (a > b) { return 1; }
664 this.dataSource.data.sort((rowA, rowB) => {
666 for (let idx = 0; idx < sortDefs.length; idx++) {
667 const sortDef = sortDefs[idx];
669 const valueA = this.getRowColumnValue(rowA, sortDef.col);
670 const valueB = this.getRowColumnValue(rowB, sortDef.col);
672 if (valueA === '' && valueB === '') { continue; }
673 if (valueA === '' && valueB !== '') { return 1; }
674 if (valueA !== '' && valueB === '') { return -1; }
676 const diff = sortDef.col.comparator(valueA, valueB);
677 if (diff === 0) { continue; }
679 return sortDef.dir === 'DESC' ? -diff : diff;
682 return 0; // No differences found.
686 getRowIndex(row: any): any {
687 const col = this.columnSet.indexColumn;
689 throw new Error('grid index column required');
691 return this.getRowColumnValue(row, col);
694 // Returns position in the data source array of the row with
695 // the provided index.
696 getRowPosition(index: any): number {
697 // for-loop for early exit
698 for (let idx = 0; idx < this.dataSource.data.length; idx++) {
699 const row = this.dataSource.data[idx];
700 if (row !== undefined && index === this.getRowIndex(row)) {
706 // Return the row with the provided index.
707 getRowByIndex(index: any): any {
708 for (let idx = 0; idx < this.dataSource.data.length; idx++) {
709 const row = this.dataSource.data[idx];
710 if (row !== undefined && index === this.getRowIndex(row)) {
716 // Returns all selected rows, regardless of whether they are
717 // currently visible in the grid display.
718 // De-selects previously selected rows which are no longer
719 // present in the grid.
720 getSelectedRows(): any[] {
724 this.rowSelector.selected().forEach(index => {
725 const row = this.getRowByIndex(index);
733 this.rowSelector.deselect(deleted);
737 rowIsSelected(row: any): boolean {
738 const index = this.getRowIndex(row);
739 return this.rowSelector.selected().filter(
744 getRowColumnValue(row: any, col: GridColumn): string {
748 val = this.nestedItemFieldValue(row, col);
749 } else if (col.name in row) {
750 val = this.getObjectFieldValue(row, col.name);
753 if (col.datatype === 'bool') {
754 // Avoid string-ifying bools so we can use an <eg-bool/>
755 // in the grid template.
759 return this.format.transform({
761 idlClass: col.idlClass,
762 idlField: col.idlFieldDef ? col.idlFieldDef.name : col.name,
763 datatype: col.datatype,
764 datePlusTime: Boolean(col.datePlusTime),
765 timezoneContextOrg: Number(col.timezoneContextOrg)
769 getObjectFieldValue(obj: any, name: string): any {
770 if (typeof obj[name] === 'function') {
777 nestedItemFieldValue(obj: any, col: GridColumn): string {
781 const original = obj;
782 const steps = col.path.split('.');
784 for (let i = 0; i < steps.length; i++) {
785 const step = steps[i];
787 if (obj === null || obj === undefined || typeof obj !== 'object') {
788 // We have run out of data to step through before
789 // reaching the end of the path. Conclude fleshing via
790 // callback if provided then exit.
791 if (col.flesher && obj !== undefined) {
792 return col.flesher(obj, col, original);
797 const class_ = obj.classname;
798 if (class_ && (idlClassDef = this.idl.classes[class_])) {
799 idlField = idlClassDef.field_map[step];
802 obj = this.getObjectFieldValue(obj, step);
805 // We found a nested IDL object which may or may not have
806 // been configured as a top-level column. Flesh the column
807 // metadata with our newly found IDL info.
810 col.datatype = idlField.datatype;
812 if (!col.idlFieldDef) {
813 idlField = col.idlFieldDef;
816 col.idlClass = idlClassDef.name;
819 col.label = idlField.label || idlField.name;
827 getColumnTextContent(row: any, col: GridColumn): string {
828 if (this.columnHasTextGenerator(col)) {
829 const str = this.cellTextGenerator[col.name](row);
830 return (str === null || str === undefined) ? '' : str;
832 if (col.cellTemplate) {
833 return ''; // avoid 'undefined' values
835 return this.getRowColumnValue(row, col);
840 selectOneRow(index: any) {
841 this.rowSelector.clear();
842 this.rowSelector.select(index);
843 this.lastSelectedIndex = index;
846 selectMultipleRows(indexes: any[]) {
847 this.rowSelector.clear();
848 this.rowSelector.select(indexes);
849 this.lastSelectedIndex = indexes[indexes.length - 1];
852 // selects or deselects an item, without affecting the others.
853 // returns true if the item is selected; false if de-selected.
854 toggleSelectOneRow(index: any) {
855 if (this.rowSelector.contains(index)) {
856 this.rowSelector.deselect(index);
860 this.rowSelector.select(index);
861 this.lastSelectedIndex = index;
865 selectRowByPos(pos: number) {
866 const row = this.dataSource.data[pos];
868 this.selectOneRow(this.getRowIndex(row));
872 selectPreviousRow() {
873 if (!this.lastSelectedIndex) { return; }
874 const pos = this.getRowPosition(this.lastSelectedIndex);
875 if (pos === this.pager.offset) {
876 this.toPrevPage().then(ok => this.selectLastRow(), err => {});
878 this.selectRowByPos(pos - 1);
883 if (!this.lastSelectedIndex) { return; }
884 const pos = this.getRowPosition(this.lastSelectedIndex);
885 if (pos === (this.pager.offset + this.pager.limit - 1)) {
886 this.toNextPage().then(ok => this.selectFirstRow(), err => {});
888 this.selectRowByPos(pos + 1);
893 // Select the previous row in addition to any currently selected row.
894 // However, if the previous row is already selected, assume the user
895 // has reversed direction and now wants to de-select the last selected row.
896 selectMultiRowsPrevious() {
897 if (!this.lastSelectedIndex) { return; }
898 const pos = this.getRowPosition(this.lastSelectedIndex);
899 const selectedIndexes = this.rowSelector.selected();
901 const promise = // load the previous page of data if needed
902 (pos === this.pager.offset) ? this.toPrevPage() : Promise.resolve();
906 const row = this.dataSource.data[pos - 1];
907 const newIndex = this.getRowIndex(row);
908 if (selectedIndexes.filter(i => i === newIndex).length > 0) {
909 // Prev row is already selected. User is reversing direction.
910 this.rowSelector.deselect(this.lastSelectedIndex);
911 this.lastSelectedIndex = newIndex;
913 this.selectMultipleRows(selectedIndexes.concat(newIndex));
921 // Select the next row in addition to any currently selected row.
922 // However, if the next row is already selected, assume the user
923 // has reversed direction and wants to de-select the last selected row.
924 selectMultiRowsNext() {
925 if (!this.lastSelectedIndex) { return; }
926 const pos = this.getRowPosition(this.lastSelectedIndex);
927 const selectedIndexes = this.rowSelector.selected();
929 const promise = // load the next page of data if needed
930 (pos === (this.pager.offset + this.pager.limit - 1)) ?
931 this.toNextPage() : Promise.resolve();
935 const row = this.dataSource.data[pos + 1];
936 const newIndex = this.getRowIndex(row);
937 if (selectedIndexes.filter(i => i === newIndex).length > 0) {
938 // Next row is already selected. User is reversing direction.
939 this.rowSelector.deselect(this.lastSelectedIndex);
940 this.lastSelectedIndex = newIndex;
942 this.selectMultipleRows(selectedIndexes.concat(newIndex));
949 getFirstRowInPage(): any {
950 return this.dataSource.data[this.pager.offset];
953 getLastRowInPage(): any {
954 return this.dataSource.data[this.pager.offset + this.pager.limit - 1];
958 this.selectOneRow(this.getRowIndex(this.getFirstRowInPage()));
962 this.selectOneRow(this.getRowIndex(this.getLastRowInPage()));
966 const rows = this.dataSource.getPageOfRows(this.pager);
967 const indexes = rows.map(r => this.getRowIndex(r));
968 this.rowSelector.select(indexes);
969 this.selectRowsInPageEmitter.emit();
972 toPrevPage(): Promise<any> {
973 if (this.pager.isFirstPage()) {
974 return Promise.reject('on first');
976 // temp ignore pager events since we're calling requestPage manually.
978 this.pager.decrement();
979 this.listenToPager();
980 return this.dataSource.requestPage(this.pager);
983 toNextPage(): Promise<any> {
984 if (this.pager.isLastPage()) {
985 return Promise.reject('on last');
987 // temp ignore pager events since we're calling requestPage manually.
989 this.pager.increment();
990 this.listenToPager();
991 return this.dataSource.requestPage(this.pager);
994 getAllRows(): Promise<any> {
995 const pager = new Pager();
997 pager.limit = MAX_ALL_ROW_COUNT;
998 return this.dataSource.requestPage(pager);
1001 // Returns a key/value pair object of visible column data as text.
1002 getRowAsFlatText(row: any): any {
1004 this.columnSet.displayColumns().forEach(col => {
1006 this.getColumnTextContent(row, col);
1011 getAllRowsAsText(): Observable<any> {
1012 return Observable.create(observer => {
1013 this.getAllRows().then(ok => {
1014 this.dataSource.data.forEach(row => {
1015 observer.next(this.getRowAsFlatText(row));
1017 observer.complete();
1022 removeFilters(): void {
1023 this.dataSource.filters = {};
1024 this.columnSet.displayColumns().forEach(col => { col.removeFilter(); });
1025 this.filterControls.forEach(ctl => ctl.reset());
1028 filtersSet(): boolean {
1029 return Object.keys(this.dataSource.filters).length > 0;
1032 gridToCsv(): Promise<string> {
1035 const columns = this.columnSet.displayColumns();
1038 columns.forEach(col => {
1039 csvStr += this.valueToCsv(col.label),
1043 csvStr = csvStr.replace(/,$/, '\n');
1045 return new Promise(resolve => {
1046 this.getAllRowsAsText().subscribe(
1048 columns.forEach(col => {
1049 csvStr += this.valueToCsv(row[col.name]);
1052 csvStr = csvStr.replace(/,$/, '\n');
1055 () => resolve(csvStr)
1061 // prepares a string for inclusion within a CSV document
1062 // by escaping commas and quotes and removing newlines.
1063 valueToCsv(str: string): string {
1065 if (!str) { return ''; }
1066 str = str.replace(/\n/g, '');
1067 if (str.match(/\,/) || str.match(/"/)) {
1068 str = str.replace(/"/g, '""');
1069 str = '"' + str + '"';
1075 if (!this.columnSet.idlClass) { return; }
1077 const pkeyField = this.idl.classes[this.columnSet.idlClass].pkey;
1079 // generate columns for all non-virtual fields on the IDL class
1080 this.idl.classes[this.columnSet.idlClass].fields
1081 .filter(field => !field.virtual)
1083 if (!this.ignoredFields.filter(ignored => ignored === field.name).length) {
1084 const col = new GridColumn();
1085 col.name = field.name;
1086 col.label = field.label || field.name;
1087 col.idlFieldDef = field;
1088 col.idlClass = this.columnSet.idlClass;
1089 col.datatype = field.datatype;
1090 col.isIndex = (field.name === pkeyField);
1093 if (this.showDeclaredFieldsOnly) {
1097 this.columnSet.add(col);
1102 saveGridConfig(): Promise<any> {
1103 if (!this.persistKey) {
1104 throw new Error('Grid persistKey required to save columns');
1106 const conf = new GridPersistConf();
1108 conf.limit = this.pager.limit;
1109 conf.columns = this.columnSet.compileSaveObject();
1111 return this.store.setItem('eg.grid.' + this.persistKey, conf);
1114 // TODO: saveGridConfigAsOrgSetting(...)
1116 getGridConfig(persistKey: string): Promise<GridPersistConf> {
1117 if (!persistKey) { return Promise.resolve(null); }
1118 return this.store.getItem('eg.grid.' + persistKey);
1121 columnHasTextGenerator(col: GridColumn): boolean {
1122 return this.cellTextGenerator && col.name in this.cellTextGenerator;
1127 // Actions apply to specific rows
1128 export class GridToolbarAction {
1130 onClick: EventEmitter<any []>;
1131 action: (rows: any[]) => any; // DEPRECATED
1134 isGroup: boolean; // used for group placeholder entries
1135 isSeparator: boolean;
1136 disableOnRows: (rows: any[]) => boolean;
1139 // Buttons are global actions
1140 export class GridToolbarButton {
1142 onClick: EventEmitter<any []>;
1143 action: () => any; // DEPRECATED
1147 export class GridToolbarCheckbox {
1150 onChange: EventEmitter<boolean>;
1153 export class GridDataSource {
1158 allRowsRetrieved: boolean;
1159 requestingData: boolean;
1160 retrievalError: boolean;
1161 getRows: (pager: Pager, sort: any[]) => Observable<any>;
1171 this.allRowsRetrieved = false;
1174 // called from the template -- no data fetching
1175 getPageOfRows(pager: Pager): any[] {
1177 return this.data.slice(
1178 pager.offset, pager.limit + pager.offset
1179 ).filter(row => row !== undefined);
1184 // called on initial component load and user action (e.g. paging, sorting).
1185 requestPage(pager: Pager): Promise<any> {
1188 this.getPageOfRows(pager).length === pager.limit
1189 // already have all data
1190 || this.allRowsRetrieved
1191 // have no way to get more data.
1194 return Promise.resolve();
1197 // If we have to call out for data, set inFetch
1198 this.requestingData = true;
1199 this.retrievalError = false;
1201 return new Promise((resolve, reject) => {
1202 let idx = pager.offset;
1203 return this.getRows(pager, this.sort).subscribe(
1205 this.data[idx++] = row;
1206 this.requestingData = false;
1207 this.retrievalError = false;
1210 console.error(`grid getRows() error ${err}`);
1211 this.requestingData = false;
1212 this.retrievalError = true;
1216 this.checkAllRetrieved(pager, idx);
1217 this.requestingData = false;
1218 this.retrievalError = false;
1225 // See if the last getRows() call resulted in the final set of data.
1226 checkAllRetrieved(pager: Pager, idx: number) {
1227 if (this.allRowsRetrieved) { return; }
1229 if (idx === 0 || idx < (pager.limit + pager.offset)) {
1230 // last query returned nothing or less than one page.
1231 // confirm we have all of the preceding pages.
1232 if (!this.data.includes(undefined)) {
1233 this.allRowsRetrieved = true;
1234 pager.resultCount = this.data.length;