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