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