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