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