]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/eg2/src/app/share/grid/grid.ts
59baa63ef45493d2a8eb803ef0ce69abc832b21f
[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             return this.cellTextGenerator[col.name](row);
826         } else {
827             if (col.cellTemplate) {
828                 return ''; // avoid 'undefined' values
829             } else {
830                 return this.getRowColumnValue(row, col);
831             }
832         }
833     }
834
835     selectOneRow(index: any) {
836         this.rowSelector.clear();
837         this.rowSelector.select(index);
838         this.lastSelectedIndex = index;
839     }
840
841     selectMultipleRows(indexes: any[]) {
842         this.rowSelector.clear();
843         this.rowSelector.select(indexes);
844         this.lastSelectedIndex = indexes[indexes.length - 1];
845     }
846
847     // selects or deselects an item, without affecting the others.
848     // returns true if the item is selected; false if de-selected.
849     toggleSelectOneRow(index: any) {
850         if (this.rowSelector.contains(index)) {
851             this.rowSelector.deselect(index);
852             return false;
853         }
854
855         this.rowSelector.select(index);
856         this.lastSelectedIndex = index;
857         return true;
858     }
859
860     selectRowByPos(pos: number) {
861         const row = this.dataSource.data[pos];
862         if (row) {
863             this.selectOneRow(this.getRowIndex(row));
864         }
865     }
866
867     selectPreviousRow() {
868         if (!this.lastSelectedIndex) { return; }
869         const pos = this.getRowPosition(this.lastSelectedIndex);
870         if (pos === this.pager.offset) {
871             this.toPrevPage().then(ok => this.selectLastRow(), err => {});
872         } else {
873             this.selectRowByPos(pos - 1);
874         }
875     }
876
877     selectNextRow() {
878         if (!this.lastSelectedIndex) { return; }
879         const pos = this.getRowPosition(this.lastSelectedIndex);
880         if (pos === (this.pager.offset + this.pager.limit - 1)) {
881             this.toNextPage().then(ok => this.selectFirstRow(), err => {});
882         } else {
883             this.selectRowByPos(pos + 1);
884         }
885     }
886
887     // shift-up-arrow
888     // Select the previous row in addition to any currently selected row.
889     // However, if the previous row is already selected, assume the user
890     // has reversed direction and now wants to de-select the last selected row.
891     selectMultiRowsPrevious() {
892         if (!this.lastSelectedIndex) { return; }
893         const pos = this.getRowPosition(this.lastSelectedIndex);
894         const selectedIndexes = this.rowSelector.selected();
895
896         const promise = // load the previous page of data if needed
897             (pos === this.pager.offset) ? this.toPrevPage() : Promise.resolve();
898
899         promise.then(
900             ok => {
901                 const row = this.dataSource.data[pos - 1];
902                 const newIndex = this.getRowIndex(row);
903                 if (selectedIndexes.filter(i => i === newIndex).length > 0) {
904                     // Prev row is already selected.  User is reversing direction.
905                     this.rowSelector.deselect(this.lastSelectedIndex);
906                     this.lastSelectedIndex = newIndex;
907                 } else {
908                     this.selectMultipleRows(selectedIndexes.concat(newIndex));
909                 }
910             },
911             err => {}
912         );
913     }
914
915     // shift-down-arrow
916     // Select the next row in addition to any currently selected row.
917     // However, if the next row is already selected, assume the user
918     // has reversed direction and wants to de-select the last selected row.
919     selectMultiRowsNext() {
920         if (!this.lastSelectedIndex) { return; }
921         const pos = this.getRowPosition(this.lastSelectedIndex);
922         const selectedIndexes = this.rowSelector.selected();
923
924         const promise = // load the next page of data if needed
925             (pos === (this.pager.offset + this.pager.limit - 1)) ?
926             this.toNextPage() : Promise.resolve();
927
928         promise.then(
929             ok => {
930                 const row = this.dataSource.data[pos + 1];
931                 const newIndex = this.getRowIndex(row);
932                 if (selectedIndexes.filter(i => i === newIndex).length > 0) {
933                     // Next row is already selected.  User is reversing direction.
934                     this.rowSelector.deselect(this.lastSelectedIndex);
935                     this.lastSelectedIndex = newIndex;
936                 } else {
937                     this.selectMultipleRows(selectedIndexes.concat(newIndex));
938                 }
939             },
940             err => {}
941         );
942     }
943
944     getFirstRowInPage(): any {
945         return this.dataSource.data[this.pager.offset];
946     }
947
948     getLastRowInPage(): any {
949         return this.dataSource.data[this.pager.offset + this.pager.limit - 1];
950     }
951
952     selectFirstRow() {
953         this.selectOneRow(this.getRowIndex(this.getFirstRowInPage()));
954     }
955
956     selectLastRow() {
957         this.selectOneRow(this.getRowIndex(this.getLastRowInPage()));
958     }
959
960     selectRowsInPage() {
961         const rows = this.dataSource.getPageOfRows(this.pager);
962         const indexes = rows.map(r => this.getRowIndex(r));
963         this.rowSelector.select(indexes);
964         this.selectRowsInPageEmitter.emit();
965     }
966
967     toPrevPage(): Promise<any> {
968         if (this.pager.isFirstPage()) {
969             return Promise.reject('on first');
970         }
971         // temp ignore pager events since we're calling requestPage manually.
972         this.ignorePager();
973         this.pager.decrement();
974         this.listenToPager();
975         return this.dataSource.requestPage(this.pager);
976     }
977
978     toNextPage(): Promise<any> {
979         if (this.pager.isLastPage()) {
980             return Promise.reject('on last');
981         }
982         // temp ignore pager events since we're calling requestPage manually.
983         this.ignorePager();
984         this.pager.increment();
985         this.listenToPager();
986         return this.dataSource.requestPage(this.pager);
987     }
988
989     getAllRows(): Promise<any> {
990         const pager = new Pager();
991         pager.offset = 0;
992         pager.limit = MAX_ALL_ROW_COUNT;
993         return this.dataSource.requestPage(pager);
994     }
995
996     // Returns a key/value pair object of visible column data as text.
997     getRowAsFlatText(row: any): any {
998         const flatRow = {};
999         this.columnSet.displayColumns().forEach(col => {
1000             flatRow[col.name] =
1001                 this.getColumnTextContent(row, col);
1002         });
1003         return flatRow;
1004     }
1005
1006     getAllRowsAsText(): Observable<any> {
1007         return Observable.create(observer => {
1008             this.getAllRows().then(ok => {
1009                 this.dataSource.data.forEach(row => {
1010                     observer.next(this.getRowAsFlatText(row));
1011                 });
1012                 observer.complete();
1013             });
1014         });
1015     }
1016
1017     removeFilters(): void {
1018         this.dataSource.filters = {};
1019         this.columnSet.displayColumns().forEach(col => { col.removeFilter(); });
1020         this.filterControls.forEach(ctl => ctl.reset());
1021         this.reload();
1022     }
1023     filtersSet(): boolean {
1024         return Object.keys(this.dataSource.filters).length > 0;
1025     }
1026
1027     gridToCsv(): Promise<string> {
1028
1029         let csvStr = '';
1030         const columns = this.columnSet.displayColumns();
1031
1032         // CSV header
1033         columns.forEach(col => {
1034             csvStr += this.valueToCsv(col.label),
1035             csvStr += ',';
1036         });
1037
1038         csvStr = csvStr.replace(/,$/, '\n');
1039
1040         return new Promise(resolve => {
1041             this.getAllRowsAsText().subscribe(
1042                 row => {
1043                     columns.forEach(col => {
1044                         csvStr += this.valueToCsv(row[col.name]);
1045                         csvStr += ',';
1046                     });
1047                     csvStr = csvStr.replace(/,$/, '\n');
1048                 },
1049                 err => {},
1050                 ()  => resolve(csvStr)
1051             );
1052         });
1053     }
1054
1055
1056     // prepares a string for inclusion within a CSV document
1057     // by escaping commas and quotes and removing newlines.
1058     valueToCsv(str: string): string {
1059         str = '' + str;
1060         if (!str) { return ''; }
1061         str = str.replace(/\n/g, '');
1062         if (str.match(/\,/) || str.match(/"/)) {
1063             str = str.replace(/"/g, '""');
1064             str = '"' + str + '"';
1065         }
1066         return str;
1067     }
1068
1069     generateColumns() {
1070         if (!this.columnSet.idlClass) { return; }
1071
1072         const pkeyField = this.idl.classes[this.columnSet.idlClass].pkey;
1073
1074         // generate columns for all non-virtual fields on the IDL class
1075         this.idl.classes[this.columnSet.idlClass].fields
1076         .filter(field => !field.virtual)
1077         .forEach(field => {
1078             const col = new GridColumn();
1079             col.name = field.name;
1080             col.label = field.label || field.name;
1081             col.idlFieldDef = field;
1082             col.idlClass = this.columnSet.idlClass;
1083             col.datatype = field.datatype;
1084             col.isIndex = (field.name === pkeyField);
1085             col.isAuto = true;
1086
1087             if (this.showDeclaredFieldsOnly) {
1088                 col.hidden = true;
1089             }
1090
1091             this.columnSet.add(col);
1092         });
1093     }
1094
1095     saveGridConfig(): Promise<any> {
1096         if (!this.persistKey) {
1097             throw new Error('Grid persistKey required to save columns');
1098         }
1099         const conf = new GridPersistConf();
1100         conf.version = 2;
1101         conf.limit = this.pager.limit;
1102         conf.columns = this.columnSet.compileSaveObject();
1103
1104         return this.store.setItem('eg.grid.' + this.persistKey, conf);
1105     }
1106
1107     // TODO: saveGridConfigAsOrgSetting(...)
1108
1109     getGridConfig(persistKey: string): Promise<GridPersistConf> {
1110         if (!persistKey) { return Promise.resolve(null); }
1111         return this.store.getItem('eg.grid.' + persistKey);
1112     }
1113
1114     columnHasTextGenerator(col: GridColumn): boolean {
1115         return this.cellTextGenerator && col.name in this.cellTextGenerator;
1116     }
1117 }
1118
1119
1120 // Actions apply to specific rows
1121 export class GridToolbarAction {
1122     label: string;
1123     onClick: EventEmitter<any []>;
1124     action: (rows: any[]) => any; // DEPRECATED
1125     group: string;
1126     disabled: boolean;
1127     isGroup: boolean; // used for group placeholder entries
1128     isSeparator: boolean;
1129     disableOnRows: (rows: any[]) => boolean;
1130 }
1131
1132 // Buttons are global actions
1133 export class GridToolbarButton {
1134     label: string;
1135     onClick: EventEmitter<any []>;
1136     action: () => any; // DEPRECATED
1137     disabled: boolean;
1138 }
1139
1140 export class GridToolbarCheckbox {
1141     label: string;
1142     isChecked: boolean;
1143     onChange: EventEmitter<boolean>;
1144 }
1145
1146 export class GridDataSource {
1147
1148     data: any[];
1149     sort: any[];
1150     filters: Object;
1151     allRowsRetrieved: boolean;
1152     requestingData: boolean;
1153     getRows: (pager: Pager, sort: any[]) => Observable<any>;
1154
1155     constructor() {
1156         this.sort = [];
1157         this.filters = {};
1158         this.reset();
1159     }
1160
1161     reset() {
1162         this.data = [];
1163         this.allRowsRetrieved = false;
1164     }
1165
1166     // called from the template -- no data fetching
1167     getPageOfRows(pager: Pager): any[] {
1168         if (this.data) {
1169             return this.data.slice(
1170                 pager.offset, pager.limit + pager.offset
1171             ).filter(row => row !== undefined);
1172         }
1173         return [];
1174     }
1175
1176     // called on initial component load and user action (e.g. paging, sorting).
1177     requestPage(pager: Pager): Promise<any> {
1178
1179         if (
1180             this.getPageOfRows(pager).length === pager.limit
1181             // already have all data
1182             || this.allRowsRetrieved
1183             // have no way to get more data.
1184             || !this.getRows
1185         ) {
1186             return Promise.resolve();
1187         }
1188
1189         // If we have to call out for data, set inFetch
1190         this.requestingData = true;
1191
1192         return new Promise((resolve, reject) => {
1193             let idx = pager.offset;
1194             return this.getRows(pager, this.sort).subscribe(
1195                 row => {
1196                     this.data[idx++] = row;
1197                     this.requestingData = false;
1198                 },
1199                 err => {
1200                     console.error(`grid getRows() error ${err}`);
1201                     reject(err);
1202                 },
1203                 ()  => {
1204                     this.checkAllRetrieved(pager, idx);
1205                     this.requestingData = false;
1206                     resolve();
1207                 }
1208             );
1209         });
1210     }
1211
1212     // See if the last getRows() call resulted in the final set of data.
1213     checkAllRetrieved(pager: Pager, idx: number) {
1214         if (this.allRowsRetrieved) { return; }
1215
1216         if (idx === 0 || idx < (pager.limit + pager.offset)) {
1217             // last query returned nothing or less than one page.
1218             // confirm we have all of the preceding pages.
1219             if (!this.data.includes(undefined)) {
1220                 this.allRowsRetrieved = true;
1221                 pager.resultCount = this.data.length;
1222             }
1223         }
1224     }
1225 }
1226
1227