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;
403 export class GridRowSelector {
404 indexes: {[string: string]: boolean};
410 // Returns true if all of the requested indexes exist in the selector.
411 contains(index: string | string[]): boolean {
412 const indexes = [].concat(index);
413 for (let i = 0; i < indexes.length; i++) { // early exit
414 if (!this.indexes[indexes[i]]) {
421 select(index: string | string[]) {
422 const indexes = [].concat(index);
423 indexes.forEach(i => this.indexes[i] = true);
426 deselect(index: string | string[]) {
427 const indexes = [].concat(index);
428 indexes.forEach(i => delete this.indexes[i]);
431 // Returns the list of selected index values.
432 // In some contexts (template checkboxes) the value for an index is
433 // set to false to deselect instead of having it removed (via deselect()).
434 // NOTE GridRowSelector has no knowledge of when a row is no longer
435 // present in the grid. Use GridContext.getSelectedRows() to get
436 // list of selected rows that are still present in the grid.
438 return Object.keys(this.indexes).filter(
439 ind => Boolean(this.indexes[ind]));
443 return this.selected().length === 0;
451 export interface GridRowFlairEntry {
452 icon: string; // name of material icon
453 title?: string; // tooltip string
456 export class GridColumnPersistConf {
463 export class GridPersistConf {
466 columns: GridColumnPersistConf[];
469 export class GridContext {
474 isFilterable: boolean;
475 stickyGridHeader: boolean;
476 isMultiSortable: boolean;
477 useLocalSort: boolean;
479 disableMultiSelect: boolean;
480 disableSelect: boolean;
481 dataSource: GridDataSource;
482 columnSet: GridColumnSet;
483 rowSelector: GridRowSelector;
484 toolbarButtons: GridToolbarButton[];
485 toolbarCheckboxes: GridToolbarCheckbox[];
486 toolbarActions: GridToolbarAction[];
487 lastSelectedIndex: any;
488 pageChanges: Subscription;
489 rowFlairIsEnabled: boolean;
490 rowFlairCallback: (row: any) => GridRowFlairEntry;
491 rowClassCallback: (row: any) => string;
492 cellClassCallback: (row: any, col: GridColumn) => string;
493 defaultVisibleFields: string[];
494 defaultHiddenFields: string[];
495 overflowCells: boolean;
496 disablePaging: boolean;
497 showDeclaredFieldsOnly: boolean;
499 // Allow calling code to know when the select-all-rows-in-page
500 // action has occurred.
501 selectRowsInPageEmitter: EventEmitter<void>;
503 filterControls: QueryList<GridFilterControlComponent>;
505 // Services injected by our grid component
508 store: ServerStoreService;
509 format: FormatService;
514 store: ServerStoreService,
515 format: FormatService) {
520 this.format = format;
521 this.pager = new Pager();
522 this.rowSelector = new GridRowSelector();
523 this.toolbarButtons = [];
524 this.toolbarCheckboxes = [];
525 this.toolbarActions = [];
529 this.selectRowsInPageEmitter = new EventEmitter<void>();
530 this.columnSet = new GridColumnSet(this.idl, this.idlClass);
531 this.columnSet.isSortable = this.isSortable === true;
532 this.columnSet.isFilterable = this.isFilterable === true;
533 this.columnSet.isMultiSortable = this.isMultiSortable === true;
534 this.columnSet.defaultHiddenFields = this.defaultHiddenFields;
535 this.columnSet.defaultVisibleFields = this.defaultVisibleFields;
536 if (!this.pager.limit) {
537 this.pager.limit = this.disablePaging ? MAX_ALL_ROW_COUNT : 10;
539 this.generateColumns();
542 // Load initial settings and data.
544 this.applyGridConfig()
545 .then(ok => this.dataSource.requestPage(this.pager))
546 .then(ok => this.listenToPager());
553 applyGridConfig(): Promise<void> {
554 return this.getGridConfig(this.persistKey)
558 columns = conf.columns;
560 this.pager.limit = conf.limit;
564 // This is called regardless of the presence of saved
565 // settings so defaults can be applied.
566 this.columnSet.applyColumnSettings(columns);
571 // Give the UI time to settle before reloading grid data.
572 // This can help when data retrieval depends on a value
573 // getting modified by an angular digest cycle.
576 this.dataSource.reset();
577 this.dataSource.requestPage(this.pager);
581 reloadWithoutPagerReset() {
583 this.dataSource.reset();
584 this.dataSource.requestPage(this.pager);
588 // Sort the existing data source instead of requesting sorted
589 // data from the client. Reset pager to page 1. As with reload(),
590 // give the client a chance to setting before redisplaying.
594 this.sortLocalData();
595 this.dataSource.requestPage(this.pager);
599 // Subscribe or unsubscribe to page-change events from the pager.
601 if (this.pageChanges) { return; }
602 this.pageChanges = this.pager.onChange$.subscribe(
603 val => this.dataSource.requestPage(this.pager));
607 if (!this.pageChanges) { return; }
608 this.pageChanges.unsubscribe();
609 this.pageChanges = null;
612 // Sort data in the data source array
615 const sortDefs = this.dataSource.sort.map(sort => {
616 const column = this.columnSet.getColByName(sort.name);
624 if (!def.col.comparator) {
625 switch (def.col.datatype) {
629 def.col.comparator = (a, b) => {
632 if (a < b) { return -1; }
633 if (a > b) { return 1; }
638 def.col.comparator = (a, b) => {
639 if (a < b) { return -1; }
640 if (a > b) { return 1; }
649 this.dataSource.data.sort((rowA, rowB) => {
651 for (let idx = 0; idx < sortDefs.length; idx++) {
652 const sortDef = sortDefs[idx];
654 const valueA = this.getRowColumnValue(rowA, sortDef.col);
655 const valueB = this.getRowColumnValue(rowB, sortDef.col);
657 if (valueA === '' && valueB === '') { continue; }
658 if (valueA === '' && valueB !== '') { return 1; }
659 if (valueA !== '' && valueB === '') { return -1; }
661 const diff = sortDef.col.comparator(valueA, valueB);
662 if (diff === 0) { continue; }
664 return sortDef.dir === 'DESC' ? -diff : diff;
667 return 0; // No differences found.
671 getRowIndex(row: any): any {
672 const col = this.columnSet.indexColumn;
674 throw new Error('grid index column required');
676 return this.getRowColumnValue(row, col);
679 // Returns position in the data source array of the row with
680 // the provided index.
681 getRowPosition(index: any): number {
682 // for-loop for early exit
683 for (let idx = 0; idx < this.dataSource.data.length; idx++) {
684 const row = this.dataSource.data[idx];
685 if (row !== undefined && index === this.getRowIndex(row)) {
691 // Return the row with the provided index.
692 getRowByIndex(index: any): any {
693 for (let idx = 0; idx < this.dataSource.data.length; idx++) {
694 const row = this.dataSource.data[idx];
695 if (row !== undefined && index === this.getRowIndex(row)) {
701 // Returns all selected rows, regardless of whether they are
702 // currently visible in the grid display.
703 // De-selects previously selected rows which are no longer
704 // present in the grid.
705 getSelectedRows(): any[] {
709 this.rowSelector.selected().forEach(index => {
710 const row = this.getRowByIndex(index);
718 this.rowSelector.deselect(deleted);
722 rowIsSelected(row: any): boolean {
723 const index = this.getRowIndex(row);
724 return this.rowSelector.selected().filter(
729 getRowColumnValue(row: any, col: GridColumn): string {
733 val = this.nestedItemFieldValue(row, col);
734 } else if (col.name in row) {
735 val = this.getObjectFieldValue(row, col.name);
738 if (col.datatype === 'bool') {
739 // Avoid string-ifying bools so we can use an <eg-bool/>
740 // in the grid template.
744 return this.format.transform({
746 idlClass: col.idlClass,
747 idlField: col.idlFieldDef ? col.idlFieldDef.name : col.name,
748 datatype: col.datatype,
749 datePlusTime: Boolean(col.datePlusTime),
750 timezoneContextOrg: Number(col.timezoneContextOrg)
754 getObjectFieldValue(obj: any, name: string): any {
755 if (typeof obj[name] === 'function') {
762 nestedItemFieldValue(obj: any, col: GridColumn): string {
766 const original = obj;
767 const steps = col.path.split('.');
769 for (let i = 0; i < steps.length; i++) {
770 const step = steps[i];
772 if (obj === null || obj === undefined || typeof obj !== 'object') {
773 // We have run out of data to step through before
774 // reaching the end of the path. Conclude fleshing via
775 // callback if provided then exit.
776 if (col.flesher && obj !== undefined) {
777 return col.flesher(obj, col, original);
782 const class_ = obj.classname;
783 if (class_ && (idlClassDef = this.idl.classes[class_])) {
784 idlField = idlClassDef.field_map[step];
787 obj = this.getObjectFieldValue(obj, step);
790 // We found a nested IDL object which may or may not have
791 // been configured as a top-level column. Flesh the column
792 // metadata with our newly found IDL info.
795 col.datatype = idlField.datatype;
797 if (!col.idlFieldDef) {
798 idlField = col.idlFieldDef;
801 col.idlClass = idlClassDef.name;
804 col.label = idlField.label || idlField.name;
812 getColumnTextContent(row: any, col: GridColumn): string {
813 if (col.cellPrintValue) {
814 return col.cellPrintValue(row, col);
816 if (col.cellTemplate) {
817 return ''; // avoid 'undefined' values
819 return this.getRowColumnValue(row, col);
824 selectOneRow(index: any) {
825 this.rowSelector.clear();
826 this.rowSelector.select(index);
827 this.lastSelectedIndex = index;
830 selectMultipleRows(indexes: any[]) {
831 this.rowSelector.clear();
832 this.rowSelector.select(indexes);
833 this.lastSelectedIndex = indexes[indexes.length - 1];
836 // selects or deselects an item, without affecting the others.
837 // returns true if the item is selected; false if de-selected.
838 toggleSelectOneRow(index: any) {
839 if (this.rowSelector.contains(index)) {
840 this.rowSelector.deselect(index);
844 this.rowSelector.select(index);
845 this.lastSelectedIndex = index;
849 selectRowByPos(pos: number) {
850 const row = this.dataSource.data[pos];
852 this.selectOneRow(this.getRowIndex(row));
856 selectPreviousRow() {
857 if (!this.lastSelectedIndex) { return; }
858 const pos = this.getRowPosition(this.lastSelectedIndex);
859 if (pos === this.pager.offset) {
860 this.toPrevPage().then(ok => this.selectLastRow(), err => {});
862 this.selectRowByPos(pos - 1);
867 if (!this.lastSelectedIndex) { return; }
868 const pos = this.getRowPosition(this.lastSelectedIndex);
869 if (pos === (this.pager.offset + this.pager.limit - 1)) {
870 this.toNextPage().then(ok => this.selectFirstRow(), err => {});
872 this.selectRowByPos(pos + 1);
877 // Select the previous row in addition to any currently selected row.
878 // However, if the previous row is already selected, assume the user
879 // has reversed direction and now wants to de-select the last selected row.
880 selectMultiRowsPrevious() {
881 if (!this.lastSelectedIndex) { return; }
882 const pos = this.getRowPosition(this.lastSelectedIndex);
883 const selectedIndexes = this.rowSelector.selected();
885 const promise = // load the previous page of data if needed
886 (pos === this.pager.offset) ? this.toPrevPage() : Promise.resolve();
890 const row = this.dataSource.data[pos - 1];
891 const newIndex = this.getRowIndex(row);
892 if (selectedIndexes.filter(i => i === newIndex).length > 0) {
893 // Prev row is already selected. User is reversing direction.
894 this.rowSelector.deselect(this.lastSelectedIndex);
895 this.lastSelectedIndex = newIndex;
897 this.selectMultipleRows(selectedIndexes.concat(newIndex));
905 // Select the next row in addition to any currently selected row.
906 // However, if the next row is already selected, assume the user
907 // has reversed direction and wants to de-select the last selected row.
908 selectMultiRowsNext() {
909 if (!this.lastSelectedIndex) { return; }
910 const pos = this.getRowPosition(this.lastSelectedIndex);
911 const selectedIndexes = this.rowSelector.selected();
913 const promise = // load the next page of data if needed
914 (pos === (this.pager.offset + this.pager.limit - 1)) ?
915 this.toNextPage() : Promise.resolve();
919 const row = this.dataSource.data[pos + 1];
920 const newIndex = this.getRowIndex(row);
921 if (selectedIndexes.filter(i => i === newIndex).length > 0) {
922 // Next row is already selected. User is reversing direction.
923 this.rowSelector.deselect(this.lastSelectedIndex);
924 this.lastSelectedIndex = newIndex;
926 this.selectMultipleRows(selectedIndexes.concat(newIndex));
933 getFirstRowInPage(): any {
934 return this.dataSource.data[this.pager.offset];
937 getLastRowInPage(): any {
938 return this.dataSource.data[this.pager.offset + this.pager.limit - 1];
942 this.selectOneRow(this.getRowIndex(this.getFirstRowInPage()));
946 this.selectOneRow(this.getRowIndex(this.getLastRowInPage()));
950 const rows = this.dataSource.getPageOfRows(this.pager);
951 const indexes = rows.map(r => this.getRowIndex(r));
952 this.rowSelector.select(indexes);
953 this.selectRowsInPageEmitter.emit();
956 toPrevPage(): Promise<any> {
957 if (this.pager.isFirstPage()) {
958 return Promise.reject('on first');
960 // temp ignore pager events since we're calling requestPage manually.
962 this.pager.decrement();
963 this.listenToPager();
964 return this.dataSource.requestPage(this.pager);
967 toNextPage(): Promise<any> {
968 if (this.pager.isLastPage()) {
969 return Promise.reject('on last');
971 // temp ignore pager events since we're calling requestPage manually.
973 this.pager.increment();
974 this.listenToPager();
975 return this.dataSource.requestPage(this.pager);
978 getAllRows(): Promise<any> {
979 const pager = new Pager();
981 pager.limit = MAX_ALL_ROW_COUNT;
982 return this.dataSource.requestPage(pager);
985 // Returns a key/value pair object of visible column data as text.
986 getRowAsFlatText(row: any): any {
988 this.columnSet.displayColumns().forEach(col => {
990 this.getColumnTextContent(row, col);
995 getAllRowsAsText(): Observable<any> {
996 return Observable.create(observer => {
997 this.getAllRows().then(ok => {
998 this.dataSource.data.forEach(row => {
999 observer.next(this.getRowAsFlatText(row));
1001 observer.complete();
1006 removeFilters(): void {
1007 this.dataSource.filters = {};
1008 this.columnSet.displayColumns().forEach(col => { col.removeFilter(); });
1009 this.filterControls.forEach(ctl => ctl.reset());
1012 filtersSet(): boolean {
1013 return Object.keys(this.dataSource.filters).length > 0;
1016 gridToCsv(): Promise<string> {
1019 const columns = this.columnSet.displayColumns();
1022 columns.forEach(col => {
1023 csvStr += this.valueToCsv(col.label),
1027 csvStr = csvStr.replace(/,$/, '\n');
1029 return new Promise(resolve => {
1030 this.getAllRowsAsText().subscribe(
1032 columns.forEach(col => {
1033 csvStr += this.valueToCsv(row[col.name]);
1036 csvStr = csvStr.replace(/,$/, '\n');
1039 () => resolve(csvStr)
1045 // prepares a string for inclusion within a CSV document
1046 // by escaping commas and quotes and removing newlines.
1047 valueToCsv(str: string): string {
1049 if (!str) { return ''; }
1050 str = str.replace(/\n/g, '');
1051 if (str.match(/\,/) || str.match(/"/)) {
1052 str = str.replace(/"/g, '""');
1053 str = '"' + str + '"';
1059 if (!this.columnSet.idlClass) { return; }
1061 const pkeyField = this.idl.classes[this.columnSet.idlClass].pkey;
1063 // generate columns for all non-virtual fields on the IDL class
1064 this.idl.classes[this.columnSet.idlClass].fields
1065 .filter(field => !field.virtual)
1067 const col = new GridColumn();
1068 col.name = field.name;
1069 col.label = field.label || field.name;
1070 col.idlFieldDef = field;
1071 col.idlClass = this.columnSet.idlClass;
1072 col.datatype = field.datatype;
1073 col.isIndex = (field.name === pkeyField);
1076 if (this.showDeclaredFieldsOnly) {
1080 this.columnSet.add(col);
1084 saveGridConfig(): Promise<any> {
1085 if (!this.persistKey) {
1086 throw new Error('Grid persistKey required to save columns');
1088 const conf = new GridPersistConf();
1090 conf.limit = this.pager.limit;
1091 conf.columns = this.columnSet.compileSaveObject();
1093 return this.store.setItem('eg.grid.' + this.persistKey, conf);
1096 // TODO: saveGridConfigAsOrgSetting(...)
1098 getGridConfig(persistKey: string): Promise<GridPersistConf> {
1099 if (!persistKey) { return Promise.resolve(null); }
1100 return this.store.getItem('eg.grid.' + persistKey);
1105 // Actions apply to specific rows
1106 export class GridToolbarAction {
1108 onClick: EventEmitter<any []>;
1109 action: (rows: any[]) => any; // DEPRECATED
1112 isGroup: boolean; // used for group placeholder entries
1113 isSeparator: boolean;
1114 disableOnRows: (rows: any[]) => boolean;
1117 // Buttons are global actions
1118 export class GridToolbarButton {
1120 onClick: EventEmitter<any []>;
1121 action: () => any; // DEPRECATED
1125 export class GridToolbarCheckbox {
1128 onChange: EventEmitter<boolean>;
1131 export class GridDataSource {
1136 allRowsRetrieved: boolean;
1137 requestingData: boolean;
1138 getRows: (pager: Pager, sort: any[]) => Observable<any>;
1148 this.allRowsRetrieved = false;
1151 // called from the template -- no data fetching
1152 getPageOfRows(pager: Pager): any[] {
1154 return this.data.slice(
1155 pager.offset, pager.limit + pager.offset
1156 ).filter(row => row !== undefined);
1161 // called on initial component load and user action (e.g. paging, sorting).
1162 requestPage(pager: Pager): Promise<any> {
1165 this.getPageOfRows(pager).length === pager.limit
1166 // already have all data
1167 || this.allRowsRetrieved
1168 // have no way to get more data.
1171 return Promise.resolve();
1174 // If we have to call out for data, set inFetch
1175 this.requestingData = true;
1177 return new Promise((resolve, reject) => {
1178 let idx = pager.offset;
1179 return this.getRows(pager, this.sort).subscribe(
1181 this.data[idx++] = row;
1182 this.requestingData = false;
1185 console.error(`grid getRows() error ${err}`);
1189 this.checkAllRetrieved(pager, idx);
1190 this.requestingData = false;
1197 // See if the last getRows() call resulted in the final set of data.
1198 checkAllRetrieved(pager: Pager, idx: number) {
1199 if (this.allRowsRetrieved) { return; }
1201 if (idx === 0 || idx < (pager.limit + pager.offset)) {
1202 // last query returned nothing or less than one page.
1203 // confirm we have all of the preceding pages.
1204 if (!this.data.includes(undefined)) {
1205 this.allRowsRetrieved = true;
1206 pager.resultCount = this.data.length;