]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/eg2/src/app/share/grid/grid.ts
LP1911238 Angular grid shift-click 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} 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     // Select all rows between the previously selected row and
935     // the provided row, including the provided row.
936     // This is additive only -- rows are never de-selected.
937     selectRowRange(index: any) {
938
939         if (!this.lastSelectedIndex) {
940             this.selectOneRow(index);
941             return;
942         }
943
944         const next = this.getRowPosition(index);
945         const prev = this.getRowPosition(this.lastSelectedIndex);
946         const start = Math.min(prev, next);
947         const end = Math.max(prev, next);
948
949         for (let idx = start; idx <= end; idx++) {
950             const row = this.dataSource.data[idx];
951             if (row) {
952                 this.rowSelector.select(this.getRowIndex(row));
953             }
954         }
955
956         this.lastSelectedIndex = index;
957     }
958
959     // shift-down-arrow
960     // Select the next row in addition to any currently selected row.
961     // However, if the next row is already selected, assume the user
962     // has reversed direction and wants to de-select the last selected row.
963     selectMultiRowsNext() {
964         if (!this.lastSelectedIndex) { return; }
965         const pos = this.getRowPosition(this.lastSelectedIndex);
966         const selectedIndexes = this.rowSelector.selected();
967
968         const promise = // load the next page of data if needed
969             (pos === (this.pager.offset + this.pager.limit - 1)) ?
970             this.toNextPage() : Promise.resolve();
971
972         promise.then(
973             ok => {
974                 const row = this.dataSource.data[pos + 1];
975                 const newIndex = this.getRowIndex(row);
976                 if (selectedIndexes.filter(i => i === newIndex).length > 0) {
977                     // Next row is already selected.  User is reversing direction.
978                     this.rowSelector.deselect(this.lastSelectedIndex);
979                     this.lastSelectedIndex = newIndex;
980                 } else {
981                     this.selectMultipleRows(selectedIndexes.concat(newIndex));
982                 }
983             },
984             err => {}
985         );
986     }
987
988     getFirstRowInPage(): any {
989         return this.dataSource.data[this.pager.offset];
990     }
991
992     getLastRowInPage(): any {
993         return this.dataSource.data[this.pager.offset + this.pager.limit - 1];
994     }
995
996     selectFirstRow() {
997         this.selectOneRow(this.getRowIndex(this.getFirstRowInPage()));
998     }
999
1000     selectLastRow() {
1001         this.selectOneRow(this.getRowIndex(this.getLastRowInPage()));
1002     }
1003
1004     selectRowsInPage() {
1005         const rows = this.dataSource.getPageOfRows(this.pager);
1006         const indexes = rows.map(r => this.getRowIndex(r));
1007         this.rowSelector.select(indexes);
1008         this.selectRowsInPageEmitter.emit();
1009     }
1010
1011     toPrevPage(): Promise<any> {
1012         if (this.pager.isFirstPage()) {
1013             return Promise.reject('on first');
1014         }
1015         // temp ignore pager events since we're calling requestPage manually.
1016         this.ignorePager();
1017         this.pager.decrement();
1018         this.listenToPager();
1019         return this.dataSource.requestPage(this.pager);
1020     }
1021
1022     toNextPage(): Promise<any> {
1023         if (this.pager.isLastPage()) {
1024             return Promise.reject('on last');
1025         }
1026         // temp ignore pager events since we're calling requestPage manually.
1027         this.ignorePager();
1028         this.pager.increment();
1029         this.listenToPager();
1030         return this.dataSource.requestPage(this.pager);
1031     }
1032
1033     getAllRows(): Promise<any> {
1034         const pager = new Pager();
1035         pager.offset = 0;
1036         pager.limit = MAX_ALL_ROW_COUNT;
1037         return this.dataSource.requestPage(pager);
1038     }
1039
1040     // Returns a key/value pair object of visible column data as text.
1041     getRowAsFlatText(row: any): any {
1042         const flatRow = {};
1043         this.columnSet.displayColumns().forEach(col => {
1044             flatRow[col.name] =
1045                 this.getColumnTextContent(row, col);
1046         });
1047         return flatRow;
1048     }
1049
1050     getAllRowsAsText(): Observable<any> {
1051         return Observable.create(observer => {
1052             this.getAllRows().then(ok => {
1053                 this.dataSource.data.forEach(row => {
1054                     observer.next(this.getRowAsFlatText(row));
1055                 });
1056                 observer.complete();
1057             });
1058         });
1059     }
1060
1061     removeFilters(): void {
1062         this.dataSource.filters = {};
1063         this.columnSet.displayColumns().forEach(col => { col.removeFilter(); });
1064         this.filterControls.forEach(ctl => ctl.reset());
1065         this.reload();
1066     }
1067     filtersSet(): boolean {
1068         return Object.keys(this.dataSource.filters).length > 0;
1069     }
1070
1071     gridToCsv(): Promise<string> {
1072
1073         let csvStr = '';
1074         const columns = this.columnSet.displayColumns();
1075
1076         // CSV header
1077         columns.forEach(col => {
1078             csvStr += this.valueToCsv(col.label),
1079             csvStr += ',';
1080         });
1081
1082         csvStr = csvStr.replace(/,$/, '\n');
1083
1084         return new Promise(resolve => {
1085             this.getAllRowsAsText().subscribe(
1086                 row => {
1087                     columns.forEach(col => {
1088                         csvStr += this.valueToCsv(row[col.name]);
1089                         csvStr += ',';
1090                     });
1091                     csvStr = csvStr.replace(/,$/, '\n');
1092                 },
1093                 err => {},
1094                 ()  => resolve(csvStr)
1095             );
1096         });
1097     }
1098
1099
1100     // prepares a string for inclusion within a CSV document
1101     // by escaping commas and quotes and removing newlines.
1102     valueToCsv(str: string): string {
1103         str = '' + str;
1104         if (!str) { return ''; }
1105         str = str.replace(/\n/g, '');
1106         if (str.match(/\,/) || str.match(/"/)) {
1107             str = str.replace(/"/g, '""');
1108             str = '"' + str + '"';
1109         }
1110         return str;
1111     }
1112
1113     generateColumns() {
1114         if (!this.columnSet.idlClass) { return; }
1115
1116         const pkeyField = this.idl.classes[this.columnSet.idlClass].pkey;
1117         const specifiedColumnOrder = this.autoGeneratedColumnOrder ?
1118             this.autoGeneratedColumnOrder.split(/,/) : [];
1119
1120         // generate columns for all non-virtual fields on the IDL class
1121         const fields = this.idl.classes[this.columnSet.idlClass].fields
1122             .filter(field => !field.virtual);
1123
1124         const sortedFields = this.autoGeneratedColumnOrder ?
1125             this.idl.sortIdlFields(fields, this.autoGeneratedColumnOrder.split(/,/)) :
1126             fields;
1127
1128         sortedFields.forEach(field => {
1129             if (!this.ignoredFields.filter(ignored => ignored === field.name).length) {
1130                 const col = new GridColumn();
1131                 col.name = field.name;
1132                 col.label = field.label || field.name;
1133                 col.idlFieldDef = field;
1134                 col.idlClass = this.columnSet.idlClass;
1135                 col.datatype = field.datatype;
1136                 col.isIndex = (field.name === pkeyField);
1137                 col.isAuto = true;
1138
1139                 if (this.showDeclaredFieldsOnly) {
1140                     col.hidden = true;
1141                 }
1142
1143                 this.columnSet.add(col);
1144             }
1145         });
1146     }
1147
1148     saveGridConfig(): Promise<any> {
1149         if (!this.persistKey) {
1150             throw new Error('Grid persistKey required to save columns');
1151         }
1152         const conf = new GridPersistConf();
1153         conf.version = 2;
1154         conf.limit = this.pager.limit;
1155         conf.columns = this.columnSet.compileSaveObject();
1156
1157         return this.store.setItem('eg.grid.' + this.persistKey, conf);
1158     }
1159
1160     // TODO: saveGridConfigAsOrgSetting(...)
1161
1162     getGridConfig(persistKey: string): Promise<GridPersistConf> {
1163         if (!persistKey) { return Promise.resolve(null); }
1164         return this.store.getItem('eg.grid.' + persistKey);
1165     }
1166
1167     columnHasTextGenerator(col: GridColumn): boolean {
1168         return this.cellTextGenerator && col.name in this.cellTextGenerator;
1169     }
1170 }
1171
1172
1173 // Actions apply to specific rows
1174 export class GridToolbarAction {
1175     label: string;
1176     onClick: EventEmitter<any []>;
1177     action: (rows: any[]) => any; // DEPRECATED
1178     group: string;
1179     disabled: boolean;
1180     isGroup: boolean; // used for group placeholder entries
1181     isSeparator: boolean;
1182     disableOnRows: (rows: any[]) => boolean;
1183 }
1184
1185 // Buttons are global actions
1186 export class GridToolbarButton {
1187     label: string;
1188     onClick: EventEmitter<any []>;
1189     action: () => any; // DEPRECATED
1190     disabled: boolean;
1191 }
1192
1193 export class GridToolbarCheckbox {
1194     label: string;
1195     isChecked: boolean;
1196     onChange: EventEmitter<boolean>;
1197 }
1198
1199 export class GridDataSource {
1200
1201     data: any[];
1202     sort: any[];
1203     filters: Object;
1204     allRowsRetrieved: boolean;
1205     requestingData: boolean;
1206     retrievalError: boolean;
1207     getRows: (pager: Pager, sort: any[]) => Observable<any>;
1208
1209     constructor() {
1210         this.sort = [];
1211         this.filters = {};
1212         this.reset();
1213     }
1214
1215     reset() {
1216         this.data = [];
1217         this.allRowsRetrieved = false;
1218     }
1219
1220     // called from the template -- no data fetching
1221     getPageOfRows(pager: Pager): any[] {
1222         if (this.data) {
1223             return this.data.slice(
1224                 pager.offset, pager.limit + pager.offset
1225             ).filter(row => row !== undefined);
1226         }
1227         return [];
1228     }
1229
1230     // called on initial component load and user action (e.g. paging, sorting).
1231     requestPage(pager: Pager): Promise<any> {
1232
1233         if (
1234             this.getPageOfRows(pager).length === pager.limit
1235             // already have all data
1236             || this.allRowsRetrieved
1237             // have no way to get more data.
1238             || !this.getRows
1239         ) {
1240             return Promise.resolve();
1241         }
1242
1243         // If we have to call out for data, set inFetch
1244         this.requestingData = true;
1245         this.retrievalError = false;
1246
1247         return new Promise((resolve, reject) => {
1248             let idx = pager.offset;
1249             return this.getRows(pager, this.sort).subscribe(
1250                 row => {
1251                     this.data[idx++] = row;
1252                     // not updating this.requestingData, as having
1253                     // retrieved one row doesn't mean we're done
1254                     this.retrievalError = false;
1255                 },
1256                 err => {
1257                     console.error(`grid getRows() error ${err}`);
1258                     this.requestingData = false;
1259                     this.retrievalError = true;
1260                     reject(err);
1261                 },
1262                 ()  => {
1263                     this.checkAllRetrieved(pager, idx);
1264                     this.requestingData = false;
1265                     this.retrievalError = false;
1266                     resolve();
1267                 }
1268             );
1269         });
1270     }
1271
1272     // See if the last getRows() call resulted in the final set of data.
1273     checkAllRetrieved(pager: Pager, idx: number) {
1274         if (this.allRowsRetrieved) { return; }
1275
1276         if (idx === 0 || idx < (pager.limit + pager.offset)) {
1277             // last query returned nothing or less than one page.
1278             // confirm we have all of the preceding pages.
1279             if (!this.data.includes(undefined)) {
1280                 this.allRowsRetrieved = true;
1281                 pager.resultCount = this.data.length;
1282             }
1283         }
1284     }
1285 }
1286
1287