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; }
179 let idlClass = this.idl.classes[this.idlClass];
181 const pathParts = dotpath.split(/\./);
183 for (let i = 0; i < pathParts.length; i++) {
184 const part = pathParts[i];
185 idlParent = idlField;
186 idlField = idlClass.field_map[part];
189 if (idlField['class'] && (
190 idlField.datatype === 'link' ||
191 idlField.datatype === 'org_unit')) {
192 idlClass = this.idl.classes[idlField['class']];
200 idlParent: idlParent,
208 this.columns.forEach(col => {
212 col.visible = this.stockVisible.includes(col.name);
216 applyColumnDefaults(col: GridColumn) {
218 if (!col.idlFieldDef && col.path) {
219 const idlInfo = this.idlInfoFromDotpath(col.path);
221 col.idlFieldDef = idlInfo.idlField;
222 col.idlClass = idlInfo.idlClass.name;
224 col.label = col.idlFieldDef.label || col.idlFieldDef.name;
225 col.datatype = col.idlFieldDef.datatype;
230 if (!col.name) { col.name = col.path; }
231 if (!col.flex) { col.flex = 2; }
232 if (!col.align) { col.align = 'left'; }
233 if (!col.label) { col.label = col.name; }
234 if (!col.datatype) { col.datatype = 'text'; }
236 col.visible = !col.hidden;
239 applyColumnSortability(col: GridColumn) {
240 // column sortability defaults to the sortability of the column set.
241 if (col.isSortable === undefined && this.isSortable) {
242 col.isSortable = true;
245 if (col.isMultiSortable === undefined && this.isMultiSortable) {
246 col.isMultiSortable = true;
249 if (col.isMultiSortable) {
250 col.isSortable = true;
253 applyColumnFilterability(col: GridColumn) {
254 // column filterability defaults to the afilterability of the column set.
255 if (col.isFilterable === undefined && this.isFilterable) {
256 col.isFilterable = true;
260 displayColumns(): GridColumn[] {
261 return this.columns.filter(c => c.visible);
264 insertBefore(source: GridColumn, target: GridColumn) {
267 this.columns.forEach((col, idx) => {
268 if (col.name === target.name) { targetIdx = idx; }});
270 this.columns.forEach((col, idx) => {
271 if (col.name === source.name) { sourceIdx = idx; }});
273 if (sourceIdx >= 0) {
274 this.columns.splice(sourceIdx, 1);
277 this.columns.splice(targetIdx, 0, source);
280 // Move visible columns to the front of the list.
281 moveVisibleToFront() {
282 const newCols = this.displayColumns();
283 this.columns.forEach(col => {
284 if (!col.visible) { newCols.push(col); }});
285 this.columns = newCols;
288 moveColumn(col: GridColumn, diff: number) {
289 let srcIdx, targetIdx;
291 this.columns.forEach((c, i) => {
292 if (c.name === col.name) { srcIdx = i; }
295 targetIdx = srcIdx + diff;
298 } else if (targetIdx >= this.columns.length) {
299 // Target index follows the last visible column.
301 this.columns.forEach((c, idx) => {
302 if (c.visible) { lastVisible = idx; }
305 // When moving a column (down) causes one or more
306 // visible columns to shuffle forward, our column
307 // moves into the slot of the last visible column.
308 // Otherwise, put it into the slot directly following
309 // the last visible column.
310 targetIdx = srcIdx <= lastVisible ? lastVisible : lastVisible + 1;
313 // Splice column out of old position, insert at new position.
314 this.columns.splice(srcIdx, 1);
315 this.columns.splice(targetIdx, 0, col);
318 compileSaveObject(): GridColumnPersistConf[] {
319 // only store information about visible columns.
320 // scrunch the data down to just the needed info.
321 return this.displayColumns().map(col => {
322 const c: GridColumnPersistConf = {name : col.name};
323 if (col.align !== 'left') { c.align = col.align; }
324 if (col.flex !== 2) { c.flex = Number(col.flex); }
325 if (Number(col.sort)) { c.sort = Number(col.sort); }
330 applyColumnSettings(conf: GridColumnPersistConf[]) {
332 if (!conf || conf.length === 0) {
333 // No configuration is available, but we have a list of
334 // fields to show or hide by default
336 if (this.defaultVisibleFields) {
337 this.columns.forEach(col => {
338 if (this.defaultVisibleFields.includes(col.name)) {
345 } else if (this.defaultHiddenFields) {
346 this.defaultHiddenFields.forEach(name => {
347 const col = this.getColByName(name);
359 conf.forEach(colConf => {
360 const col = this.getColByName(colConf.name);
361 if (!col) { return; } // no such column in this grid.
364 if (colConf.align) { col.align = colConf.align; }
365 if (colConf.flex) { col.flex = Number(colConf.flex); }
366 if (colConf.sort) { col.sort = Number(colConf.sort); }
368 // Add to new columns array, avoid dupes.
369 if (newCols.filter(c => c.name === col.name).length === 0) {
374 // columns which are not expressed within the saved
375 // configuration are marked as non-visible and
376 // appended to the end of the new list of columns.
377 this.columns.forEach(c => {
378 if (conf.filter(cf => cf.name === c.name).length === 0) {
384 this.columns = newCols;
389 export class GridRowSelector {
390 indexes: {[string: string]: boolean};
396 // Returns true if all of the requested indexes exist in the selector.
397 contains(index: string | string[]): boolean {
398 const indexes = [].concat(index);
399 for (let i = 0; i < indexes.length; i++) { // early exit
400 if (!this.indexes[indexes[i]]) {
407 select(index: string | string[]) {
408 const indexes = [].concat(index);
409 indexes.forEach(i => this.indexes[i] = true);
412 deselect(index: string | string[]) {
413 const indexes = [].concat(index);
414 indexes.forEach(i => delete this.indexes[i]);
417 // Returns the list of selected index values.
418 // In some contexts (template checkboxes) the value for an index is
419 // set to false to deselect instead of having it removed (via deselect()).
420 // NOTE GridRowSelector has no knowledge of when a row is no longer
421 // present in the grid. Use GridContext.getSelectedRows() to get
422 // list of selected rows that are still present in the grid.
424 return Object.keys(this.indexes).filter(
425 ind => Boolean(this.indexes[ind]));
429 return this.selected().length === 0;
437 export interface GridRowFlairEntry {
438 icon: string; // name of material icon
439 title?: string; // tooltip string
442 export class GridColumnPersistConf {
449 export class GridPersistConf {
452 columns: GridColumnPersistConf[];
455 export class GridContext {
460 isFilterable: boolean;
461 stickyGridHeader: boolean;
462 isMultiSortable: boolean;
463 useLocalSort: boolean;
465 disableMultiSelect: boolean;
466 disableSelect: boolean;
467 dataSource: GridDataSource;
468 columnSet: GridColumnSet;
469 rowSelector: GridRowSelector;
470 toolbarButtons: GridToolbarButton[];
471 toolbarCheckboxes: GridToolbarCheckbox[];
472 toolbarActions: GridToolbarAction[];
473 lastSelectedIndex: any;
474 pageChanges: Subscription;
475 rowFlairIsEnabled: boolean;
476 rowFlairCallback: (row: any) => GridRowFlairEntry;
477 rowClassCallback: (row: any) => string;
478 cellClassCallback: (row: any, col: GridColumn) => string;
479 defaultVisibleFields: string[];
480 defaultHiddenFields: string[];
481 overflowCells: boolean;
482 showLinkSelectors: boolean;
483 disablePaging: boolean;
484 showDeclaredFieldsOnly: boolean;
486 // Allow calling code to know when the select-all-rows-in-page
487 // action has occurred.
488 selectRowsInPageEmitter: EventEmitter<void>;
490 filterControls: QueryList<GridFilterControlComponent>;
492 // Services injected by our grid component
495 store: ServerStoreService;
496 format: FormatService;
501 store: ServerStoreService,
502 format: FormatService) {
507 this.format = format;
508 this.pager = new Pager();
509 this.rowSelector = new GridRowSelector();
510 this.toolbarButtons = [];
511 this.toolbarCheckboxes = [];
512 this.toolbarActions = [];
516 this.selectRowsInPageEmitter = new EventEmitter<void>();
517 this.columnSet = new GridColumnSet(this.idl, this.idlClass);
518 this.columnSet.isSortable = this.isSortable === true;
519 this.columnSet.isFilterable = this.isFilterable === true;
520 this.columnSet.isMultiSortable = this.isMultiSortable === true;
521 this.columnSet.defaultHiddenFields = this.defaultHiddenFields;
522 this.columnSet.defaultVisibleFields = this.defaultVisibleFields;
523 if (!this.pager.limit) {
524 this.pager.limit = this.disablePaging ? MAX_ALL_ROW_COUNT : 10;
526 this.generateColumns();
529 // Load initial settings and data.
531 this.applyGridConfig()
532 .then(ok => this.dataSource.requestPage(this.pager))
533 .then(ok => this.listenToPager());
540 applyGridConfig(): Promise<void> {
541 return this.getGridConfig(this.persistKey)
545 columns = conf.columns;
547 this.pager.limit = conf.limit;
551 // This is called regardless of the presence of saved
552 // settings so defaults can be applied.
553 this.columnSet.applyColumnSettings(columns);
558 // Give the UI time to settle before reloading grid data.
559 // This can help when data retrieval depends on a value
560 // getting modified by an angular digest cycle.
563 this.dataSource.reset();
564 this.dataSource.requestPage(this.pager);
568 reloadWithoutPagerReset() {
570 this.dataSource.reset();
571 this.dataSource.requestPage(this.pager);
575 // Sort the existing data source instead of requesting sorted
576 // data from the client. Reset pager to page 1. As with reload(),
577 // give the client a chance to setting before redisplaying.
581 this.sortLocalData();
582 this.dataSource.requestPage(this.pager);
586 // Subscribe or unsubscribe to page-change events from the pager.
588 if (this.pageChanges) { return; }
589 this.pageChanges = this.pager.onChange$.subscribe(
590 val => this.dataSource.requestPage(this.pager));
594 if (!this.pageChanges) { return; }
595 this.pageChanges.unsubscribe();
596 this.pageChanges = null;
599 // Sort data in the data source array
602 const sortDefs = this.dataSource.sort.map(sort => {
603 const column = this.columnSet.getColByName(sort.name);
611 if (!def.col.comparator) {
612 switch (def.col.datatype) {
616 def.col.comparator = (a, b) => {
619 if (a < b) { return -1; }
620 if (a > b) { return 1; }
625 def.col.comparator = (a, b) => {
626 if (a < b) { return -1; }
627 if (a > b) { return 1; }
636 this.dataSource.data.sort((rowA, rowB) => {
638 for (let idx = 0; idx < sortDefs.length; idx++) {
639 const sortDef = sortDefs[idx];
641 const valueA = this.getRowColumnValue(rowA, sortDef.col);
642 const valueB = this.getRowColumnValue(rowB, sortDef.col);
644 if (valueA === '' && valueB === '') { continue; }
645 if (valueA === '' && valueB !== '') { return 1; }
646 if (valueA !== '' && valueB === '') { return -1; }
648 const diff = sortDef.col.comparator(valueA, valueB);
649 if (diff === 0) { continue; }
651 return sortDef.dir === 'DESC' ? -diff : diff;
654 return 0; // No differences found.
658 getRowIndex(row: any): any {
659 const col = this.columnSet.indexColumn;
661 throw new Error('grid index column required');
663 return this.getRowColumnValue(row, col);
666 // Returns position in the data source array of the row with
667 // the provided index.
668 getRowPosition(index: any): number {
669 // for-loop for early exit
670 for (let idx = 0; idx < this.dataSource.data.length; idx++) {
671 const row = this.dataSource.data[idx];
672 if (row !== undefined && index === this.getRowIndex(row)) {
678 // Return the row with the provided index.
679 getRowByIndex(index: any): any {
680 for (let idx = 0; idx < this.dataSource.data.length; idx++) {
681 const row = this.dataSource.data[idx];
682 if (row !== undefined && index === this.getRowIndex(row)) {
688 // Returns all selected rows, regardless of whether they are
689 // currently visible in the grid display.
690 // De-selects previously selected rows which are no longer
691 // present in the grid.
692 getSelectedRows(): any[] {
696 this.rowSelector.selected().forEach(index => {
697 const row = this.getRowByIndex(index);
705 this.rowSelector.deselect(deleted);
709 rowIsSelected(row: any): boolean {
710 const index = this.getRowIndex(row);
711 return this.rowSelector.selected().filter(
716 getRowColumnValue(row: any, col: GridColumn): string {
720 val = this.nestedItemFieldValue(row, col);
721 } else if (col.name in row) {
722 val = this.getObjectFieldValue(row, col.name);
725 if (col.datatype === 'bool') {
726 // Avoid string-ifying bools so we can use an <eg-bool/>
727 // in the grid template.
731 return this.format.transform({
733 idlClass: col.idlClass,
734 idlField: col.idlFieldDef ? col.idlFieldDef.name : col.name,
735 datatype: col.datatype,
736 datePlusTime: Boolean(col.datePlusTime),
737 timezoneContextOrg: Number(col.timezoneContextOrg)
741 getObjectFieldValue(obj: any, name: string): any {
742 if (typeof obj[name] === 'function') {
749 nestedItemFieldValue(obj: any, col: GridColumn): string {
753 const original = obj;
754 const steps = col.path.split('.');
756 for (let i = 0; i < steps.length; i++) {
757 const step = steps[i];
759 if (obj === null || obj === undefined || typeof obj !== 'object') {
760 // We have run out of data to step through before
761 // reaching the end of the path. Conclude fleshing via
762 // callback if provided then exit.
763 if (col.flesher && obj !== undefined) {
764 return col.flesher(obj, col, original);
769 const class_ = obj.classname;
770 if (class_ && (idlClassDef = this.idl.classes[class_])) {
771 idlField = idlClassDef.field_map[step];
774 obj = this.getObjectFieldValue(obj, step);
777 // We found a nested IDL object which may or may not have
778 // been configured as a top-level column. Flesh the column
779 // metadata with our newly found IDL info.
782 col.datatype = idlField.datatype;
784 if (!col.idlFieldDef) {
785 idlField = col.idlFieldDef;
788 col.idlClass = idlClassDef.name;
791 col.label = idlField.label || idlField.name;
799 getColumnTextContent(row: any, col: GridColumn): string {
800 if (col.cellTemplate) {
802 // Extract the text content from the rendered template.
804 return this.getRowColumnValue(row, col);
808 selectOneRow(index: any) {
809 this.rowSelector.clear();
810 this.rowSelector.select(index);
811 this.lastSelectedIndex = index;
814 selectMultipleRows(indexes: any[]) {
815 this.rowSelector.clear();
816 this.rowSelector.select(indexes);
817 this.lastSelectedIndex = indexes[indexes.length - 1];
820 // selects or deselects an item, without affecting the others.
821 // returns true if the item is selected; false if de-selected.
822 toggleSelectOneRow(index: any) {
823 if (this.rowSelector.contains(index)) {
824 this.rowSelector.deselect(index);
828 this.rowSelector.select(index);
829 this.lastSelectedIndex = index;
833 selectRowByPos(pos: number) {
834 const row = this.dataSource.data[pos];
836 this.selectOneRow(this.getRowIndex(row));
840 selectPreviousRow() {
841 if (!this.lastSelectedIndex) { return; }
842 const pos = this.getRowPosition(this.lastSelectedIndex);
843 if (pos === this.pager.offset) {
844 this.toPrevPage().then(ok => this.selectLastRow(), err => {});
846 this.selectRowByPos(pos - 1);
851 if (!this.lastSelectedIndex) { return; }
852 const pos = this.getRowPosition(this.lastSelectedIndex);
853 if (pos === (this.pager.offset + this.pager.limit - 1)) {
854 this.toNextPage().then(ok => this.selectFirstRow(), err => {});
856 this.selectRowByPos(pos + 1);
861 // Select the previous row in addition to any currently selected row.
862 // However, if the previous row is already selected, assume the user
863 // has reversed direction and now wants to de-select the last selected row.
864 selectMultiRowsPrevious() {
865 if (!this.lastSelectedIndex) { return; }
866 const pos = this.getRowPosition(this.lastSelectedIndex);
867 const selectedIndexes = this.rowSelector.selected();
869 const promise = // load the previous page of data if needed
870 (pos === this.pager.offset) ? this.toPrevPage() : Promise.resolve();
874 const row = this.dataSource.data[pos - 1];
875 const newIndex = this.getRowIndex(row);
876 if (selectedIndexes.filter(i => i === newIndex).length > 0) {
877 // Prev row is already selected. User is reversing direction.
878 this.rowSelector.deselect(this.lastSelectedIndex);
879 this.lastSelectedIndex = newIndex;
881 this.selectMultipleRows(selectedIndexes.concat(newIndex));
889 // Select the next row in addition to any currently selected row.
890 // However, if the next row is already selected, assume the user
891 // has reversed direction and wants to de-select the last selected row.
892 selectMultiRowsNext() {
893 if (!this.lastSelectedIndex) { return; }
894 const pos = this.getRowPosition(this.lastSelectedIndex);
895 const selectedIndexes = this.rowSelector.selected();
897 const promise = // load the next page of data if needed
898 (pos === (this.pager.offset + this.pager.limit - 1)) ?
899 this.toNextPage() : Promise.resolve();
903 const row = this.dataSource.data[pos + 1];
904 const newIndex = this.getRowIndex(row);
905 if (selectedIndexes.filter(i => i === newIndex).length > 0) {
906 // Next row is already selected. User is reversing direction.
907 this.rowSelector.deselect(this.lastSelectedIndex);
908 this.lastSelectedIndex = newIndex;
910 this.selectMultipleRows(selectedIndexes.concat(newIndex));
917 getFirstRowInPage(): any {
918 return this.dataSource.data[this.pager.offset];
921 getLastRowInPage(): any {
922 return this.dataSource.data[this.pager.offset + this.pager.limit - 1];
926 this.selectOneRow(this.getRowIndex(this.getFirstRowInPage()));
930 this.selectOneRow(this.getRowIndex(this.getLastRowInPage()));
934 const rows = this.dataSource.getPageOfRows(this.pager);
935 const indexes = rows.map(r => this.getRowIndex(r));
936 this.rowSelector.select(indexes);
937 this.selectRowsInPageEmitter.emit();
940 toPrevPage(): Promise<any> {
941 if (this.pager.isFirstPage()) {
942 return Promise.reject('on first');
944 // temp ignore pager events since we're calling requestPage manually.
946 this.pager.decrement();
947 this.listenToPager();
948 return this.dataSource.requestPage(this.pager);
951 toNextPage(): Promise<any> {
952 if (this.pager.isLastPage()) {
953 return Promise.reject('on last');
955 // temp ignore pager events since we're calling requestPage manually.
957 this.pager.increment();
958 this.listenToPager();
959 return this.dataSource.requestPage(this.pager);
962 getAllRows(): Promise<any> {
963 const pager = new Pager();
965 pager.limit = MAX_ALL_ROW_COUNT;
966 return this.dataSource.requestPage(pager);
969 // Returns a key/value pair object of visible column data as text.
970 getRowAsFlatText(row: any): any {
972 this.columnSet.displayColumns().forEach(col => {
974 this.getColumnTextContent(row, col);
979 getAllRowsAsText(): Observable<any> {
980 return Observable.create(observer => {
981 this.getAllRows().then(ok => {
982 this.dataSource.data.forEach(row => {
983 observer.next(this.getRowAsFlatText(row));
990 removeFilters(): void {
991 this.dataSource.filters = {};
992 this.columnSet.displayColumns().forEach(col => { col.removeFilter(); });
993 this.filterControls.forEach(ctl => ctl.reset());
996 filtersSet(): boolean {
997 return Object.keys(this.dataSource.filters).length > 0;
1000 gridToCsv(): Promise<string> {
1003 const columns = this.columnSet.displayColumns();
1006 columns.forEach(col => {
1007 csvStr += this.valueToCsv(col.label),
1011 csvStr = csvStr.replace(/,$/, '\n');
1013 return new Promise(resolve => {
1014 this.getAllRowsAsText().subscribe(
1016 columns.forEach(col => {
1017 csvStr += this.valueToCsv(row[col.name]);
1020 csvStr = csvStr.replace(/,$/, '\n');
1023 () => resolve(csvStr)
1029 // prepares a string for inclusion within a CSV document
1030 // by escaping commas and quotes and removing newlines.
1031 valueToCsv(str: string): string {
1033 if (!str) { return ''; }
1034 str = str.replace(/\n/g, '');
1035 if (str.match(/\,/) || str.match(/"/)) {
1036 str = str.replace(/"/g, '""');
1037 str = '"' + str + '"';
1043 if (!this.columnSet.idlClass) { return; }
1045 const pkeyField = this.idl.classes[this.columnSet.idlClass].pkey;
1047 // generate columns for all non-virtual fields on the IDL class
1048 this.idl.classes[this.columnSet.idlClass].fields
1049 .filter(field => !field.virtual)
1051 const col = new GridColumn();
1052 col.name = field.name;
1053 col.label = field.label || field.name;
1054 col.idlFieldDef = field;
1055 col.idlClass = this.columnSet.idlClass;
1056 col.datatype = field.datatype;
1057 col.isIndex = (field.name === pkeyField);
1060 if (this.showLinkSelectors) {
1061 const selector = this.idl.getLinkSelector(
1062 this.columnSet.idlClass, field.name);
1064 col.path = field.name + '.' + selector;
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;