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