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 cellTemplate: TemplateRef<any>;
34 isDragTarget: boolean;
36 isFilterable: boolean;
38 isMultiSortable: boolean;
39 disableTooltip: boolean;
40 comparator: (valueA: any, valueB: any) => number;
42 // True if the column was automatically generated.
47 filterOperator: string;
48 filterInputDisabled: boolean;
49 filterIncludeOrgAncestors: boolean;
50 filterIncludeOrgDescendants: boolean;
52 flesher: (obj: any, col: GridColumn, item: any) => any;
54 getCellContext(row: any) {
58 userContext: this.cellContext
67 this.isFiltered = false;
68 this.filterValue = undefined;
69 this.filterOperator = '=';
70 this.filterInputDisabled = false;
71 this.filterIncludeOrgAncestors = false;
72 this.filterIncludeOrgDescendants = false;
76 export class GridColumnSet {
77 columns: GridColumn[];
79 indexColumn: GridColumn;
81 isFilterable: boolean;
82 isMultiSortable: boolean;
83 stockVisible: string[];
85 defaultHiddenFields: string[];
86 defaultVisibleFields: string[];
88 constructor(idl: IdlService, idlClass?: string) {
91 this.stockVisible = [];
92 this.idlClass = idlClass;
95 add(col: GridColumn) {
97 this.applyColumnDefaults(col);
99 if (!this.insertColumn(col)) {
100 // Column was rejected as a duplicate.
104 if (col.isIndex) { this.indexColumn = col; }
106 // track which fields are visible on page load.
108 this.stockVisible.push(col.name);
111 this.applyColumnSortability(col);
112 this.applyColumnFilterability(col);
115 // Returns true if the new column was inserted, false otherwise.
116 // Declared columns take precedence over auto-generated columns
117 // when collisions occur.
118 // Declared columns are inserted in front of auto columns.
119 insertColumn(col: GridColumn): boolean {
122 if (this.getColByName(col.name)) {
123 // New auto-generated column conflicts with existing
127 // No collisions. Add to the end of the list
128 this.columns.push(col);
133 // Adding a declared column.
136 for (let idx = 0; idx < this.columns.length; idx++) {
137 const testCol = this.columns[idx];
138 if (testCol.name === col.name) { // match found
139 if (testCol.isAuto) {
140 // new column takes precedence, remove the existing column.
141 this.columns.splice(idx, 1);
144 // New column does not take precedence. Avoid
151 // Delcared columns are inserted just before the first auto-column
152 for (let idx = 0; idx < this.columns.length; idx++) {
153 const testCol = this.columns[idx];
154 if (testCol.isAuto) {
156 this.columns.unshift(col);
158 this.columns.splice(idx, 0, col);
164 // No insertion point found. Toss the new column on the end.
165 this.columns.push(col);
169 getColByName(name: string): GridColumn {
170 return this.columns.filter(c => c.name === name)[0];
173 idlInfoFromDotpath(dotpath: string): any {
174 if (!dotpath || !this.idlClass) { return null; }
178 let idlClass = this.idl.classes[this.idlClass];
180 const pathParts = dotpath.split(/\./);
182 for (let i = 0; i < pathParts.length; i++) {
183 const part = pathParts[i];
184 idlParent = idlField;
185 idlField = idlClass.field_map[part];
188 if (idlField['class'] && (
189 idlField.datatype === 'link' ||
190 idlField.datatype === 'org_unit')) {
191 idlClass = this.idl.classes[idlField['class']];
199 idlParent: idlParent,
207 this.columns.forEach(col => {
211 col.visible = this.stockVisible.includes(col.name);
215 applyColumnDefaults(col: GridColumn) {
217 if (!col.idlFieldDef && col.path) {
218 const idlInfo = this.idlInfoFromDotpath(col.path);
220 col.idlFieldDef = idlInfo.idlField;
221 col.idlClass = idlInfo.idlClass.name;
223 col.label = col.idlFieldDef.label || col.idlFieldDef.name;
224 col.datatype = col.idlFieldDef.datatype;
229 if (!col.name) { col.name = col.path; }
230 if (!col.flex) { col.flex = 2; }
231 if (!col.align) { col.align = 'left'; }
232 if (!col.label) { col.label = col.name; }
233 if (!col.datatype) { col.datatype = 'text'; }
235 col.visible = !col.hidden;
238 applyColumnSortability(col: GridColumn) {
239 // column sortability defaults to the sortability of the column set.
240 if (col.isSortable === undefined && this.isSortable) {
241 col.isSortable = true;
244 if (col.isMultiSortable === undefined && this.isMultiSortable) {
245 col.isMultiSortable = true;
248 if (col.isMultiSortable) {
249 col.isSortable = true;
252 applyColumnFilterability(col: GridColumn) {
253 // column filterability defaults to the afilterability of the column set.
254 if (col.isFilterable === undefined && this.isFilterable) {
255 col.isFilterable = true;
259 displayColumns(): GridColumn[] {
260 return this.columns.filter(c => c.visible);
263 insertBefore(source: GridColumn, target: GridColumn) {
266 this.columns.forEach((col, idx) => {
267 if (col.name === target.name) { targetIdx = idx; }});
269 this.columns.forEach((col, idx) => {
270 if (col.name === source.name) { sourceIdx = idx; }});
272 if (sourceIdx >= 0) {
273 this.columns.splice(sourceIdx, 1);
276 this.columns.splice(targetIdx, 0, source);
279 // Move visible columns to the front of the list.
280 moveVisibleToFront() {
281 const newCols = this.displayColumns();
282 this.columns.forEach(col => {
283 if (!col.visible) { newCols.push(col); }});
284 this.columns = newCols;
287 moveColumn(col: GridColumn, diff: number) {
288 let srcIdx, targetIdx;
290 this.columns.forEach((c, i) => {
291 if (c.name === col.name) { srcIdx = i; }
294 targetIdx = srcIdx + diff;
297 } else if (targetIdx >= this.columns.length) {
298 // Target index follows the last visible column.
300 this.columns.forEach((c, idx) => {
301 if (c.visible) { lastVisible = idx; }
304 // When moving a column (down) causes one or more
305 // visible columns to shuffle forward, our column
306 // moves into the slot of the last visible column.
307 // Otherwise, put it into the slot directly following
308 // the last visible column.
309 targetIdx = srcIdx <= lastVisible ? lastVisible : lastVisible + 1;
312 // Splice column out of old position, insert at new position.
313 this.columns.splice(srcIdx, 1);
314 this.columns.splice(targetIdx, 0, col);
317 compileSaveObject(): GridColumnPersistConf[] {
318 // only store information about visible columns.
319 // scrunch the data down to just the needed info.
320 return this.displayColumns().map(col => {
321 const c: GridColumnPersistConf = {name : col.name};
322 if (col.align !== 'left') { c.align = col.align; }
323 if (col.flex !== 2) { c.flex = Number(col.flex); }
324 if (Number(col.sort)) { c.sort = Number(c.sort); }
329 applyColumnSettings(conf: GridColumnPersistConf[]) {
331 if (!conf || conf.length === 0) {
332 // No configuration is available, but we have a list of
333 // fields to show or hide by default
335 if (this.defaultVisibleFields) {
336 this.columns.forEach(col => {
337 if (this.defaultVisibleFields.includes(col.name)) {
344 } else if (this.defaultHiddenFields) {
345 this.defaultHiddenFields.forEach(name => {
346 const col = this.getColByName(name);
358 conf.forEach(colConf => {
359 const col = this.getColByName(colConf.name);
360 if (!col) { return; } // no such column in this grid.
363 if (colConf.align) { col.align = colConf.align; }
364 if (colConf.flex) { col.flex = Number(colConf.flex); }
365 if (colConf.sort) { col.sort = Number(colConf.sort); }
367 // Add to new columns array, avoid dupes.
368 if (newCols.filter(c => c.name === col.name).length === 0) {
373 // columns which are not expressed within the saved
374 // configuration are marked as non-visible and
375 // appended to the end of the new list of columns.
376 this.columns.forEach(c => {
377 if (conf.filter(cf => cf.name === c.name).length === 0) {
383 this.columns = newCols;
388 export class GridRowSelector {
389 indexes: {[string: string]: boolean};
395 // Returns true if all of the requested indexes exist in the selector.
396 contains(index: string | string[]): boolean {
397 const indexes = [].concat(index);
398 for (let i = 0; i < indexes.length; i++) { // early exit
399 if (!this.indexes[indexes[i]]) {
406 select(index: string | string[]) {
407 const indexes = [].concat(index);
408 indexes.forEach(i => this.indexes[i] = true);
411 deselect(index: string | string[]) {
412 const indexes = [].concat(index);
413 indexes.forEach(i => delete this.indexes[i]);
416 // Returns the list of selected index values.
417 // In some contexts (template checkboxes) the value for an index is
418 // set to false to deselect instead of having it removed (via deselect()).
419 // NOTE GridRowSelector has no knowledge of when a row is no longer
420 // present in the grid. Use GridContext.getSelectedRows() to get
421 // list of selected rows that are still present in the grid.
423 return Object.keys(this.indexes).filter(
424 ind => Boolean(this.indexes[ind]));
428 return this.selected().length === 0;
436 export interface GridRowFlairEntry {
437 icon: string; // name of material icon
438 title?: string; // tooltip string
441 export class GridColumnPersistConf {
448 export class GridPersistConf {
451 columns: GridColumnPersistConf[];
454 export class GridContext {
459 isFilterable: boolean;
460 stickyGridHeader: boolean;
461 isMultiSortable: boolean;
462 useLocalSort: boolean;
464 disableMultiSelect: boolean;
465 disableSelect: boolean;
466 dataSource: GridDataSource;
467 columnSet: GridColumnSet;
468 rowSelector: GridRowSelector;
469 toolbarButtons: GridToolbarButton[];
470 toolbarCheckboxes: GridToolbarCheckbox[];
471 toolbarActions: GridToolbarAction[];
472 lastSelectedIndex: any;
473 pageChanges: Subscription;
474 rowFlairIsEnabled: boolean;
475 rowFlairCallback: (row: any) => GridRowFlairEntry;
476 rowClassCallback: (row: any) => string;
477 cellClassCallback: (row: any, col: GridColumn) => string;
478 defaultVisibleFields: string[];
479 defaultHiddenFields: string[];
480 overflowCells: boolean;
481 showLinkSelectors: boolean;
482 disablePaging: boolean;
483 showDeclaredFieldsOnly: boolean;
485 // Allow calling code to know when the select-all-rows-in-page
486 // action has occurred.
487 selectRowsInPageEmitter: EventEmitter<void>;
489 filterControls: QueryList<GridFilterControlComponent>;
491 // Services injected by our grid component
494 store: ServerStoreService;
495 format: FormatService;
500 store: ServerStoreService,
501 format: FormatService) {
506 this.format = format;
507 this.pager = new Pager();
508 this.rowSelector = new GridRowSelector();
509 this.toolbarButtons = [];
510 this.toolbarCheckboxes = [];
511 this.toolbarActions = [];
515 this.selectRowsInPageEmitter = new EventEmitter<void>();
516 this.columnSet = new GridColumnSet(this.idl, this.idlClass);
517 this.columnSet.isSortable = this.isSortable === true;
518 this.columnSet.isFilterable = this.isFilterable === true;
519 this.columnSet.isMultiSortable = this.isMultiSortable === true;
520 this.columnSet.defaultHiddenFields = this.defaultHiddenFields;
521 this.columnSet.defaultVisibleFields = this.defaultVisibleFields;
522 if (!this.pager.limit) {
523 this.pager.limit = this.disablePaging ? MAX_ALL_ROW_COUNT : 10;
525 this.generateColumns();
528 // Load initial settings and data.
530 this.applyGridConfig()
531 .then(ok => this.dataSource.requestPage(this.pager))
532 .then(ok => this.listenToPager());
539 applyGridConfig(): Promise<void> {
540 return this.getGridConfig(this.persistKey)
544 columns = conf.columns;
546 this.pager.limit = conf.limit;
550 // This is called regardless of the presence of saved
551 // settings so defaults can be applied.
552 this.columnSet.applyColumnSettings(columns);
557 // Give the UI time to settle before reloading grid data.
558 // This can help when data retrieval depends on a value
559 // getting modified by an angular digest cycle.
562 this.dataSource.reset();
563 this.dataSource.requestPage(this.pager);
567 reloadWithoutPagerReset() {
569 this.dataSource.reset();
570 this.dataSource.requestPage(this.pager);
574 // Sort the existing data source instead of requesting sorted
575 // data from the client. Reset pager to page 1. As with reload(),
576 // give the client a chance to setting before redisplaying.
580 this.sortLocalData();
581 this.dataSource.requestPage(this.pager);
585 // Subscribe or unsubscribe to page-change events from the pager.
587 if (this.pageChanges) { return; }
588 this.pageChanges = this.pager.onChange$.subscribe(
589 val => this.dataSource.requestPage(this.pager));
593 if (!this.pageChanges) { return; }
594 this.pageChanges.unsubscribe();
595 this.pageChanges = null;
598 // Sort data in the data source array
601 const sortDefs = this.dataSource.sort.map(sort => {
602 const column = this.columnSet.getColByName(sort.name);
610 if (!def.col.comparator) {
611 switch (def.col.datatype) {
615 def.col.comparator = (a, b) => {
618 if (a < b) { return -1; }
619 if (a > b) { return 1; }
624 def.col.comparator = (a, b) => {
625 if (a < b) { return -1; }
626 if (a > b) { return 1; }
635 this.dataSource.data.sort((rowA, rowB) => {
637 for (let idx = 0; idx < sortDefs.length; idx++) {
638 const sortDef = sortDefs[idx];
640 const valueA = this.getRowColumnValue(rowA, sortDef.col);
641 const valueB = this.getRowColumnValue(rowB, sortDef.col);
643 if (valueA === '' && valueB === '') { continue; }
644 if (valueA === '' && valueB !== '') { return 1; }
645 if (valueA !== '' && valueB === '') { return -1; }
647 const diff = sortDef.col.comparator(valueA, valueB);
648 if (diff === 0) { continue; }
650 return sortDef.dir === 'DESC' ? -diff : diff;
653 return 0; // No differences found.
657 getRowIndex(row: any): any {
658 const col = this.columnSet.indexColumn;
660 throw new Error('grid index column required');
662 return this.getRowColumnValue(row, col);
665 // Returns position in the data source array of the row with
666 // the provided index.
667 getRowPosition(index: any): number {
668 // for-loop for early exit
669 for (let idx = 0; idx < this.dataSource.data.length; idx++) {
670 const row = this.dataSource.data[idx];
671 if (row !== undefined && index === this.getRowIndex(row)) {
677 // Return the row with the provided index.
678 getRowByIndex(index: any): any {
679 for (let idx = 0; idx < this.dataSource.data.length; idx++) {
680 const row = this.dataSource.data[idx];
681 if (row !== undefined && index === this.getRowIndex(row)) {
687 // Returns all selected rows, regardless of whether they are
688 // currently visible in the grid display.
689 // De-selects previously selected rows which are no longer
690 // present in the grid.
691 getSelectedRows(): any[] {
695 this.rowSelector.selected().forEach(index => {
696 const row = this.getRowByIndex(index);
704 this.rowSelector.deselect(deleted);
708 rowIsSelected(row: any): boolean {
709 const index = this.getRowIndex(row);
710 return this.rowSelector.selected().filter(
715 getRowColumnValue(row: any, col: GridColumn): string {
719 val = this.nestedItemFieldValue(row, col);
720 } else if (col.name in row) {
721 val = this.getObjectFieldValue(row, col.name);
724 if (col.datatype === 'bool') {
725 // Avoid string-ifying bools so we can use an <eg-bool/>
726 // in the grid template.
730 return this.format.transform({
732 idlClass: col.idlClass,
733 idlField: col.idlFieldDef ? col.idlFieldDef.name : col.name,
734 datatype: col.datatype,
735 datePlusTime: Boolean(col.datePlusTime)
739 getObjectFieldValue(obj: any, name: string): any {
740 if (typeof obj[name] === 'function') {
747 nestedItemFieldValue(obj: any, col: GridColumn): string {
751 const original = obj;
752 const steps = col.path.split('.');
754 for (let i = 0; i < steps.length; i++) {
755 const step = steps[i];
757 if (obj === null || obj === undefined || typeof obj !== 'object') {
758 // We have run out of data to step through before
759 // reaching the end of the path. Conclude fleshing via
760 // callback if provided then exit.
761 if (col.flesher && obj !== undefined) {
762 return col.flesher(obj, col, original);
767 const class_ = obj.classname;
768 if (class_ && (idlClassDef = this.idl.classes[class_])) {
769 idlField = idlClassDef.field_map[step];
772 obj = this.getObjectFieldValue(obj, step);
775 // We found a nested IDL object which may or may not have
776 // been configured as a top-level column. Flesh the column
777 // metadata with our newly found IDL info.
780 col.datatype = idlField.datatype;
782 if (!col.idlFieldDef) {
783 idlField = col.idlFieldDef;
786 col.idlClass = idlClassDef.name;
789 col.label = idlField.label || idlField.name;
797 getColumnTextContent(row: any, col: GridColumn): string {
798 if (col.cellTemplate) {
800 // Extract the text content from the rendered template.
802 return this.getRowColumnValue(row, col);
806 selectOneRow(index: any) {
807 this.rowSelector.clear();
808 this.rowSelector.select(index);
809 this.lastSelectedIndex = index;
812 selectMultipleRows(indexes: any[]) {
813 this.rowSelector.clear();
814 this.rowSelector.select(indexes);
815 this.lastSelectedIndex = indexes[indexes.length - 1];
818 // selects or deselects an item, without affecting the others.
819 // returns true if the item is selected; false if de-selected.
820 toggleSelectOneRow(index: any) {
821 if (this.rowSelector.contains(index)) {
822 this.rowSelector.deselect(index);
826 this.rowSelector.select(index);
827 this.lastSelectedIndex = index;
831 selectRowByPos(pos: number) {
832 const row = this.dataSource.data[pos];
834 this.selectOneRow(this.getRowIndex(row));
838 selectPreviousRow() {
839 if (!this.lastSelectedIndex) { return; }
840 const pos = this.getRowPosition(this.lastSelectedIndex);
841 if (pos === this.pager.offset) {
842 this.toPrevPage().then(ok => this.selectLastRow(), err => {});
844 this.selectRowByPos(pos - 1);
849 if (!this.lastSelectedIndex) { return; }
850 const pos = this.getRowPosition(this.lastSelectedIndex);
851 if (pos === (this.pager.offset + this.pager.limit - 1)) {
852 this.toNextPage().then(ok => this.selectFirstRow(), err => {});
854 this.selectRowByPos(pos + 1);
859 // Select the previous row in addition to any currently selected row.
860 // However, if the previous row is already selected, assume the user
861 // has reversed direction and now wants to de-select the last selected row.
862 selectMultiRowsPrevious() {
863 if (!this.lastSelectedIndex) { return; }
864 const pos = this.getRowPosition(this.lastSelectedIndex);
865 const selectedIndexes = this.rowSelector.selected();
867 const promise = // load the previous page of data if needed
868 (pos === this.pager.offset) ? this.toPrevPage() : Promise.resolve();
872 const row = this.dataSource.data[pos - 1];
873 const newIndex = this.getRowIndex(row);
874 if (selectedIndexes.filter(i => i === newIndex).length > 0) {
875 // Prev row is already selected. User is reversing direction.
876 this.rowSelector.deselect(this.lastSelectedIndex);
877 this.lastSelectedIndex = newIndex;
879 this.selectMultipleRows(selectedIndexes.concat(newIndex));
887 // Select the next row in addition to any currently selected row.
888 // However, if the next row is already selected, assume the user
889 // has reversed direction and wants to de-select the last selected row.
890 selectMultiRowsNext() {
891 if (!this.lastSelectedIndex) { return; }
892 const pos = this.getRowPosition(this.lastSelectedIndex);
893 const selectedIndexes = this.rowSelector.selected();
895 const promise = // load the next page of data if needed
896 (pos === (this.pager.offset + this.pager.limit - 1)) ?
897 this.toNextPage() : Promise.resolve();
901 const row = this.dataSource.data[pos + 1];
902 const newIndex = this.getRowIndex(row);
903 if (selectedIndexes.filter(i => i === newIndex).length > 0) {
904 // Next row is already selected. User is reversing direction.
905 this.rowSelector.deselect(this.lastSelectedIndex);
906 this.lastSelectedIndex = newIndex;
908 this.selectMultipleRows(selectedIndexes.concat(newIndex));
915 getFirstRowInPage(): any {
916 return this.dataSource.data[this.pager.offset];
919 getLastRowInPage(): any {
920 return this.dataSource.data[this.pager.offset + this.pager.limit - 1];
924 this.selectOneRow(this.getRowIndex(this.getFirstRowInPage()));
928 this.selectOneRow(this.getRowIndex(this.getLastRowInPage()));
932 const rows = this.dataSource.getPageOfRows(this.pager);
933 const indexes = rows.map(r => this.getRowIndex(r));
934 this.rowSelector.select(indexes);
935 this.selectRowsInPageEmitter.emit();
938 toPrevPage(): Promise<any> {
939 if (this.pager.isFirstPage()) {
940 return Promise.reject('on first');
942 // temp ignore pager events since we're calling requestPage manually.
944 this.pager.decrement();
945 this.listenToPager();
946 return this.dataSource.requestPage(this.pager);
949 toNextPage(): Promise<any> {
950 if (this.pager.isLastPage()) {
951 return Promise.reject('on last');
953 // temp ignore pager events since we're calling requestPage manually.
955 this.pager.increment();
956 this.listenToPager();
957 return this.dataSource.requestPage(this.pager);
960 getAllRows(): Promise<any> {
961 const pager = new Pager();
963 pager.limit = MAX_ALL_ROW_COUNT;
964 return this.dataSource.requestPage(pager);
967 // Returns a key/value pair object of visible column data as text.
968 getRowAsFlatText(row: any): any {
970 this.columnSet.displayColumns().forEach(col => {
972 this.getColumnTextContent(row, col);
977 getAllRowsAsText(): Observable<any> {
978 return Observable.create(observer => {
979 this.getAllRows().then(ok => {
980 this.dataSource.data.forEach(row => {
981 observer.next(this.getRowAsFlatText(row));
988 removeFilters(): void {
989 this.dataSource.filters = {};
990 this.columnSet.displayColumns().forEach(col => { col.removeFilter(); });
991 this.filterControls.forEach(ctl => ctl.reset());
994 filtersSet(): boolean {
995 return Object.keys(this.dataSource.filters).length > 0;
998 gridToCsv(): Promise<string> {
1001 const columns = this.columnSet.displayColumns();
1004 columns.forEach(col => {
1005 csvStr += this.valueToCsv(col.label),
1009 csvStr = csvStr.replace(/,$/, '\n');
1011 return new Promise(resolve => {
1012 this.getAllRowsAsText().subscribe(
1014 columns.forEach(col => {
1015 csvStr += this.valueToCsv(row[col.name]);
1018 csvStr = csvStr.replace(/,$/, '\n');
1021 () => resolve(csvStr)
1027 // prepares a string for inclusion within a CSV document
1028 // by escaping commas and quotes and removing newlines.
1029 valueToCsv(str: string): string {
1031 if (!str) { return ''; }
1032 str = str.replace(/\n/g, '');
1033 if (str.match(/\,/) || str.match(/"/)) {
1034 str = str.replace(/"/g, '""');
1035 str = '"' + str + '"';
1041 if (!this.columnSet.idlClass) { return; }
1043 const pkeyField = this.idl.classes[this.columnSet.idlClass].pkey;
1045 // generate columns for all non-virtual fields on the IDL class
1046 this.idl.classes[this.columnSet.idlClass].fields
1047 .filter(field => !field.virtual)
1049 const col = new GridColumn();
1050 col.name = field.name;
1051 col.label = field.label || field.name;
1052 col.idlFieldDef = field;
1053 col.idlClass = this.columnSet.idlClass;
1054 col.datatype = field.datatype;
1055 col.isIndex = (field.name === pkeyField);
1058 if (this.showLinkSelectors) {
1059 const selector = this.idl.getLinkSelector(
1060 this.columnSet.idlClass, field.name);
1062 col.path = field.name + '.' + selector;
1066 if (this.showDeclaredFieldsOnly) {
1070 this.columnSet.add(col);
1074 saveGridConfig(): Promise<any> {
1075 if (!this.persistKey) {
1076 throw new Error('Grid persistKey required to save columns');
1078 const conf = new GridPersistConf();
1080 conf.limit = this.pager.limit;
1081 conf.columns = this.columnSet.compileSaveObject();
1083 return this.store.setItem('eg.grid.' + this.persistKey, conf);
1086 // TODO: saveGridConfigAsOrgSetting(...)
1088 getGridConfig(persistKey: string): Promise<GridPersistConf> {
1089 if (!persistKey) { return Promise.resolve(null); }
1090 return this.store.getItem('eg.grid.' + persistKey);
1095 // Actions apply to specific rows
1096 export class GridToolbarAction {
1098 onClick: EventEmitter<any []>;
1099 action: (rows: any[]) => any; // DEPRECATED
1102 isGroup: boolean; // used for group placeholder entries
1103 isSeparator: boolean;
1104 disableOnRows: (rows: any[]) => boolean;
1107 // Buttons are global actions
1108 export class GridToolbarButton {
1110 onClick: EventEmitter<any []>;
1111 action: () => any; // DEPRECATED
1115 export class GridToolbarCheckbox {
1118 onChange: EventEmitter<boolean>;
1121 export class GridDataSource {
1126 allRowsRetrieved: boolean;
1127 requestingData: boolean;
1128 getRows: (pager: Pager, sort: any[]) => Observable<any>;
1138 this.allRowsRetrieved = false;
1141 // called from the template -- no data fetching
1142 getPageOfRows(pager: Pager): any[] {
1144 return this.data.slice(
1145 pager.offset, pager.limit + pager.offset
1146 ).filter(row => row !== undefined);
1151 // called on initial component load and user action (e.g. paging, sorting).
1152 requestPage(pager: Pager): Promise<any> {
1155 this.getPageOfRows(pager).length === pager.limit
1156 // already have all data
1157 || this.allRowsRetrieved
1158 // have no way to get more data.
1161 return Promise.resolve();
1164 // If we have to call out for data, set inFetch
1165 this.requestingData = true;
1167 return new Promise((resolve, reject) => {
1168 let idx = pager.offset;
1169 return this.getRows(pager, this.sort).subscribe(
1171 this.data[idx++] = row;
1172 this.requestingData = false;
1175 console.error(`grid getRows() error ${err}`);
1179 this.checkAllRetrieved(pager, idx);
1180 this.requestingData = false;
1187 // See if the last getRows() call resulted in the final set of data.
1188 checkAllRetrieved(pager: Pager, idx: number) {
1189 if (this.allRowsRetrieved) { return; }
1191 if (idx === 0 || idx < (pager.limit + pager.offset)) {
1192 // last query returned nothing or less than one page.
1193 // confirm we have all of the preceding pages.
1194 if (!this.data.includes(undefined)) {
1195 this.allRowsRetrieved = true;
1196 pager.resultCount = this.data.length;