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