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