]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/eg2/src/app/share/grid/grid.ts
LP1904036 Grid flat data service/support
[Evergreen.git] / Open-ILS / src / eg2 / src / app / share / grid / grid.ts
1 /**
2  * Collection of grid related classses and interfaces.
3  */
4 import {TemplateRef, EventEmitter, QueryList} from '@angular/core';
5 import {Observable, Subscription, empty} 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';
12
13 const MAX_ALL_ROW_COUNT = 10000;
14
15 export class GridColumn {
16     name: string;
17     path: string;
18     label: string;
19     flex: number;
20     align: string;
21     hidden: boolean;
22     visible: boolean;
23     sort: number;
24     // IDL class of the object which contains this field.
25     // Not to be confused with the class of a linked object.
26     idlClass: string;
27     idlFieldDef: any;
28     datatype: string;
29     datePlusTime: boolean;
30     ternaryBool: boolean;
31     timezoneContextOrg: number;
32     cellTemplate: TemplateRef<any>;
33     dateOnlyIntervalField: string;
34
35     cellContext: any;
36     isIndex: boolean;
37     isDragTarget: boolean;
38     isSortable: boolean;
39     isFilterable: boolean;
40     isFiltered: boolean;
41     isMultiSortable: boolean;
42     disableTooltip: boolean;
43     asyncSupportsEmptyTermClick: boolean;
44     comparator: (valueA: any, valueB: any) => number;
45     required = false;
46
47     // True if the column was automatically generated.
48     isAuto: boolean;
49
50     // for filters
51     filterValue: string;
52     filterOperator: string;
53     filterInputDisabled: boolean;
54     filterIncludeOrgAncestors: boolean;
55     filterIncludeOrgDescendants: boolean;
56
57     flesher: (obj: any, col: GridColumn, item: any) => any;
58
59     getCellContext(row: any) {
60         return {
61           col: this,
62           row: row,
63           userContext: this.cellContext
64         };
65     }
66
67     constructor() {
68         this.removeFilter();
69     }
70
71     removeFilter() {
72         this.isFiltered = false;
73         this.filterValue = undefined;
74         this.filterOperator = '=';
75         this.filterInputDisabled = false;
76         this.filterIncludeOrgAncestors = false;
77         this.filterIncludeOrgDescendants = false;
78     }
79 }
80
81 export class GridColumnSet {
82     columns: GridColumn[];
83     idlClass: string;
84     indexColumn: GridColumn;
85     isSortable: boolean;
86     isFilterable: boolean;
87     isMultiSortable: boolean;
88     stockVisible: string[];
89     idl: IdlService;
90     defaultHiddenFields: string[];
91     defaultVisibleFields: string[];
92
93     constructor(idl: IdlService, idlClass?: string) {
94         this.idl = idl;
95         this.columns = [];
96         this.stockVisible = [];
97         this.idlClass = idlClass;
98     }
99
100     add(col: GridColumn) {
101
102         this.applyColumnDefaults(col);
103
104         if (!this.insertColumn(col)) {
105             // Column was rejected as a duplicate.
106             return;
107         }
108
109         if (col.isIndex) { this.indexColumn = col; }
110
111         // track which fields are visible on page load.
112         if (col.visible) {
113             this.stockVisible.push(col.name);
114         }
115
116         this.applyColumnSortability(col);
117         this.applyColumnFilterability(col);
118     }
119
120
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 {
126
127         if (col.isAuto) {
128             if (this.getColByName(col.name)) {
129                 // New auto-generated column conflicts with existing
130                 // column.  Skip it.
131                 return false;
132             } else {
133                 // No collisions.  Add to the end of the list
134                 this.columns.push(col);
135                 return true;
136             }
137         }
138
139         // Adding a declared column.
140
141         // Check for dupes.
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);
148                     break;
149                 } else {
150                     // New column does not take precedence.  Avoid
151                     // inserting it.
152                     return false;
153                 }
154             }
155         }
156
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) {
161                 if (idx === 0) {
162                     this.columns.unshift(col);
163                 } else {
164                     this.columns.splice(idx, 0, col);
165                 }
166                 return true;
167             }
168         }
169
170         // No insertion point found.  Toss the new column on the end.
171         this.columns.push(col);
172         return true;
173     }
174
175     getColByName(name: string): GridColumn {
176         return this.columns.filter(c => c.name === name)[0];
177     }
178
179     idlInfoFromDotpath(dotpath: string): any {
180         if (!dotpath || !this.idlClass) { return null; }
181
182         let idlParent;
183         let idlField;
184         let idlClass;
185         let nextIdlClass = this.idl.classes[this.idlClass];
186
187         const pathParts = dotpath.split(/\./);
188
189         for (let i = 0; i < pathParts.length; i++) {
190
191             const part = pathParts[i];
192             idlParent = idlField;
193             idlClass = nextIdlClass;
194             idlField = idlClass.field_map[part];
195
196             if (!idlField) { return null; } // invalid IDL path
197
198             if (i === pathParts.length - 1) {
199                 // No more links to process.
200                 break;
201             }
202
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']];
210             }
211         }
212
213         return {
214             idlParent: idlParent,
215             idlField : idlField,
216             idlClass : idlClass
217         };
218     }
219
220
221     reset() {
222         this.columns.forEach(col => {
223             col.flex = 2;
224             col.sort = 0;
225             col.align = 'left';
226             col.visible = this.stockVisible.includes(col.name);
227         });
228     }
229
230     applyColumnDefaults(col: GridColumn) {
231
232         if (!col.idlFieldDef) {
233             const idlInfo = this.idlInfoFromDotpath(col.path || col.name);
234             if (idlInfo) {
235                 col.idlFieldDef = idlInfo.idlField;
236                 col.idlClass = idlInfo.idlClass.name;
237                 if (!col.datatype) {
238                     col.datatype = col.idlFieldDef.datatype;
239                 }
240                 if (!col.label) {
241                     col.label = col.idlFieldDef.label || col.idlFieldDef.name;
242                 }
243             }
244         }
245
246         if (!col.name) { col.name = col.path; }
247         if (!col.flex) { col.flex = 2; }
248         if (!col.align) { col.align = 'left'; }
249         if (!col.label) { col.label = col.name; }
250         if (!col.datatype) { col.datatype = 'text'; }
251
252         col.visible = !col.hidden;
253     }
254
255     applyColumnSortability(col: GridColumn) {
256         // column sortability defaults to the sortability of the column set.
257         if (col.isSortable === undefined && this.isSortable) {
258             col.isSortable = true;
259         }
260
261         if (col.isMultiSortable === undefined && this.isMultiSortable) {
262             col.isMultiSortable = true;
263         }
264
265         if (col.isMultiSortable) {
266             col.isSortable = true;
267         }
268     }
269     applyColumnFilterability(col: GridColumn) {
270         // column filterability defaults to the afilterability of the column set.
271         if (col.isFilterable === undefined && this.isFilterable) {
272             col.isFilterable = true;
273         }
274     }
275
276     displayColumns(): GridColumn[] {
277         return this.columns.filter(c => c.visible);
278     }
279
280     // Sorted visible columns followed by sorted non-visible columns.
281     // Note we don't sort this.columns directly as it would impact
282     // grid column display ordering.
283     sortForColPicker(): GridColumn[] {
284         const visible = this.columns.filter(c => c.visible);
285         const invisible = this.columns.filter(c => !c.visible);
286
287         visible.sort((a, b) => a.label < b.label ? -1 : 1);
288         invisible.sort((a, b) => a.label < b.label ? -1 : 1);
289
290         return visible.concat(invisible);
291     }
292
293     requiredColumns(): GridColumn[] {
294         const visible = this.displayColumns();
295         return visible.concat(
296             this.columns.filter(c => c.required && !c.visible));
297     }
298
299     insertBefore(source: GridColumn, target: GridColumn) {
300         let targetIdx = -1;
301         let sourceIdx = -1;
302         this.columns.forEach((col, idx) => {
303             if (col.name === target.name) { targetIdx = idx; }});
304
305         this.columns.forEach((col, idx) => {
306             if (col.name === source.name) { sourceIdx = idx; }});
307
308         if (sourceIdx >= 0) {
309             this.columns.splice(sourceIdx, 1);
310         }
311
312         this.columns.splice(targetIdx, 0, source);
313     }
314
315     // Move visible columns to the front of the list.
316     moveVisibleToFront() {
317         const newCols = this.displayColumns();
318         this.columns.forEach(col => {
319             if (!col.visible) { newCols.push(col); }});
320         this.columns = newCols;
321     }
322
323     moveColumn(col: GridColumn, diff: number) {
324         let srcIdx, targetIdx;
325
326         this.columns.forEach((c, i) => {
327           if (c.name === col.name) { srcIdx = i; }
328         });
329
330         targetIdx = srcIdx + diff;
331         if (targetIdx < 0) {
332             targetIdx = 0;
333         } else if (targetIdx >= this.columns.length) {
334             // Target index follows the last visible column.
335             let lastVisible = 0;
336             this.columns.forEach((c, idx) => {
337                 if (c.visible) { lastVisible = idx; }
338             });
339
340             // When moving a column (down) causes one or more
341             // visible columns to shuffle forward, our column
342             // moves into the slot of the last visible column.
343             // Otherwise, put it into the slot directly following
344             // the last visible column.
345             targetIdx = srcIdx <= lastVisible ? lastVisible : lastVisible + 1;
346         }
347
348         // Splice column out of old position, insert at new position.
349         this.columns.splice(srcIdx, 1);
350         this.columns.splice(targetIdx, 0, col);
351     }
352
353     compileSaveObject(): GridColumnPersistConf[] {
354         // only store information about visible columns.
355         // scrunch the data down to just the needed info.
356         return this.displayColumns().map(col => {
357             const c: GridColumnPersistConf = {name : col.name};
358             if (col.align !== 'left') { c.align = col.align; }
359             if (col.flex !== 2) { c.flex = Number(col.flex); }
360             if (Number(col.sort)) { c.sort = Number(col.sort); }
361             return c;
362         });
363     }
364
365     applyColumnSettings(conf: GridColumnPersistConf[]) {
366
367         if (!conf || conf.length === 0) {
368             // No configuration is available, but we have a list of
369             // fields to show or hide by default
370
371             if (this.defaultVisibleFields) {
372                 this.columns.forEach(col => {
373                     if (this.defaultVisibleFields.includes(col.name)) {
374                         col.visible = true;
375                     } else {
376                         col.visible = false;
377                     }
378                 });
379
380             } else if (this.defaultHiddenFields) {
381                 this.defaultHiddenFields.forEach(name => {
382                     const col = this.getColByName(name);
383                     if (col) {
384                         col.visible = false;
385                     }
386                 });
387             }
388
389             return;
390         }
391
392         const newCols = [];
393
394         conf.forEach(colConf => {
395             const col = this.getColByName(colConf.name);
396             if (!col) { return; } // no such column in this grid.
397
398             col.visible = true;
399             if (colConf.align) { col.align = colConf.align; }
400             if (colConf.flex)  { col.flex = Number(colConf.flex); }
401             if (colConf.sort)  { col.sort = Number(colConf.sort); }
402
403             // Add to new columns array, avoid dupes.
404             if (newCols.filter(c => c.name === col.name).length === 0) {
405                 newCols.push(col);
406             }
407         });
408
409         // columns which are not expressed within the saved
410         // configuration are marked as non-visible and
411         // appended to the end of the new list of columns.
412         this.columns.forEach(c => {
413             if (conf.filter(cf => cf.name === c.name).length === 0) {
414                 c.visible = false;
415                 newCols.push(c);
416             }
417         });
418
419         this.columns = newCols;
420     }
421 }
422
423 // Maps colunm names to functions which return plain text values for
424 // each mapped column on a given row.  This is primarily useful for
425 // generating print-friendly content for grid cells rendered via
426 // cellTemplate.
427 //
428 // USAGE NOTE: Since a cellTemplate can be passed arbitrary context
429 //             but a GridCellTextGenerator only gets the row object,
430 //             if it's important to include content that's not available
431 //             by default in the row object, you may want to stick
432 //             it in the row object as an additional attribute.
433 //
434 export interface GridCellTextGenerator {
435     [columnName: string]: (row: any) => string;
436 }
437
438 export class GridRowSelector {
439     indexes: {[string: string]: boolean};
440
441     // Track these so we can emit the selectionChange event
442     // only when the selection actually changes.
443     previousSelection: string[] = [];
444
445     // Emits the selected indexes on selection change
446     selectionChange: EventEmitter<string[]> = new EventEmitter<string[]>();
447
448     constructor() {
449         this.clear();
450     }
451
452     // Returns true if all of the requested indexes exist in the selector.
453     contains(index: string | string[]): boolean {
454         const indexes = [].concat(index);
455         for (let i = 0; i < indexes.length; i++) { // early exit
456             if (!this.indexes[indexes[i]]) {
457                 return false;
458             }
459         }
460         return true;
461     }
462
463     emitChange() {
464         const keys = this.selected();
465
466         if (keys.length === this.previousSelection.length &&
467             this.contains(this.previousSelection)) {
468             return; // No change has occurred
469         }
470
471         this.previousSelection = keys;
472         this.selectionChange.emit(keys);
473     }
474
475     select(index: string | string[]) {
476         const indexes = [].concat(index);
477         indexes.forEach(i => this.indexes[i] = true);
478         this.emitChange();
479     }
480
481     deselect(index: string | string[]) {
482         const indexes = [].concat(index);
483         indexes.forEach(i => delete this.indexes[i]);
484         this.emitChange();
485     }
486
487     toggle(index: string) {
488         if (this.indexes[index]) {
489             this.deselect(index);
490         } else {
491             this.select(index);
492         }
493     }
494
495     selected(): string[] {
496         return Object.keys(this.indexes);
497     }
498
499     isEmpty(): boolean {
500         return this.selected().length === 0;
501     }
502
503     clear() {
504         this.indexes = {};
505         this.emitChange();
506     }
507 }
508
509 export interface GridRowFlairEntry {
510     icon: string;   // name of material icon
511     title?: string;  // tooltip string
512 }
513
514 export class GridColumnPersistConf {
515     name: string;
516     flex?: number;
517     sort?: number;
518     align?: string;
519 }
520
521 export class GridPersistConf {
522     version: number;
523     limit: number;
524     columns: GridColumnPersistConf[];
525     hideToolbarActions: string[];
526 }
527
528 export class GridContext {
529
530     pager: Pager;
531     idlClass: string;
532     isSortable: boolean;
533     isFilterable: boolean;
534     stickyGridHeader: boolean;
535     isMultiSortable: boolean;
536     useLocalSort: boolean;
537     persistKey: string;
538     disableMultiSelect: boolean;
539     disableSelect: boolean;
540     dataSource: GridDataSource;
541     columnSet: GridColumnSet;
542     autoGeneratedColumnOrder: string;
543     rowSelector: GridRowSelector;
544     toolbarLabel: string;
545     toolbarButtons: GridToolbarButton[];
546     toolbarCheckboxes: GridToolbarCheckbox[];
547     toolbarActions: GridToolbarAction[];
548     lastSelectedIndex: any;
549     pageChanges: Subscription;
550     rowFlairIsEnabled: boolean;
551     rowFlairCallback: (row: any) => GridRowFlairEntry;
552     rowClassCallback: (row: any) => string;
553     cellClassCallback: (row: any, col: GridColumn) => string;
554     defaultVisibleFields: string[];
555     defaultHiddenFields: string[];
556     ignoredFields: string[];
557     overflowCells: boolean;
558     disablePaging: boolean;
559     showDeclaredFieldsOnly: boolean;
560     cellTextGenerator: GridCellTextGenerator;
561     reloadOnColumnChange: boolean;
562
563     // Allow calling code to know when the select-all-rows-in-page
564     // action has occurred.
565     selectRowsInPageEmitter: EventEmitter<void>;
566
567     filterControls: QueryList<GridFilterControlComponent>;
568
569     // Services injected by our grid component
570     idl: IdlService;
571     org: OrgService;
572     store: ServerStoreService;
573     format: FormatService;
574
575     constructor(
576         idl: IdlService,
577         org: OrgService,
578         store: ServerStoreService,
579         format: FormatService) {
580
581         this.idl = idl;
582         this.org = org;
583         this.store = store;
584         this.format = format;
585         this.pager = new Pager();
586         this.rowSelector = new GridRowSelector();
587         this.toolbarButtons = [];
588         this.toolbarCheckboxes = [];
589         this.toolbarActions = [];
590     }
591
592     init() {
593         this.selectRowsInPageEmitter = new EventEmitter<void>();
594         this.columnSet = new GridColumnSet(this.idl, this.idlClass);
595         this.columnSet.isSortable = this.isSortable === true;
596         this.columnSet.isFilterable = this.isFilterable === true;
597         this.columnSet.isMultiSortable = this.isMultiSortable === true;
598         this.columnSet.defaultHiddenFields = this.defaultHiddenFields;
599         this.columnSet.defaultVisibleFields = this.defaultVisibleFields;
600         if (!this.pager.limit) {
601             this.pager.limit = this.disablePaging ? MAX_ALL_ROW_COUNT : 10;
602         }
603         this.generateColumns();
604     }
605
606     // Load initial settings and data.
607     initData() {
608         this.applyGridConfig()
609         .then(ok => this.dataSource.requestPage(this.pager))
610         .then(ok => this.listenToPager());
611     }
612
613     destroy() {
614         this.ignorePager();
615     }
616
617     applyGridConfig(): Promise<void> {
618         return this.getGridConfig(this.persistKey)
619         .then(conf => {
620             let columns = [];
621             if (conf) {
622                 columns = conf.columns;
623                 if (conf.limit && !this.disablePaging) {
624                     this.pager.limit = conf.limit;
625                 }
626                 this.applyToolbarActionVisibility(conf.hideToolbarActions);
627             }
628
629             // This is called regardless of the presence of saved
630             // settings so defaults can be applied.
631             this.columnSet.applyColumnSettings(columns);
632         });
633     }
634
635     applyToolbarActionVisibility(hidden: string[]) {
636         if (!hidden || hidden.length === 0) { return; }
637
638         const groups = [];
639         this.toolbarActions.forEach(action => {
640             if (action.isGroup) {
641                 groups.push(action);
642             } else if (!action.isSeparator) {
643                 action.hidden = hidden.includes(action.label);
644             }
645         });
646
647         // If all actions in a group are hidden, hide the group as well.
648         // Note the group may be marked as hidden in the configuration,
649         // but the addition of new entries within a group should cause
650         // it to be visible again.
651         groups.forEach(group => {
652             const visible = this.toolbarActions
653                 .filter(action => action.group === group.label && !action.hidden);
654             group.hidden = visible.length === 0;
655         });
656     }
657
658     reload() {
659         // Give the UI time to settle before reloading grid data.
660         // This can help when data retrieval depends on a value
661         // getting modified by an angular digest cycle.
662         setTimeout(() => {
663             this.pager.reset();
664             this.dataSource.reset();
665             this.dataSource.requestPage(this.pager);
666         });
667     }
668
669     reloadWithoutPagerReset() {
670         setTimeout(() => {
671             this.dataSource.reset();
672             this.dataSource.requestPage(this.pager);
673         });
674     }
675
676     // Sort the existing data source instead of requesting sorted
677     // data from the client.  Reset pager to page 1.  As with reload(),
678     // give the client a chance to setting before redisplaying.
679     sortLocal() {
680         setTimeout(() => {
681             this.pager.reset();
682             this.sortLocalData();
683             this.dataSource.requestPage(this.pager);
684         });
685     }
686
687     // Subscribe or unsubscribe to page-change events from the pager.
688     listenToPager() {
689         if (this.pageChanges) { return; }
690         this.pageChanges = this.pager.onChange$.subscribe(
691             val => this.dataSource.requestPage(this.pager));
692     }
693
694     ignorePager() {
695         if (!this.pageChanges) { return; }
696         this.pageChanges.unsubscribe();
697         this.pageChanges = null;
698     }
699
700     // Sort data in the data source array
701     sortLocalData() {
702
703         const sortDefs = this.dataSource.sort.map(sort => {
704             const column = this.columnSet.getColByName(sort.name);
705
706             const def = {
707                 name: sort.name,
708                 dir: sort.dir,
709                 col: column
710             };
711
712             if (!def.col.comparator) {
713                 switch (def.col.datatype) {
714                     case 'id':
715                     case 'money':
716                     case 'int':
717                         def.col.comparator = (a, b) => {
718                             a = Number(a);
719                             b = Number(b);
720                             if (a < b) { return -1; }
721                             if (a > b) { return 1; }
722                             return 0;
723                         };
724                         break;
725                     default:
726                         def.col.comparator = (a, b) => {
727                             if (a < b) { return -1; }
728                             if (a > b) { return 1; }
729                             return 0;
730                         };
731                 }
732             }
733
734             return def;
735         });
736
737         this.dataSource.data.sort((rowA, rowB) => {
738
739             for (let idx = 0; idx < sortDefs.length; idx++) {
740                 const sortDef = sortDefs[idx];
741
742                 const valueA = this.getRowColumnValue(rowA, sortDef.col);
743                 const valueB = this.getRowColumnValue(rowB, sortDef.col);
744
745                 if (valueA === '' && valueB === '') { continue; }
746                 if (valueA === '' && valueB !== '') { return 1; }
747                 if (valueA !== '' && valueB === '') { return -1; }
748
749                 const diff = sortDef.col.comparator(valueA, valueB);
750                 if (diff === 0) { continue; }
751
752                 return sortDef.dir === 'DESC' ? -diff : diff;
753             }
754
755             return 0; // No differences found.
756         });
757     }
758
759     getRowIndex(row: any): any {
760         const col = this.columnSet.indexColumn;
761         if (!col) {
762             throw new Error('grid index column required');
763         }
764         return this.getRowColumnValue(row, col);
765     }
766
767     // Returns position in the data source array of the row with
768     // the provided index.
769     getRowPosition(index: any): number {
770         // for-loop for early exit
771         for (let idx = 0; idx < this.dataSource.data.length; idx++) {
772             const row = this.dataSource.data[idx];
773             if (row !== undefined && index === this.getRowIndex(row)) {
774                 return idx;
775             }
776         }
777     }
778
779     // Return the row with the provided index.
780     getRowByIndex(index: any): any {
781         for (let idx = 0; idx < this.dataSource.data.length; idx++) {
782             const row = this.dataSource.data[idx];
783             if (row !== undefined && index === this.getRowIndex(row)) {
784                 return row;
785             }
786         }
787     }
788
789     // Returns all selected rows, regardless of whether they are
790     // currently visible in the grid display.
791     // De-selects previously selected rows which are no longer
792     // present in the grid.
793     getSelectedRows(): any[] {
794         const selected = [];
795         const deleted = [];
796
797         this.rowSelector.selected().forEach(index => {
798             const row = this.getRowByIndex(index);
799             if (row) {
800                 selected.push(row);
801             } else {
802                 deleted.push(index);
803             }
804         });
805
806         this.rowSelector.deselect(deleted);
807         return selected;
808     }
809
810     rowIsSelected(row: any): boolean {
811         const index = this.getRowIndex(row);
812         return this.rowSelector.selected().filter(
813             idx => idx === index
814         ).length > 0;
815     }
816
817     getRowColumnBareValue(row: any, col: GridColumn): any {
818         if (col.name in row) {
819             return this.getObjectFieldValue(row, col.name);
820         } else if (col.path) {
821             return this.nestedItemFieldValue(row, col);
822         }
823     }
824
825     getRowColumnValue(row: any, col: GridColumn): any {
826         const val = this.getRowColumnBareValue(row, col);
827
828         if (col.datatype === 'bool') {
829             // Avoid string-ifying bools so we can use an <eg-bool/>
830             // in the grid template.
831             return val;
832         }
833
834         let interval;
835         const intField = col.dateOnlyIntervalField;
836         if (intField) {
837             const intCol =
838                 this.columnSet.columns.filter(c => c.path === intField)[0];
839             if (intCol) {
840                 interval = this.getRowColumnBareValue(row, intCol);
841             }
842         }
843
844         return this.format.transform({
845             value: val,
846             idlClass: col.idlClass,
847             idlField: col.idlFieldDef ? col.idlFieldDef.name : col.name,
848             datatype: col.datatype,
849             datePlusTime: Boolean(col.datePlusTime),
850             timezoneContextOrg: Number(col.timezoneContextOrg),
851             dateOnlyInterval: interval
852         });
853     }
854
855     getObjectFieldValue(obj: any, name: string): any {
856         if (typeof obj[name] === 'function') {
857             return obj[name]();
858         } else {
859             return obj[name];
860         }
861     }
862
863     nestedItemFieldValue(obj: any, col: GridColumn): string {
864
865         let idlField;
866         let idlClassDef;
867         const original = obj;
868         const steps = col.path.split('.');
869
870         for (let i = 0; i < steps.length; i++) {
871             const step = steps[i];
872
873             if (obj === null || obj === undefined || typeof obj !== 'object') {
874                 // We have run out of data to step through before
875                 // reaching the end of the path.  Conclude fleshing via
876                 // callback if provided then exit.
877                 if (col.flesher && obj !== undefined) {
878                     return col.flesher(obj, col, original);
879                 }
880                 return obj;
881             }
882
883             const class_ = obj.classname;
884             if (class_ && (idlClassDef = this.idl.classes[class_])) {
885                 idlField = idlClassDef.field_map[step];
886             }
887
888             obj = this.getObjectFieldValue(obj, step);
889         }
890
891         // We found a nested IDL object which may or may not have
892         // been configured as a top-level column.  Flesh the column
893         // metadata with our newly found IDL info.
894         if (idlField) {
895             if (!col.datatype) {
896                 col.datatype = idlField.datatype;
897             }
898             if (!col.idlFieldDef) {
899                 idlField = col.idlFieldDef;
900             }
901             if (!col.idlClass) {
902                 col.idlClass = idlClassDef.name;
903             }
904             if (!col.label) {
905                 col.label = idlField.label || idlField.name;
906             }
907         }
908
909         return obj;
910     }
911
912
913     getColumnTextContent(row: any, col: GridColumn): string {
914         if (this.columnHasTextGenerator(col)) {
915             const str = this.cellTextGenerator[col.name](row);
916             return (str === null || str === undefined)  ? '' : str;
917         } else {
918             if (col.cellTemplate) {
919                 return ''; // avoid 'undefined' values
920             } else {
921                 return this.getRowColumnValue(row, col);
922             }
923         }
924     }
925
926     selectOneRow(index: any) {
927         this.rowSelector.clear();
928         this.rowSelector.select(index);
929         this.lastSelectedIndex = index;
930     }
931
932     selectMultipleRows(indexes: any[]) {
933         this.rowSelector.clear();
934         this.rowSelector.select(indexes);
935         this.lastSelectedIndex = indexes[indexes.length - 1];
936     }
937
938     // selects or deselects an item, without affecting the others.
939     // returns true if the item is selected; false if de-selected.
940     toggleSelectOneRow(index: any) {
941         if (this.rowSelector.contains(index)) {
942             this.rowSelector.deselect(index);
943             return false;
944         }
945
946         this.rowSelector.select(index);
947         this.lastSelectedIndex = index;
948         return true;
949     }
950
951     selectRowByPos(pos: number) {
952         const row = this.dataSource.data[pos];
953         if (row) {
954             this.selectOneRow(this.getRowIndex(row));
955         }
956     }
957
958     selectPreviousRow() {
959         if (!this.lastSelectedIndex) { return; }
960         const pos = this.getRowPosition(this.lastSelectedIndex);
961         if (pos === this.pager.offset) {
962             this.toPrevPage().then(ok => this.selectLastRow(), err => {});
963         } else {
964             this.selectRowByPos(pos - 1);
965         }
966     }
967
968     selectNextRow() {
969         if (!this.lastSelectedIndex) { return; }
970         const pos = this.getRowPosition(this.lastSelectedIndex);
971         if (pos === (this.pager.offset + this.pager.limit - 1)) {
972             this.toNextPage().then(ok => this.selectFirstRow(), err => {});
973         } else {
974             this.selectRowByPos(pos + 1);
975         }
976     }
977
978     // shift-up-arrow
979     // Select the previous row in addition to any currently selected row.
980     // However, if the previous row is already selected, assume the user
981     // has reversed direction and now wants to de-select the last selected row.
982     selectMultiRowsPrevious() {
983         if (!this.lastSelectedIndex) { return; }
984         const pos = this.getRowPosition(this.lastSelectedIndex);
985         const selectedIndexes = this.rowSelector.selected();
986
987         const promise = // load the previous page of data if needed
988             (pos === this.pager.offset) ? this.toPrevPage() : Promise.resolve();
989
990         promise.then(
991             ok => {
992                 const row = this.dataSource.data[pos - 1];
993                 const newIndex = this.getRowIndex(row);
994                 if (selectedIndexes.filter(i => i === newIndex).length > 0) {
995                     // Prev row is already selected.  User is reversing direction.
996                     this.rowSelector.deselect(this.lastSelectedIndex);
997                     this.lastSelectedIndex = newIndex;
998                 } else {
999                     this.selectMultipleRows(selectedIndexes.concat(newIndex));
1000                 }
1001             },
1002             err => {}
1003         );
1004     }
1005
1006     // Select all rows between the previously selected row and
1007     // the provided row, including the provided row.
1008     // This is additive only -- rows are never de-selected.
1009     selectRowRange(index: any) {
1010
1011         if (!this.lastSelectedIndex) {
1012             this.selectOneRow(index);
1013             return;
1014         }
1015
1016         const next = this.getRowPosition(index);
1017         const prev = this.getRowPosition(this.lastSelectedIndex);
1018         const start = Math.min(prev, next);
1019         const end = Math.max(prev, next);
1020
1021         for (let idx = start; idx <= end; idx++) {
1022             const row = this.dataSource.data[idx];
1023             if (row) {
1024                 this.rowSelector.select(this.getRowIndex(row));
1025             }
1026         }
1027
1028         this.lastSelectedIndex = index;
1029     }
1030
1031     // shift-down-arrow
1032     // Select the next row in addition to any currently selected row.
1033     // However, if the next row is already selected, assume the user
1034     // has reversed direction and wants to de-select the last selected row.
1035     selectMultiRowsNext() {
1036         if (!this.lastSelectedIndex) { return; }
1037         const pos = this.getRowPosition(this.lastSelectedIndex);
1038         const selectedIndexes = this.rowSelector.selected();
1039
1040         const promise = // load the next page of data if needed
1041             (pos === (this.pager.offset + this.pager.limit - 1)) ?
1042             this.toNextPage() : Promise.resolve();
1043
1044         promise.then(
1045             ok => {
1046                 const row = this.dataSource.data[pos + 1];
1047                 const newIndex = this.getRowIndex(row);
1048                 if (selectedIndexes.filter(i => i === newIndex).length > 0) {
1049                     // Next row is already selected.  User is reversing direction.
1050                     this.rowSelector.deselect(this.lastSelectedIndex);
1051                     this.lastSelectedIndex = newIndex;
1052                 } else {
1053                     this.selectMultipleRows(selectedIndexes.concat(newIndex));
1054                 }
1055             },
1056             err => {}
1057         );
1058     }
1059
1060     getFirstRowInPage(): any {
1061         return this.dataSource.data[this.pager.offset];
1062     }
1063
1064     getLastRowInPage(): any {
1065         return this.dataSource.data[this.pager.offset + this.pager.limit - 1];
1066     }
1067
1068     selectFirstRow() {
1069         this.selectOneRow(this.getRowIndex(this.getFirstRowInPage()));
1070     }
1071
1072     selectLastRow() {
1073         this.selectOneRow(this.getRowIndex(this.getLastRowInPage()));
1074     }
1075
1076     selectRowsInPage() {
1077         const rows = this.dataSource.getPageOfRows(this.pager);
1078         const indexes = rows.map(r => this.getRowIndex(r));
1079         this.rowSelector.select(indexes);
1080         this.selectRowsInPageEmitter.emit();
1081     }
1082
1083     toPrevPage(): Promise<any> {
1084         if (this.pager.isFirstPage()) {
1085             return Promise.reject('on first');
1086         }
1087         // temp ignore pager events since we're calling requestPage manually.
1088         this.ignorePager();
1089         this.pager.decrement();
1090         this.listenToPager();
1091         return this.dataSource.requestPage(this.pager);
1092     }
1093
1094     toNextPage(): Promise<any> {
1095         if (this.pager.isLastPage()) {
1096             return Promise.reject('on last');
1097         }
1098         // temp ignore pager events since we're calling requestPage manually.
1099         this.ignorePager();
1100         this.pager.increment();
1101         this.listenToPager();
1102         return this.dataSource.requestPage(this.pager);
1103     }
1104
1105     getAllRows(): Promise<any> {
1106         const pager = new Pager();
1107         pager.offset = 0;
1108         pager.limit = MAX_ALL_ROW_COUNT;
1109         return this.dataSource.requestPage(pager);
1110     }
1111
1112     // Returns a key/value pair object of visible column data as text.
1113     getRowAsFlatText(row: any): any {
1114         const flatRow = {};
1115         this.columnSet.displayColumns().forEach(col => {
1116             flatRow[col.name] =
1117                 this.getColumnTextContent(row, col);
1118         });
1119         return flatRow;
1120     }
1121
1122     getAllRowsAsText(): Observable<any> {
1123         return Observable.create(observer => {
1124             this.getAllRows().then(ok => {
1125                 this.dataSource.data.forEach(row => {
1126                     observer.next(this.getRowAsFlatText(row));
1127                 });
1128                 observer.complete();
1129             });
1130         });
1131     }
1132
1133     removeFilters(): void {
1134         this.dataSource.filters = {};
1135         this.columnSet.displayColumns().forEach(col => { col.removeFilter(); });
1136         this.filterControls.forEach(ctl => ctl.reset());
1137         this.reload();
1138     }
1139     filtersSet(): boolean {
1140         return Object.keys(this.dataSource.filters).length > 0;
1141     }
1142
1143     gridToCsv(): Promise<string> {
1144
1145         let csvStr = '';
1146         const columns = this.columnSet.displayColumns();
1147
1148         // CSV header
1149         columns.forEach(col => {
1150             csvStr += this.valueToCsv(col.label),
1151             csvStr += ',';
1152         });
1153
1154         csvStr = csvStr.replace(/,$/, '\n');
1155
1156         return new Promise(resolve => {
1157             this.getAllRowsAsText().subscribe(
1158                 row => {
1159                     columns.forEach(col => {
1160                         csvStr += this.valueToCsv(row[col.name]);
1161                         csvStr += ',';
1162                     });
1163                     csvStr = csvStr.replace(/,$/, '\n');
1164                 },
1165                 err => {},
1166                 ()  => resolve(csvStr)
1167             );
1168         });
1169     }
1170
1171
1172     // prepares a string for inclusion within a CSV document
1173     // by escaping commas and quotes and removing newlines.
1174     valueToCsv(str: string): string {
1175         str = '' + str;
1176         if (!str) { return ''; }
1177         str = str.replace(/\n/g, '');
1178         if (str.match(/\,/) || str.match(/"/)) {
1179             str = str.replace(/"/g, '""');
1180             str = '"' + str + '"';
1181         }
1182         return str;
1183     }
1184
1185     generateColumns() {
1186         if (!this.columnSet.idlClass) { return; }
1187
1188         const pkeyField = this.idl.classes[this.columnSet.idlClass].pkey;
1189         const specifiedColumnOrder = this.autoGeneratedColumnOrder ?
1190             this.autoGeneratedColumnOrder.split(/,/) : [];
1191
1192         // generate columns for all non-virtual fields on the IDL class
1193         const fields = this.idl.classes[this.columnSet.idlClass].fields
1194             .filter(field => !field.virtual);
1195
1196         const sortedFields = this.autoGeneratedColumnOrder ?
1197             this.idl.sortIdlFields(fields, this.autoGeneratedColumnOrder.split(/,/)) :
1198             fields;
1199
1200         sortedFields.forEach(field => {
1201             if (!this.ignoredFields.filter(ignored => ignored === field.name).length) {
1202                 const col = new GridColumn();
1203                 col.name = field.name;
1204                 col.label = field.label || field.name;
1205                 col.idlFieldDef = field;
1206                 col.idlClass = this.columnSet.idlClass;
1207                 col.datatype = field.datatype;
1208                 col.isIndex = (field.name === pkeyField);
1209                 col.isAuto = true;
1210
1211                 if (this.showDeclaredFieldsOnly) {
1212                     col.hidden = true;
1213                 }
1214
1215                 this.columnSet.add(col);
1216             }
1217         });
1218     }
1219
1220     saveGridConfig(): Promise<any> {
1221         if (!this.persistKey) {
1222             throw new Error('Grid persistKey required to save columns');
1223         }
1224         const conf = new GridPersistConf();
1225         conf.version = 2;
1226         conf.limit = this.pager.limit;
1227         conf.columns = this.columnSet.compileSaveObject();
1228
1229         // Avoid persisting group visibility since that may change
1230         // with the addition of new columns.  Always calculate that
1231         // in real time.
1232         conf.hideToolbarActions = this.toolbarActions
1233             .filter(action => !action.isGroup && action.hidden)
1234             .map(action => action.label);
1235
1236         return this.store.setItem('eg.grid.' + this.persistKey, conf);
1237     }
1238
1239     // TODO: saveGridConfigAsOrgSetting(...)
1240
1241     getGridConfig(persistKey: string): Promise<GridPersistConf> {
1242         if (!persistKey) { return Promise.resolve(null); }
1243         return this.store.getItem('eg.grid.' + persistKey);
1244     }
1245
1246     columnHasTextGenerator(col: GridColumn): boolean {
1247         return this.cellTextGenerator && col.name in this.cellTextGenerator;
1248     }
1249 }
1250
1251
1252 // Actions apply to specific rows
1253 export class GridToolbarAction {
1254     label: string;
1255     onClick: EventEmitter<any []>;
1256     action: (rows: any[]) => any; // DEPRECATED
1257     group: string;
1258     disabled: boolean;
1259     isGroup: boolean; // used for group placeholder entries
1260     isSeparator: boolean;
1261     disableOnRows: (rows: any[]) => boolean;
1262     hidden?: boolean;
1263 }
1264
1265 // Buttons are global actions
1266 export class GridToolbarButton {
1267     label: string;
1268     onClick: EventEmitter<any []>;
1269     action: () => any; // DEPRECATED
1270     disabled: boolean;
1271     routerLink: string;
1272 }
1273
1274 export class GridToolbarCheckbox {
1275     label: string;
1276     isChecked: boolean;
1277     onChange: EventEmitter<boolean>;
1278 }
1279
1280 export interface GridColumnSort {
1281     name: string;
1282     dir: string;
1283 }
1284
1285 export class GridDataSource {
1286
1287     data: any[];
1288     sort: GridColumnSort[];
1289     filters: Object;
1290     allRowsRetrieved: boolean;
1291     requestingData: boolean;
1292     retrievalError: boolean;
1293     getRows: (pager: Pager, sort: GridColumnSort[]) => Observable<any>;
1294
1295     constructor() {
1296         this.sort = [];
1297         this.filters = {};
1298         this.reset();
1299     }
1300
1301     reset() {
1302         this.data = [];
1303         this.allRowsRetrieved = false;
1304     }
1305
1306     // called from the template -- no data fetching
1307     getPageOfRows(pager: Pager): any[] {
1308         if (this.data) {
1309             return this.data.slice(
1310                 pager.offset, pager.limit + pager.offset
1311             ).filter(row => row !== undefined);
1312         }
1313         return [];
1314     }
1315
1316     // called on initial component load and user action (e.g. paging, sorting).
1317     requestPage(pager: Pager): Promise<any> {
1318
1319         if (
1320             this.getPageOfRows(pager).length === pager.limit
1321             // already have all data
1322             || this.allRowsRetrieved
1323             // have no way to get more data.
1324             || !this.getRows
1325         ) {
1326             return Promise.resolve();
1327         }
1328
1329         // If we have to call out for data, set inFetch
1330         this.requestingData = true;
1331         this.retrievalError = false;
1332
1333         return new Promise((resolve, reject) => {
1334             let idx = pager.offset;
1335             return this.getRows(pager, this.sort).subscribe(
1336                 row => {
1337                     this.data[idx++] = row;
1338                     // not updating this.requestingData, as having
1339                     // retrieved one row doesn't mean we're done
1340                     this.retrievalError = false;
1341                 },
1342                 err => {
1343                     console.error(`grid getRows() error ${err}`);
1344                     this.requestingData = false;
1345                     this.retrievalError = true;
1346                     reject(err);
1347                 },
1348                 ()  => {
1349                     this.checkAllRetrieved(pager, idx);
1350                     this.requestingData = false;
1351                     this.retrievalError = false;
1352                     resolve(null);
1353                 }
1354             );
1355         });
1356     }
1357
1358     // See if the last getRows() call resulted in the final set of data.
1359     checkAllRetrieved(pager: Pager, idx: number) {
1360         if (this.allRowsRetrieved) { return; }
1361
1362         if (idx === 0 || idx < (pager.limit + pager.offset)) {
1363             // last query returned nothing or less than one page.
1364             // confirm we have all of the preceding pages.
1365             if (!this.data.includes(undefined)) {
1366                 this.allRowsRetrieved = true;
1367                 pager.resultCount = this.data.length;
1368             }
1369         }
1370     }
1371 }
1372