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