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