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>;
35 isDragTarget: boolean;
37 isFilterable: boolean;
39 isMultiSortable: boolean;
40 disableTooltip: boolean;
41 comparator: (valueA: any, valueB: any) => number;
43 // True if the column was automatically generated.
48 filterOperator: string;
49 filterInputDisabled: boolean;
50 filterIncludeOrgAncestors: boolean;
51 filterIncludeOrgDescendants: boolean;
53 flesher: (obj: any, col: GridColumn, item: any) => any;
55 getCellContext(row: any) {
59 userContext: this.cellContext
68 this.isFiltered = false;
69 this.filterValue = undefined;
70 this.filterOperator = '=';
71 this.filterInputDisabled = false;
72 this.filterIncludeOrgAncestors = false;
73 this.filterIncludeOrgDescendants = false;
77 export class GridColumnSet {
78 columns: GridColumn[];
80 indexColumn: GridColumn;
82 isFilterable: boolean;
83 isMultiSortable: boolean;
84 stockVisible: string[];
86 defaultHiddenFields: string[];
87 defaultVisibleFields: string[];
89 constructor(idl: IdlService, idlClass?: string) {
92 this.stockVisible = [];
93 this.idlClass = idlClass;
96 add(col: GridColumn) {
98 this.applyColumnDefaults(col);
100 if (!this.insertColumn(col)) {
101 // Column was rejected as a duplicate.
105 if (col.isIndex) { this.indexColumn = col; }
107 // track which fields are visible on page load.
109 this.stockVisible.push(col.name);
112 this.applyColumnSortability(col);
113 this.applyColumnFilterability(col);
116 // Returns true if the new column was inserted, false otherwise.
117 // Declared columns take precedence over auto-generated columns
118 // when collisions occur.
119 // Declared columns are inserted in front of auto columns.
120 insertColumn(col: GridColumn): boolean {
123 if (this.getColByName(col.name)) {
124 // New auto-generated column conflicts with existing
128 // No collisions. Add to the end of the list
129 this.columns.push(col);
134 // Adding a declared column.
137 for (let idx = 0; idx < this.columns.length; idx++) {
138 const testCol = this.columns[idx];
139 if (testCol.name === col.name) { // match found
140 if (testCol.isAuto) {
141 // new column takes precedence, remove the existing column.
142 this.columns.splice(idx, 1);
145 // New column does not take precedence. Avoid
152 // Delcared columns are inserted just before the first auto-column
153 for (let idx = 0; idx < this.columns.length; idx++) {
154 const testCol = this.columns[idx];
155 if (testCol.isAuto) {
157 this.columns.unshift(col);
159 this.columns.splice(idx, 0, col);
165 // No insertion point found. Toss the new column on the end.
166 this.columns.push(col);
170 getColByName(name: string): GridColumn {
171 return this.columns.filter(c => c.name === name)[0];
174 idlInfoFromDotpath(dotpath: string): any {
175 if (!dotpath || !this.idlClass) { return null; }
180 let nextIdlClass = this.idl.classes[this.idlClass];
182 const pathParts = dotpath.split(/\./);
184 for (let i = 0; i < pathParts.length; i++) {
186 const part = pathParts[i];
187 idlParent = idlField;
188 idlClass = nextIdlClass;
189 idlField = idlClass.field_map[part];
191 if (!idlField) { return null; } // invalid IDL path
193 if (i === pathParts.length - 1) {
194 // No more links to process.
198 if (idlField['class'] && (
199 idlField.datatype === 'link' ||
200 idlField.datatype === 'org_unit')) {
201 // The link class on the current field refers to the
202 // class of the link destination, not the current field.
203 // Mark it for processing during the next iteration.
204 nextIdlClass = this.idl.classes[idlField['class']];
209 idlParent: idlParent,
217 this.columns.forEach(col => {
221 col.visible = this.stockVisible.includes(col.name);
225 applyColumnDefaults(col: GridColumn) {
227 if (!col.idlFieldDef) {
228 const idlInfo = this.idlInfoFromDotpath(col.path || col.name);
230 col.idlFieldDef = idlInfo.idlField;
231 col.idlClass = idlInfo.idlClass.name;
233 col.label = col.idlFieldDef.label || col.idlFieldDef.name;
234 col.datatype = col.idlFieldDef.datatype;
239 if (!col.name) { col.name = col.path; }
240 if (!col.flex) { col.flex = 2; }
241 if (!col.align) { col.align = 'left'; }
242 if (!col.label) { col.label = col.name; }
243 if (!col.datatype) { col.datatype = 'text'; }
245 col.visible = !col.hidden;
248 applyColumnSortability(col: GridColumn) {
249 // column sortability defaults to the sortability of the column set.
250 if (col.isSortable === undefined && this.isSortable) {
251 col.isSortable = true;
254 if (col.isMultiSortable === undefined && this.isMultiSortable) {
255 col.isMultiSortable = true;
258 if (col.isMultiSortable) {
259 col.isSortable = true;
262 applyColumnFilterability(col: GridColumn) {
263 // column filterability defaults to the afilterability of the column set.
264 if (col.isFilterable === undefined && this.isFilterable) {
265 col.isFilterable = true;
269 displayColumns(): GridColumn[] {
270 return this.columns.filter(c => c.visible);
273 insertBefore(source: GridColumn, target: GridColumn) {
276 this.columns.forEach((col, idx) => {
277 if (col.name === target.name) { targetIdx = idx; }});
279 this.columns.forEach((col, idx) => {
280 if (col.name === source.name) { sourceIdx = idx; }});
282 if (sourceIdx >= 0) {
283 this.columns.splice(sourceIdx, 1);
286 this.columns.splice(targetIdx, 0, source);
289 // Move visible columns to the front of the list.
290 moveVisibleToFront() {
291 const newCols = this.displayColumns();
292 this.columns.forEach(col => {
293 if (!col.visible) { newCols.push(col); }});
294 this.columns = newCols;
297 moveColumn(col: GridColumn, diff: number) {
298 let srcIdx, targetIdx;
300 this.columns.forEach((c, i) => {
301 if (c.name === col.name) { srcIdx = i; }
304 targetIdx = srcIdx + diff;
307 } else if (targetIdx >= this.columns.length) {
308 // Target index follows the last visible column.
310 this.columns.forEach((c, idx) => {
311 if (c.visible) { lastVisible = idx; }
314 // When moving a column (down) causes one or more
315 // visible columns to shuffle forward, our column
316 // moves into the slot of the last visible column.
317 // Otherwise, put it into the slot directly following
318 // the last visible column.
319 targetIdx = srcIdx <= lastVisible ? lastVisible : lastVisible + 1;
322 // Splice column out of old position, insert at new position.
323 this.columns.splice(srcIdx, 1);
324 this.columns.splice(targetIdx, 0, col);
327 compileSaveObject(): GridColumnPersistConf[] {
328 // only store information about visible columns.
329 // scrunch the data down to just the needed info.
330 return this.displayColumns().map(col => {
331 const c: GridColumnPersistConf = {name : col.name};
332 if (col.align !== 'left') { c.align = col.align; }
333 if (col.flex !== 2) { c.flex = Number(col.flex); }
334 if (Number(col.sort)) { c.sort = Number(col.sort); }
339 applyColumnSettings(conf: GridColumnPersistConf[]) {
341 if (!conf || conf.length === 0) {
342 // No configuration is available, but we have a list of
343 // fields to show or hide by default
345 if (this.defaultVisibleFields) {
346 this.columns.forEach(col => {
347 if (this.defaultVisibleFields.includes(col.name)) {
354 } else if (this.defaultHiddenFields) {
355 this.defaultHiddenFields.forEach(name => {
356 const col = this.getColByName(name);
368 conf.forEach(colConf => {
369 const col = this.getColByName(colConf.name);
370 if (!col) { return; } // no such column in this grid.
373 if (colConf.align) { col.align = colConf.align; }
374 if (colConf.flex) { col.flex = Number(colConf.flex); }
375 if (colConf.sort) { col.sort = Number(colConf.sort); }
377 // Add to new columns array, avoid dupes.
378 if (newCols.filter(c => c.name === col.name).length === 0) {
383 // columns which are not expressed within the saved
384 // configuration are marked as non-visible and
385 // appended to the end of the new list of columns.
386 this.columns.forEach(c => {
387 if (conf.filter(cf => cf.name === c.name).length === 0) {
393 this.columns = newCols;
398 export class GridRowSelector {
399 indexes: {[string: string]: boolean};
405 // Returns true if all of the requested indexes exist in the selector.
406 contains(index: string | string[]): boolean {
407 const indexes = [].concat(index);
408 for (let i = 0; i < indexes.length; i++) { // early exit
409 if (!this.indexes[indexes[i]]) {
416 select(index: string | string[]) {
417 const indexes = [].concat(index);
418 indexes.forEach(i => this.indexes[i] = true);
421 deselect(index: string | string[]) {
422 const indexes = [].concat(index);
423 indexes.forEach(i => delete this.indexes[i]);
426 // Returns the list of selected index values.
427 // In some contexts (template checkboxes) the value for an index is
428 // set to false to deselect instead of having it removed (via deselect()).
429 // NOTE GridRowSelector has no knowledge of when a row is no longer
430 // present in the grid. Use GridContext.getSelectedRows() to get
431 // list of selected rows that are still present in the grid.
433 return Object.keys(this.indexes).filter(
434 ind => Boolean(this.indexes[ind]));
438 return this.selected().length === 0;
446 export interface GridRowFlairEntry {
447 icon: string; // name of material icon
448 title?: string; // tooltip string
451 export class GridColumnPersistConf {
458 export class GridPersistConf {
461 columns: GridColumnPersistConf[];
464 export class GridContext {
469 isFilterable: boolean;
470 stickyGridHeader: boolean;
471 isMultiSortable: boolean;
472 useLocalSort: boolean;
474 disableMultiSelect: boolean;
475 disableSelect: boolean;
476 dataSource: GridDataSource;
477 columnSet: GridColumnSet;
478 rowSelector: GridRowSelector;
479 toolbarButtons: GridToolbarButton[];
480 toolbarCheckboxes: GridToolbarCheckbox[];
481 toolbarActions: GridToolbarAction[];
482 lastSelectedIndex: any;
483 pageChanges: Subscription;
484 rowFlairIsEnabled: boolean;
485 rowFlairCallback: (row: any) => GridRowFlairEntry;
486 rowClassCallback: (row: any) => string;
487 cellClassCallback: (row: any, col: GridColumn) => string;
488 defaultVisibleFields: string[];
489 defaultHiddenFields: string[];
490 overflowCells: boolean;
491 disablePaging: boolean;
492 showDeclaredFieldsOnly: boolean;
494 // Allow calling code to know when the select-all-rows-in-page
495 // action has occurred.
496 selectRowsInPageEmitter: EventEmitter<void>;
498 filterControls: QueryList<GridFilterControlComponent>;
500 // Services injected by our grid component
503 store: ServerStoreService;
504 format: FormatService;
509 store: ServerStoreService,
510 format: FormatService) {
515 this.format = format;
516 this.pager = new Pager();
517 this.rowSelector = new GridRowSelector();
518 this.toolbarButtons = [];
519 this.toolbarCheckboxes = [];
520 this.toolbarActions = [];
524 this.selectRowsInPageEmitter = new EventEmitter<void>();
525 this.columnSet = new GridColumnSet(this.idl, this.idlClass);
526 this.columnSet.isSortable = this.isSortable === true;
527 this.columnSet.isFilterable = this.isFilterable === true;
528 this.columnSet.isMultiSortable = this.isMultiSortable === true;
529 this.columnSet.defaultHiddenFields = this.defaultHiddenFields;
530 this.columnSet.defaultVisibleFields = this.defaultVisibleFields;
531 if (!this.pager.limit) {
532 this.pager.limit = this.disablePaging ? MAX_ALL_ROW_COUNT : 10;
534 this.generateColumns();
537 // Load initial settings and data.
539 this.applyGridConfig()
540 .then(ok => this.dataSource.requestPage(this.pager))
541 .then(ok => this.listenToPager());
548 applyGridConfig(): Promise<void> {
549 return this.getGridConfig(this.persistKey)
553 columns = conf.columns;
555 this.pager.limit = conf.limit;
559 // This is called regardless of the presence of saved
560 // settings so defaults can be applied.
561 this.columnSet.applyColumnSettings(columns);
566 // Give the UI time to settle before reloading grid data.
567 // This can help when data retrieval depends on a value
568 // getting modified by an angular digest cycle.
571 this.dataSource.reset();
572 this.dataSource.requestPage(this.pager);
576 reloadWithoutPagerReset() {
578 this.dataSource.reset();
579 this.dataSource.requestPage(this.pager);
583 // Sort the existing data source instead of requesting sorted
584 // data from the client. Reset pager to page 1. As with reload(),
585 // give the client a chance to setting before redisplaying.
589 this.sortLocalData();
590 this.dataSource.requestPage(this.pager);
594 // Subscribe or unsubscribe to page-change events from the pager.
596 if (this.pageChanges) { return; }
597 this.pageChanges = this.pager.onChange$.subscribe(
598 val => this.dataSource.requestPage(this.pager));
602 if (!this.pageChanges) { return; }
603 this.pageChanges.unsubscribe();
604 this.pageChanges = null;
607 // Sort data in the data source array
610 const sortDefs = this.dataSource.sort.map(sort => {
611 const column = this.columnSet.getColByName(sort.name);
619 if (!def.col.comparator) {
620 switch (def.col.datatype) {
624 def.col.comparator = (a, b) => {
627 if (a < b) { return -1; }
628 if (a > b) { return 1; }
633 def.col.comparator = (a, b) => {
634 if (a < b) { return -1; }
635 if (a > b) { return 1; }
644 this.dataSource.data.sort((rowA, rowB) => {
646 for (let idx = 0; idx < sortDefs.length; idx++) {
647 const sortDef = sortDefs[idx];
649 const valueA = this.getRowColumnValue(rowA, sortDef.col);
650 const valueB = this.getRowColumnValue(rowB, sortDef.col);
652 if (valueA === '' && valueB === '') { continue; }
653 if (valueA === '' && valueB !== '') { return 1; }
654 if (valueA !== '' && valueB === '') { return -1; }
656 const diff = sortDef.col.comparator(valueA, valueB);
657 if (diff === 0) { continue; }
659 return sortDef.dir === 'DESC' ? -diff : diff;
662 return 0; // No differences found.
666 getRowIndex(row: any): any {
667 const col = this.columnSet.indexColumn;
669 throw new Error('grid index column required');
671 return this.getRowColumnValue(row, col);
674 // Returns position in the data source array of the row with
675 // the provided index.
676 getRowPosition(index: any): number {
677 // for-loop for early exit
678 for (let idx = 0; idx < this.dataSource.data.length; idx++) {
679 const row = this.dataSource.data[idx];
680 if (row !== undefined && index === this.getRowIndex(row)) {
686 // Return the row with the provided index.
687 getRowByIndex(index: any): any {
688 for (let idx = 0; idx < this.dataSource.data.length; idx++) {
689 const row = this.dataSource.data[idx];
690 if (row !== undefined && index === this.getRowIndex(row)) {
696 // Returns all selected rows, regardless of whether they are
697 // currently visible in the grid display.
698 // De-selects previously selected rows which are no longer
699 // present in the grid.
700 getSelectedRows(): any[] {
704 this.rowSelector.selected().forEach(index => {
705 const row = this.getRowByIndex(index);
713 this.rowSelector.deselect(deleted);
717 rowIsSelected(row: any): boolean {
718 const index = this.getRowIndex(row);
719 return this.rowSelector.selected().filter(
724 getRowColumnValue(row: any, col: GridColumn): string {
728 val = this.nestedItemFieldValue(row, col);
729 } else if (col.name in row) {
730 val = this.getObjectFieldValue(row, col.name);
733 if (col.datatype === 'bool') {
734 // Avoid string-ifying bools so we can use an <eg-bool/>
735 // in the grid template.
739 return this.format.transform({
741 idlClass: col.idlClass,
742 idlField: col.idlFieldDef ? col.idlFieldDef.name : col.name,
743 datatype: col.datatype,
744 datePlusTime: Boolean(col.datePlusTime),
745 timezoneContextOrg: Number(col.timezoneContextOrg)
749 getObjectFieldValue(obj: any, name: string): any {
750 if (typeof obj[name] === 'function') {
757 nestedItemFieldValue(obj: any, col: GridColumn): string {
761 const original = obj;
762 const steps = col.path.split('.');
764 for (let i = 0; i < steps.length; i++) {
765 const step = steps[i];
767 if (obj === null || obj === undefined || typeof obj !== 'object') {
768 // We have run out of data to step through before
769 // reaching the end of the path. Conclude fleshing via
770 // callback if provided then exit.
771 if (col.flesher && obj !== undefined) {
772 return col.flesher(obj, col, original);
777 const class_ = obj.classname;
778 if (class_ && (idlClassDef = this.idl.classes[class_])) {
779 idlField = idlClassDef.field_map[step];
782 obj = this.getObjectFieldValue(obj, step);
785 // We found a nested IDL object which may or may not have
786 // been configured as a top-level column. Flesh the column
787 // metadata with our newly found IDL info.
790 col.datatype = idlField.datatype;
792 if (!col.idlFieldDef) {
793 idlField = col.idlFieldDef;
796 col.idlClass = idlClassDef.name;
799 col.label = idlField.label || idlField.name;
807 getColumnTextContent(row: any, col: GridColumn): string {
808 if (col.cellTemplate) {
810 // Extract the text content from the rendered template.
812 return this.getRowColumnValue(row, col);
816 selectOneRow(index: any) {
817 this.rowSelector.clear();
818 this.rowSelector.select(index);
819 this.lastSelectedIndex = index;
822 selectMultipleRows(indexes: any[]) {
823 this.rowSelector.clear();
824 this.rowSelector.select(indexes);
825 this.lastSelectedIndex = indexes[indexes.length - 1];
828 // selects or deselects an item, without affecting the others.
829 // returns true if the item is selected; false if de-selected.
830 toggleSelectOneRow(index: any) {
831 if (this.rowSelector.contains(index)) {
832 this.rowSelector.deselect(index);
836 this.rowSelector.select(index);
837 this.lastSelectedIndex = index;
841 selectRowByPos(pos: number) {
842 const row = this.dataSource.data[pos];
844 this.selectOneRow(this.getRowIndex(row));
848 selectPreviousRow() {
849 if (!this.lastSelectedIndex) { return; }
850 const pos = this.getRowPosition(this.lastSelectedIndex);
851 if (pos === this.pager.offset) {
852 this.toPrevPage().then(ok => this.selectLastRow(), err => {});
854 this.selectRowByPos(pos - 1);
859 if (!this.lastSelectedIndex) { return; }
860 const pos = this.getRowPosition(this.lastSelectedIndex);
861 if (pos === (this.pager.offset + this.pager.limit - 1)) {
862 this.toNextPage().then(ok => this.selectFirstRow(), err => {});
864 this.selectRowByPos(pos + 1);
869 // Select the previous row in addition to any currently selected row.
870 // However, if the previous row is already selected, assume the user
871 // has reversed direction and now wants to de-select the last selected row.
872 selectMultiRowsPrevious() {
873 if (!this.lastSelectedIndex) { return; }
874 const pos = this.getRowPosition(this.lastSelectedIndex);
875 const selectedIndexes = this.rowSelector.selected();
877 const promise = // load the previous page of data if needed
878 (pos === this.pager.offset) ? this.toPrevPage() : Promise.resolve();
882 const row = this.dataSource.data[pos - 1];
883 const newIndex = this.getRowIndex(row);
884 if (selectedIndexes.filter(i => i === newIndex).length > 0) {
885 // Prev row is already selected. User is reversing direction.
886 this.rowSelector.deselect(this.lastSelectedIndex);
887 this.lastSelectedIndex = newIndex;
889 this.selectMultipleRows(selectedIndexes.concat(newIndex));
897 // Select the next row in addition to any currently selected row.
898 // However, if the next row is already selected, assume the user
899 // has reversed direction and wants to de-select the last selected row.
900 selectMultiRowsNext() {
901 if (!this.lastSelectedIndex) { return; }
902 const pos = this.getRowPosition(this.lastSelectedIndex);
903 const selectedIndexes = this.rowSelector.selected();
905 const promise = // load the next page of data if needed
906 (pos === (this.pager.offset + this.pager.limit - 1)) ?
907 this.toNextPage() : Promise.resolve();
911 const row = this.dataSource.data[pos + 1];
912 const newIndex = this.getRowIndex(row);
913 if (selectedIndexes.filter(i => i === newIndex).length > 0) {
914 // Next row is already selected. User is reversing direction.
915 this.rowSelector.deselect(this.lastSelectedIndex);
916 this.lastSelectedIndex = newIndex;
918 this.selectMultipleRows(selectedIndexes.concat(newIndex));
925 getFirstRowInPage(): any {
926 return this.dataSource.data[this.pager.offset];
929 getLastRowInPage(): any {
930 return this.dataSource.data[this.pager.offset + this.pager.limit - 1];
934 this.selectOneRow(this.getRowIndex(this.getFirstRowInPage()));
938 this.selectOneRow(this.getRowIndex(this.getLastRowInPage()));
942 const rows = this.dataSource.getPageOfRows(this.pager);
943 const indexes = rows.map(r => this.getRowIndex(r));
944 this.rowSelector.select(indexes);
945 this.selectRowsInPageEmitter.emit();
948 toPrevPage(): Promise<any> {
949 if (this.pager.isFirstPage()) {
950 return Promise.reject('on first');
952 // temp ignore pager events since we're calling requestPage manually.
954 this.pager.decrement();
955 this.listenToPager();
956 return this.dataSource.requestPage(this.pager);
959 toNextPage(): Promise<any> {
960 if (this.pager.isLastPage()) {
961 return Promise.reject('on last');
963 // temp ignore pager events since we're calling requestPage manually.
965 this.pager.increment();
966 this.listenToPager();
967 return this.dataSource.requestPage(this.pager);
970 getAllRows(): Promise<any> {
971 const pager = new Pager();
973 pager.limit = MAX_ALL_ROW_COUNT;
974 return this.dataSource.requestPage(pager);
977 // Returns a key/value pair object of visible column data as text.
978 getRowAsFlatText(row: any): any {
980 this.columnSet.displayColumns().forEach(col => {
982 this.getColumnTextContent(row, col);
987 getAllRowsAsText(): Observable<any> {
988 return Observable.create(observer => {
989 this.getAllRows().then(ok => {
990 this.dataSource.data.forEach(row => {
991 observer.next(this.getRowAsFlatText(row));
998 removeFilters(): void {
999 this.dataSource.filters = {};
1000 this.columnSet.displayColumns().forEach(col => { col.removeFilter(); });
1001 this.filterControls.forEach(ctl => ctl.reset());
1004 filtersSet(): boolean {
1005 return Object.keys(this.dataSource.filters).length > 0;
1008 gridToCsv(): Promise<string> {
1011 const columns = this.columnSet.displayColumns();
1014 columns.forEach(col => {
1015 csvStr += this.valueToCsv(col.label),
1019 csvStr = csvStr.replace(/,$/, '\n');
1021 return new Promise(resolve => {
1022 this.getAllRowsAsText().subscribe(
1024 columns.forEach(col => {
1025 csvStr += this.valueToCsv(row[col.name]);
1028 csvStr = csvStr.replace(/,$/, '\n');
1031 () => resolve(csvStr)
1037 // prepares a string for inclusion within a CSV document
1038 // by escaping commas and quotes and removing newlines.
1039 valueToCsv(str: string): string {
1041 if (!str) { return ''; }
1042 str = str.replace(/\n/g, '');
1043 if (str.match(/\,/) || str.match(/"/)) {
1044 str = str.replace(/"/g, '""');
1045 str = '"' + str + '"';
1051 if (!this.columnSet.idlClass) { return; }
1053 const pkeyField = this.idl.classes[this.columnSet.idlClass].pkey;
1055 // generate columns for all non-virtual fields on the IDL class
1056 this.idl.classes[this.columnSet.idlClass].fields
1057 .filter(field => !field.virtual)
1059 const col = new GridColumn();
1060 col.name = field.name;
1061 col.label = field.label || field.name;
1062 col.idlFieldDef = field;
1063 col.idlClass = this.columnSet.idlClass;
1064 col.datatype = field.datatype;
1065 col.isIndex = (field.name === pkeyField);
1068 if (this.showDeclaredFieldsOnly) {
1072 this.columnSet.add(col);
1076 saveGridConfig(): Promise<any> {
1077 if (!this.persistKey) {
1078 throw new Error('Grid persistKey required to save columns');
1080 const conf = new GridPersistConf();
1082 conf.limit = this.pager.limit;
1083 conf.columns = this.columnSet.compileSaveObject();
1085 return this.store.setItem('eg.grid.' + this.persistKey, conf);
1088 // TODO: saveGridConfigAsOrgSetting(...)
1090 getGridConfig(persistKey: string): Promise<GridPersistConf> {
1091 if (!persistKey) { return Promise.resolve(null); }
1092 return this.store.getItem('eg.grid.' + persistKey);
1097 // Actions apply to specific rows
1098 export class GridToolbarAction {
1100 onClick: EventEmitter<any []>;
1101 action: (rows: any[]) => any; // DEPRECATED
1104 isGroup: boolean; // used for group placeholder entries
1105 isSeparator: boolean;
1106 disableOnRows: (rows: any[]) => boolean;
1109 // Buttons are global actions
1110 export class GridToolbarButton {
1112 onClick: EventEmitter<any []>;
1113 action: () => any; // DEPRECATED
1117 export class GridToolbarCheckbox {
1120 onChange: EventEmitter<boolean>;
1123 export class GridDataSource {
1128 allRowsRetrieved: boolean;
1129 requestingData: boolean;
1130 getRows: (pager: Pager, sort: any[]) => Observable<any>;
1140 this.allRowsRetrieved = false;
1143 // called from the template -- no data fetching
1144 getPageOfRows(pager: Pager): any[] {
1146 return this.data.slice(
1147 pager.offset, pager.limit + pager.offset
1148 ).filter(row => row !== undefined);
1153 // called on initial component load and user action (e.g. paging, sorting).
1154 requestPage(pager: Pager): Promise<any> {
1157 this.getPageOfRows(pager).length === pager.limit
1158 // already have all data
1159 || this.allRowsRetrieved
1160 // have no way to get more data.
1163 return Promise.resolve();
1166 // If we have to call out for data, set inFetch
1167 this.requestingData = true;
1169 return new Promise((resolve, reject) => {
1170 let idx = pager.offset;
1171 return this.getRows(pager, this.sort).subscribe(
1173 this.data[idx++] = row;
1174 this.requestingData = false;
1177 console.error(`grid getRows() error ${err}`);
1181 this.checkAllRetrieved(pager, idx);
1182 this.requestingData = false;
1189 // See if the last getRows() call resulted in the final set of data.
1190 checkAllRetrieved(pager: Pager, idx: number) {
1191 if (this.allRowsRetrieved) { return; }
1193 if (idx === 0 || idx < (pager.limit + pager.offset)) {
1194 // last query returned nothing or less than one page.
1195 // confirm we have all of the preceding pages.
1196 if (!this.data.includes(undefined)) {
1197 this.allRowsRetrieved = true;
1198 pager.resultCount = this.data.length;