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