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