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