]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/eg2/src/app/share/grid/grid.ts
LP1904036 Grid auto columns label/etc fixes
[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, empty} 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     headerLabel: string;
20     flex: number;
21     align: string;
22     hidden: boolean;
23     visible: boolean;
24     sort: number;
25     // IDL class of the object which contains this field.
26     // Not to be confused with the class of a linked object.
27     idlClass: string;
28     idlFieldDef: any;
29     datatype: string;
30     datePlusTime: boolean;
31     ternaryBool: boolean;
32     timezoneContextOrg: number;
33     cellTemplate: TemplateRef<any>;
34     dateOnlyIntervalField: string;
35
36     cellContext: any;
37     isIndex: boolean;
38     isDragTarget: boolean;
39     isSortable: boolean;
40     isFilterable: boolean;
41     isFiltered: boolean;
42     isMultiSortable: boolean;
43     disableTooltip: boolean;
44     asyncSupportsEmptyTermClick: boolean;
45     comparator: (valueA: any, valueB: any) => number;
46     required = false;
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     clone(): GridColumn {
82         const col = new GridColumn();
83
84         col.name = this.name;
85         col.path = this.path;
86         col.label = this.label;
87         col.flex = this.flex;
88         col.required = this.required;
89         col.hidden = this.hidden;
90         col.asyncSupportsEmptyTermClick = this.asyncSupportsEmptyTermClick;
91         col.isIndex = this.isIndex;
92         col.cellTemplate = this.cellTemplate;
93         col.cellContext = this.cellContext;
94         col.disableTooltip = this.disableTooltip;
95         col.isSortable = this.isSortable;
96         col.isFilterable = this.isFilterable;
97         col.isMultiSortable = this.isMultiSortable;
98         col.datatype = this.datatype;
99         col.datePlusTime = this.datePlusTime;
100         col.ternaryBool = this.ternaryBool;
101         col.timezoneContextOrg = this.timezoneContextOrg;
102         col.idlClass = this.idlClass;
103         col.isAuto = this.isAuto;
104
105         return col;
106     }
107
108 }
109
110 export class GridColumnSet {
111     columns: GridColumn[];
112     idlClass: string;
113     indexColumn: GridColumn;
114     isSortable: boolean;
115     isFilterable: boolean;
116     isMultiSortable: boolean;
117     stockVisible: string[];
118     idl: IdlService;
119     defaultHiddenFields: string[];
120     defaultVisibleFields: string[];
121
122     constructor(idl: IdlService, idlClass?: string) {
123         this.idl = idl;
124         this.columns = [];
125         this.stockVisible = [];
126         this.idlClass = idlClass;
127     }
128
129     add(col: GridColumn) {
130
131         if (col.path && col.path.match(/\*$/)) {
132             return this.generateWildcardColumns(col);
133         }
134
135         this.applyColumnDefaults(col);
136
137         if (!this.insertColumn(col)) {
138             // Column was rejected as a duplicate.
139             return;
140         }
141
142         if (col.isIndex) { this.indexColumn = col; }
143
144         // track which fields are visible on page load.
145         if (col.visible) {
146             this.stockVisible.push(col.name);
147         }
148
149         this.applyColumnSortability(col);
150         this.applyColumnFilterability(col);
151     }
152
153     generateWildcardColumns(col: GridColumn) {
154
155         const dotpath = col.path.replace(/\.?\*$/, '');
156         let classObj, idlField;
157
158         if (col.idlClass) {
159             classObj = this.idl.classes[col.idlClass];
160         } else {
161             classObj = this.idl.classes[this.idlClass];
162         }
163
164         if (!classObj) { return; }
165
166         const pathParts = dotpath.split(/\./);
167         let oldField;
168
169         // find the IDL class definition for the last element in the
170         // path before the .*
171         // An empty pathParts means expand the root class
172         pathParts.forEach((part, pathIdx) => {
173             oldField = idlField;
174             idlField = classObj.field_map[part];
175
176             // unless we're at the end of the list, this field should
177             // link to another class.
178             if (idlField && idlField['class'] && (
179                 idlField.datatype === 'link' || idlField.datatype === 'org_unit')) {
180                 classObj = this.idl.classes[idlField['class']];
181
182             } else {
183                 if (pathIdx < (pathParts.length - 1)) {
184                     // we ran out of classes to hop through before
185                     // we ran out of path components
186                     console.warn('Grid: invalid IDL path: ' + dotpath);
187                 }
188             }
189         });
190
191         if (!classObj) {
192             console.warn(
193                 'Grid: wildcard path does not resolve to an object:' + dotpath);
194             return;
195         }
196
197         classObj.fields.forEach(field => {
198
199             // Only show wildcard fields where we have data to show
200             // Virtual and un-fleshed links will not have any data.
201             if (field.virtual ||
202                 field.datatype === 'link' || field.datatype === 'org_unit') {
203                 return;
204             }
205
206             const newCol = col.clone();
207             newCol.isAuto = true;
208             newCol.path = dotpath ? dotpath + '.' + field.name : field.name;
209             newCol.label = dotpath ? classObj.label + ': ' + field.label : field.label;
210             newCol.datatype = field.datatype;
211
212             // Avoid including the class label prefix in the main grid
213             // header display so it doesn't take up so much horizontal space.
214             newCol.headerLabel = field.label;
215
216             this.add(newCol);
217         });
218     }
219
220     // Returns true if the new column was inserted, false otherwise.
221     // Declared columns take precedence over auto-generated columns
222     // when collisions occur.
223     // Declared columns are inserted in front of auto columns.
224     insertColumn(col: GridColumn): boolean {
225
226         if (col.isAuto) {
227             if (this.getColByName(col.name) || this.getColByPath(col.path)) {
228                 // New auto-generated column conflicts with existing
229                 // column.  Skip it.
230                 return false;
231             } else {
232                 // No collisions.  Add to the end of the list
233                 this.columns.push(col);
234                 return true;
235             }
236         }
237
238         // Adding a declared column.
239
240         // Check for dupes.
241         for (let idx = 0; idx < this.columns.length; idx++) {
242             const testCol = this.columns[idx];
243             if (testCol.name === col.name) { // match found
244                 if (testCol.isAuto) {
245                     // new column takes precedence, remove the existing column.
246                     this.columns.splice(idx, 1);
247                     break;
248                 } else {
249                     // New column does not take precedence.  Avoid
250                     // inserting it.
251                     return false;
252                 }
253             }
254         }
255
256         // Delcared columns are inserted just before the first auto-column
257         for (let idx = 0; idx < this.columns.length; idx++) {
258             const testCol = this.columns[idx];
259             if (testCol.isAuto) {
260                 if (idx === 0) {
261                     this.columns.unshift(col);
262                 } else {
263                     this.columns.splice(idx, 0, col);
264                 }
265                 return true;
266             }
267         }
268
269         // No insertion point found.  Toss the new column on the end.
270         this.columns.push(col);
271         return true;
272     }
273
274     getColByName(name: string): GridColumn {
275         return this.columns.filter(c => c.name === name)[0];
276     }
277
278     getColByPath(path: string): GridColumn {
279         if (path) {
280             return this.columns.filter(c => c.path === path)[0];
281         }
282     }
283
284     idlInfoFromDotpath(dotpath: string): any {
285         if (!dotpath || !this.idlClass) { return null; }
286
287         let idlParent;
288         let idlField;
289         let idlClass;
290         let nextIdlClass = this.idl.classes[this.idlClass];
291
292         const pathParts = dotpath.split(/\./);
293
294         for (let i = 0; i < pathParts.length; i++) {
295
296             const part = pathParts[i];
297             idlParent = idlField;
298             idlClass = nextIdlClass;
299             idlField = idlClass.field_map[part];
300
301             if (!idlField) { return null; } // invalid IDL path
302
303             if (i === pathParts.length - 1) {
304                 // No more links to process.
305                 break;
306             }
307
308             if (idlField['class'] && (
309                 idlField.datatype === 'link' ||
310                 idlField.datatype === 'org_unit')) {
311                 // The link class on the current field refers to the
312                 // class of the link destination, not the current field.
313                 // Mark it for processing during the next iteration.
314                 nextIdlClass = this.idl.classes[idlField['class']];
315             }
316         }
317
318         return {
319             idlParent: idlParent,
320             idlField : idlField,
321             idlClass : idlClass
322         };
323     }
324
325
326     reset() {
327         this.columns.forEach(col => {
328             col.flex = 2;
329             col.sort = 0;
330             col.align = 'left';
331             col.visible = this.stockVisible.includes(col.name);
332         });
333     }
334
335     applyColumnDefaults(col: GridColumn) {
336
337         if (!col.idlFieldDef) {
338             const idlInfo = this.idlInfoFromDotpath(col.path || col.name);
339             if (idlInfo) {
340                 col.idlFieldDef = idlInfo.idlField;
341                 col.idlClass = idlInfo.idlClass.name;
342                 if (!col.datatype) {
343                     col.datatype = col.idlFieldDef.datatype;
344                 }
345                 if (!col.label) {
346                     col.label = col.idlFieldDef.label || col.idlFieldDef.name;
347                 }
348             }
349         }
350
351         if (!col.name) { col.name = col.path; }
352         if (!col.flex) { col.flex = 2; }
353         if (!col.align) { col.align = 'left'; }
354         if (!col.label) { col.label = col.name; }
355         if (!col.datatype) { col.datatype = 'text'; }
356         if (!col.isAuto) { col.headerLabel = col.label; }
357
358         col.visible = !col.hidden;
359     }
360
361     applyColumnSortability(col: GridColumn) {
362         // column sortability defaults to the sortability of the column set.
363         if (col.isSortable === undefined && this.isSortable) {
364             col.isSortable = true;
365         }
366
367         if (col.isMultiSortable === undefined && this.isMultiSortable) {
368             col.isMultiSortable = true;
369         }
370
371         if (col.isMultiSortable) {
372             col.isSortable = true;
373         }
374     }
375     applyColumnFilterability(col: GridColumn) {
376         // column filterability defaults to the afilterability of the column set.
377         if (col.isFilterable === undefined && this.isFilterable) {
378             col.isFilterable = true;
379         }
380     }
381
382     displayColumns(): GridColumn[] {
383         return this.columns.filter(c => c.visible);
384     }
385
386     // Sorted visible columns followed by sorted non-visible columns.
387     // Note we don't sort this.columns directly as it would impact
388     // grid column display ordering.
389     sortForColPicker(): GridColumn[] {
390         const visible = this.columns.filter(c => c.visible);
391         const invisible = this.columns.filter(c => !c.visible);
392
393         visible.sort((a, b) => a.label < b.label ? -1 : 1);
394         invisible.sort((a, b) => a.label < b.label ? -1 : 1);
395
396         return visible.concat(invisible);
397     }
398
399     requiredColumns(): GridColumn[] {
400         const visible = this.displayColumns();
401         return visible.concat(
402             this.columns.filter(c => c.required && !c.visible));
403     }
404
405     // Sorted visible columns followed by sorted non-visible columns.
406     // Note we don't sort this.columns directly as it would impact
407     // grid column display ordering.
408     sortForColPicker(): GridColumn[] {
409         const visible = this.columns.filter(c => c.visible);
410         const invisible = this.columns.filter(c => !c.visible);
411
412         visible.sort((a, b) => a.label < b.label ? -1 : 1);
413         invisible.sort((a, b) => a.label < b.label ? -1 : 1);
414
415         return visible.concat(invisible);
416     }
417
418     insertBefore(source: GridColumn, target: GridColumn) {
419         let targetIdx = -1;
420         let sourceIdx = -1;
421         this.columns.forEach((col, idx) => {
422             if (col.name === target.name) { targetIdx = idx; }});
423
424         this.columns.forEach((col, idx) => {
425             if (col.name === source.name) { sourceIdx = idx; }});
426
427         if (sourceIdx >= 0) {
428             this.columns.splice(sourceIdx, 1);
429         }
430
431         this.columns.splice(targetIdx, 0, source);
432     }
433
434     // Move visible columns to the front of the list.
435     moveVisibleToFront() {
436         const newCols = this.displayColumns();
437         this.columns.forEach(col => {
438             if (!col.visible) { newCols.push(col); }});
439         this.columns = newCols;
440     }
441
442     moveColumn(col: GridColumn, diff: number) {
443         let srcIdx, targetIdx;
444
445         this.columns.forEach((c, i) => {
446           if (c.name === col.name) { srcIdx = i; }
447         });
448
449         targetIdx = srcIdx + diff;
450         if (targetIdx < 0) {
451             targetIdx = 0;
452         } else if (targetIdx >= this.columns.length) {
453             // Target index follows the last visible column.
454             let lastVisible = 0;
455             this.columns.forEach((c, idx) => {
456                 if (c.visible) { lastVisible = idx; }
457             });
458
459             // When moving a column (down) causes one or more
460             // visible columns to shuffle forward, our column
461             // moves into the slot of the last visible column.
462             // Otherwise, put it into the slot directly following
463             // the last visible column.
464             targetIdx = srcIdx <= lastVisible ? lastVisible : lastVisible + 1;
465         }
466
467         // Splice column out of old position, insert at new position.
468         this.columns.splice(srcIdx, 1);
469         this.columns.splice(targetIdx, 0, col);
470     }
471
472     compileSaveObject(): GridColumnPersistConf[] {
473         // only store information about visible columns.
474         // scrunch the data down to just the needed info.
475         return this.displayColumns().map(col => {
476             const c: GridColumnPersistConf = {name : col.name};
477             if (col.align !== 'left') { c.align = col.align; }
478             if (col.flex !== 2) { c.flex = Number(col.flex); }
479             if (Number(col.sort)) { c.sort = Number(col.sort); }
480             return c;
481         });
482     }
483
484     applyColumnSettings(conf: GridColumnPersistConf[]) {
485
486         if (!conf || conf.length === 0) {
487             // No configuration is available, but we have a list of
488             // fields to show or hide by default
489
490             if (this.defaultVisibleFields) {
491                 this.columns.forEach(col => {
492                     if (this.defaultVisibleFields.includes(col.name)) {
493                         col.visible = true;
494                     } else {
495                         col.visible = false;
496                     }
497                 });
498
499             } else if (this.defaultHiddenFields) {
500                 this.defaultHiddenFields.forEach(name => {
501                     const col = this.getColByName(name);
502                     if (col) {
503                         col.visible = false;
504                     }
505                 });
506             }
507
508             return;
509         }
510
511         const newCols = [];
512
513         conf.forEach(colConf => {
514             const col = this.getColByName(colConf.name);
515             if (!col) { return; } // no such column in this grid.
516
517             col.visible = true;
518             if (colConf.align) { col.align = colConf.align; }
519             if (colConf.flex)  { col.flex = Number(colConf.flex); }
520             if (colConf.sort)  { col.sort = Number(colConf.sort); }
521
522             // Add to new columns array, avoid dupes.
523             if (newCols.filter(c => c.name === col.name).length === 0) {
524                 newCols.push(col);
525             }
526         });
527
528         // columns which are not expressed within the saved
529         // configuration are marked as non-visible and
530         // appended to the end of the new list of columns.
531         this.columns.forEach(c => {
532             if (conf.filter(cf => cf.name === c.name).length === 0) {
533                 c.visible = false;
534                 newCols.push(c);
535             }
536         });
537
538         this.columns = newCols;
539     }
540 }
541
542 // Maps colunm names to functions which return plain text values for
543 // each mapped column on a given row.  This is primarily useful for
544 // generating print-friendly content for grid cells rendered via
545 // cellTemplate.
546 //
547 // USAGE NOTE: Since a cellTemplate can be passed arbitrary context
548 //             but a GridCellTextGenerator only gets the row object,
549 //             if it's important to include content that's not available
550 //             by default in the row object, you may want to stick
551 //             it in the row object as an additional attribute.
552 //
553 export interface GridCellTextGenerator {
554     [columnName: string]: (row: any) => string;
555 }
556
557 export class GridRowSelector {
558     indexes: {[string: string]: boolean};
559
560     // Track these so we can emit the selectionChange event
561     // only when the selection actually changes.
562     previousSelection: string[] = [];
563
564     // Emits the selected indexes on selection change
565     selectionChange: EventEmitter<string[]> = new EventEmitter<string[]>();
566
567     constructor() {
568         this.clear();
569     }
570
571     // Returns true if all of the requested indexes exist in the selector.
572     contains(index: string | string[]): boolean {
573         const indexes = [].concat(index);
574         for (let i = 0; i < indexes.length; i++) { // early exit
575             if (!this.indexes[indexes[i]]) {
576                 return false;
577             }
578         }
579         return true;
580     }
581
582     emitChange() {
583         const keys = this.selected();
584
585         if (keys.length === this.previousSelection.length &&
586             this.contains(this.previousSelection)) {
587             return; // No change has occurred
588         }
589
590         this.previousSelection = keys;
591         this.selectionChange.emit(keys);
592     }
593
594     select(index: string | string[]) {
595         const indexes = [].concat(index);
596         indexes.forEach(i => this.indexes[i] = true);
597         this.emitChange();
598     }
599
600     deselect(index: string | string[]) {
601         const indexes = [].concat(index);
602         indexes.forEach(i => delete this.indexes[i]);
603         this.emitChange();
604     }
605
606     toggle(index: string) {
607         if (this.indexes[index]) {
608             this.deselect(index);
609         } else {
610             this.select(index);
611         }
612     }
613
614     selected(): string[] {
615         return Object.keys(this.indexes);
616     }
617
618     isEmpty(): boolean {
619         return this.selected().length === 0;
620     }
621
622     clear() {
623         this.indexes = {};
624         this.emitChange();
625     }
626 }
627
628 export interface GridRowFlairEntry {
629     icon: string;   // name of material icon
630     title?: string;  // tooltip string
631 }
632
633 export class GridColumnPersistConf {
634     name: string;
635     flex?: number;
636     sort?: number;
637     align?: string;
638 }
639
640 export class GridPersistConf {
641     version: number;
642     limit: number;
643     columns: GridColumnPersistConf[];
644     hideToolbarActions: string[];
645 }
646
647 export class GridContext {
648
649     pager: Pager;
650     idlClass: string;
651     isSortable: boolean;
652     isFilterable: boolean;
653     stickyGridHeader: boolean;
654     isMultiSortable: boolean;
655     useLocalSort: boolean;
656     persistKey: string;
657     disableMultiSelect: boolean;
658     disableSelect: boolean;
659     dataSource: GridDataSource;
660     columnSet: GridColumnSet;
661     autoGeneratedColumnOrder: string;
662     rowSelector: GridRowSelector;
663     toolbarLabel: string;
664     toolbarButtons: GridToolbarButton[];
665     toolbarCheckboxes: GridToolbarCheckbox[];
666     toolbarActions: GridToolbarAction[];
667     lastSelectedIndex: any;
668     pageChanges: Subscription;
669     rowFlairIsEnabled: boolean;
670     rowFlairCallback: (row: any) => GridRowFlairEntry;
671     rowClassCallback: (row: any) => string;
672     cellClassCallback: (row: any, col: GridColumn) => string;
673     defaultVisibleFields: string[];
674     defaultHiddenFields: string[];
675     ignoredFields: string[];
676     overflowCells: boolean;
677     disablePaging: boolean;
678     showDeclaredFieldsOnly: boolean;
679     cellTextGenerator: GridCellTextGenerator;
680     reloadOnColumnChange: boolean;
681
682     // Allow calling code to know when the select-all-rows-in-page
683     // action has occurred.
684     selectRowsInPageEmitter: EventEmitter<void>;
685
686     filterControls: QueryList<GridFilterControlComponent>;
687
688     // Services injected by our grid component
689     idl: IdlService;
690     org: OrgService;
691     store: ServerStoreService;
692     format: FormatService;
693
694     constructor(
695         idl: IdlService,
696         org: OrgService,
697         store: ServerStoreService,
698         format: FormatService) {
699
700         this.idl = idl;
701         this.org = org;
702         this.store = store;
703         this.format = format;
704         this.pager = new Pager();
705         this.rowSelector = new GridRowSelector();
706         this.toolbarButtons = [];
707         this.toolbarCheckboxes = [];
708         this.toolbarActions = [];
709     }
710
711     init() {
712         this.selectRowsInPageEmitter = new EventEmitter<void>();
713         this.columnSet = new GridColumnSet(this.idl, this.idlClass);
714         this.columnSet.isSortable = this.isSortable === true;
715         this.columnSet.isFilterable = this.isFilterable === true;
716         this.columnSet.isMultiSortable = this.isMultiSortable === true;
717         this.columnSet.defaultHiddenFields = this.defaultHiddenFields;
718         this.columnSet.defaultVisibleFields = this.defaultVisibleFields;
719         if (!this.pager.limit) {
720             this.pager.limit = this.disablePaging ? MAX_ALL_ROW_COUNT : 10;
721         }
722         this.generateColumns();
723     }
724
725     // Load initial settings and data.
726     initData() {
727         this.applyGridConfig()
728         .then(ok => this.dataSource.requestPage(this.pager))
729         .then(ok => this.listenToPager());
730     }
731
732     destroy() {
733         this.ignorePager();
734     }
735
736     applyGridConfig(): Promise<void> {
737         return this.getGridConfig(this.persistKey)
738         .then(conf => {
739             let columns = [];
740             if (conf) {
741                 columns = conf.columns;
742                 if (conf.limit && !this.disablePaging) {
743                     this.pager.limit = conf.limit;
744                 }
745                 this.applyToolbarActionVisibility(conf.hideToolbarActions);
746             }
747
748             // This is called regardless of the presence of saved
749             // settings so defaults can be applied.
750             this.columnSet.applyColumnSettings(columns);
751         });
752     }
753
754     applyToolbarActionVisibility(hidden: string[]) {
755         if (!hidden || hidden.length === 0) { return; }
756
757         const groups = [];
758         this.toolbarActions.forEach(action => {
759             if (action.isGroup) {
760                 groups.push(action);
761             } else if (!action.isSeparator) {
762                 action.hidden = hidden.includes(action.label);
763             }
764         });
765
766         // If all actions in a group are hidden, hide the group as well.
767         // Note the group may be marked as hidden in the configuration,
768         // but the addition of new entries within a group should cause
769         // it to be visible again.
770         groups.forEach(group => {
771             const visible = this.toolbarActions
772                 .filter(action => action.group === group.label && !action.hidden);
773             group.hidden = visible.length === 0;
774         });
775     }
776
777     reload() {
778         // Give the UI time to settle before reloading grid data.
779         // This can help when data retrieval depends on a value
780         // getting modified by an angular digest cycle.
781         setTimeout(() => {
782             this.pager.reset();
783             this.dataSource.reset();
784             this.dataSource.requestPage(this.pager);
785         });
786     }
787
788     reloadWithoutPagerReset() {
789         setTimeout(() => {
790             this.dataSource.reset();
791             this.dataSource.requestPage(this.pager);
792         });
793     }
794
795     // Sort the existing data source instead of requesting sorted
796     // data from the client.  Reset pager to page 1.  As with reload(),
797     // give the client a chance to setting before redisplaying.
798     sortLocal() {
799         setTimeout(() => {
800             this.pager.reset();
801             this.sortLocalData();
802             this.dataSource.requestPage(this.pager);
803         });
804     }
805
806     // Subscribe or unsubscribe to page-change events from the pager.
807     listenToPager() {
808         if (this.pageChanges) { return; }
809         this.pageChanges = this.pager.onChange$.subscribe(
810             val => this.dataSource.requestPage(this.pager));
811     }
812
813     ignorePager() {
814         if (!this.pageChanges) { return; }
815         this.pageChanges.unsubscribe();
816         this.pageChanges = null;
817     }
818
819     // Sort data in the data source array
820     sortLocalData() {
821
822         const sortDefs = this.dataSource.sort.map(sort => {
823             const column = this.columnSet.getColByName(sort.name);
824
825             const def = {
826                 name: sort.name,
827                 dir: sort.dir,
828                 col: column
829             };
830
831             if (!def.col.comparator) {
832                 switch (def.col.datatype) {
833                     case 'id':
834                     case 'money':
835                     case 'int':
836                         def.col.comparator = (a, b) => {
837                             a = Number(a);
838                             b = Number(b);
839                             if (a < b) { return -1; }
840                             if (a > b) { return 1; }
841                             return 0;
842                         };
843                         break;
844                     default:
845                         def.col.comparator = (a, b) => {
846                             if (a < b) { return -1; }
847                             if (a > b) { return 1; }
848                             return 0;
849                         };
850                 }
851             }
852
853             return def;
854         });
855
856         this.dataSource.data.sort((rowA, rowB) => {
857
858             for (let idx = 0; idx < sortDefs.length; idx++) {
859                 const sortDef = sortDefs[idx];
860
861                 const valueA = this.getRowColumnValue(rowA, sortDef.col);
862                 const valueB = this.getRowColumnValue(rowB, sortDef.col);
863
864                 if (valueA === '' && valueB === '') { continue; }
865                 if (valueA === '' && valueB !== '') { return 1; }
866                 if (valueA !== '' && valueB === '') { return -1; }
867
868                 const diff = sortDef.col.comparator(valueA, valueB);
869                 if (diff === 0) { continue; }
870
871                 return sortDef.dir === 'DESC' ? -diff : diff;
872             }
873
874             return 0; // No differences found.
875         });
876     }
877
878     getRowIndex(row: any): any {
879         const col = this.columnSet.indexColumn;
880         if (!col) {
881             throw new Error('grid index column required');
882         }
883         return this.getRowColumnValue(row, col);
884     }
885
886     // Returns position in the data source array of the row with
887     // the provided index.
888     getRowPosition(index: any): number {
889         // for-loop for early exit
890         for (let idx = 0; idx < this.dataSource.data.length; idx++) {
891             const row = this.dataSource.data[idx];
892             if (row !== undefined && index === this.getRowIndex(row)) {
893                 return idx;
894             }
895         }
896     }
897
898     // Return the row with the provided index.
899     getRowByIndex(index: any): any {
900         for (let idx = 0; idx < this.dataSource.data.length; idx++) {
901             const row = this.dataSource.data[idx];
902             if (row !== undefined && index === this.getRowIndex(row)) {
903                 return row;
904             }
905         }
906     }
907
908     // Returns all selected rows, regardless of whether they are
909     // currently visible in the grid display.
910     // De-selects previously selected rows which are no longer
911     // present in the grid.
912     getSelectedRows(): any[] {
913         const selected = [];
914         const deleted = [];
915
916         this.rowSelector.selected().forEach(index => {
917             const row = this.getRowByIndex(index);
918             if (row) {
919                 selected.push(row);
920             } else {
921                 deleted.push(index);
922             }
923         });
924
925         this.rowSelector.deselect(deleted);
926         return selected;
927     }
928
929     rowIsSelected(row: any): boolean {
930         const index = this.getRowIndex(row);
931         return this.rowSelector.selected().filter(
932             idx => idx === index
933         ).length > 0;
934     }
935
936     getRowColumnBareValue(row: any, col: GridColumn): any {
937         if (col.name in row) {
938             return this.getObjectFieldValue(row, col.name);
939         } else if (col.path) {
940             return this.nestedItemFieldValue(row, col);
941         }
942     }
943
944     getRowColumnValue(row: any, col: GridColumn): any {
945         const val = this.getRowColumnBareValue(row, col);
946
947         if (col.datatype === 'bool') {
948             // Avoid string-ifying bools so we can use an <eg-bool/>
949             // in the grid template.
950             return val;
951         }
952
953         let interval;
954         const intField = col.dateOnlyIntervalField;
955         if (intField) {
956             const intCol =
957                 this.columnSet.columns.filter(c => c.path === intField)[0];
958             if (intCol) {
959                 interval = this.getRowColumnBareValue(row, intCol);
960             }
961         }
962
963         return this.format.transform({
964             value: val,
965             idlClass: col.idlClass,
966             idlField: col.idlFieldDef ? col.idlFieldDef.name : col.name,
967             datatype: col.datatype,
968             datePlusTime: Boolean(col.datePlusTime),
969             timezoneContextOrg: Number(col.timezoneContextOrg),
970             dateOnlyInterval: interval
971         });
972     }
973
974     getObjectFieldValue(obj: any, name: string): any {
975         if (typeof obj[name] === 'function') {
976             return obj[name]();
977         } else {
978             return obj[name];
979         }
980     }
981
982     nestedItemFieldValue(obj: any, col: GridColumn): string {
983
984         let idlField;
985         let idlClassDef;
986         const original = obj;
987         const steps = col.path.split('.');
988
989         for (let i = 0; i < steps.length; i++) {
990             const step = steps[i];
991
992             if (obj === null || obj === undefined || typeof obj !== 'object') {
993                 // We have run out of data to step through before
994                 // reaching the end of the path.  Conclude fleshing via
995                 // callback if provided then exit.
996                 if (col.flesher && obj !== undefined) {
997                     return col.flesher(obj, col, original);
998                 }
999                 return obj;
1000             }
1001
1002             const class_ = obj.classname;
1003             if (class_ && (idlClassDef = this.idl.classes[class_])) {
1004                 idlField = idlClassDef.field_map[step];
1005             }
1006
1007             obj = this.getObjectFieldValue(obj, step);
1008         }
1009
1010         // We found a nested IDL object which may or may not have
1011         // been configured as a top-level column.  Flesh the column
1012         // metadata with our newly found IDL info.
1013         if (idlField) {
1014             if (!col.datatype) {
1015                 col.datatype = idlField.datatype;
1016             }
1017             if (!col.idlFieldDef) {
1018                 idlField = col.idlFieldDef;
1019             }
1020             if (!col.idlClass) {
1021                 col.idlClass = idlClassDef.name;
1022             }
1023             if (!col.label) {
1024                 col.label = idlField.label || idlField.name;
1025             }
1026         }
1027
1028         return obj;
1029     }
1030
1031
1032     getColumnTextContent(row: any, col: GridColumn): string {
1033         if (this.columnHasTextGenerator(col)) {
1034             const str = this.cellTextGenerator[col.name](row);
1035             return (str === null || str === undefined)  ? '' : str;
1036         } else {
1037             if (col.cellTemplate) {
1038                 return ''; // avoid 'undefined' values
1039             } else {
1040                 return this.getRowColumnValue(row, col);
1041             }
1042         }
1043     }
1044
1045     selectOneRow(index: any) {
1046         this.rowSelector.clear();
1047         this.rowSelector.select(index);
1048         this.lastSelectedIndex = index;
1049     }
1050
1051     selectMultipleRows(indexes: any[]) {
1052         this.rowSelector.clear();
1053         this.rowSelector.select(indexes);
1054         this.lastSelectedIndex = indexes[indexes.length - 1];
1055     }
1056
1057     // selects or deselects an item, without affecting the others.
1058     // returns true if the item is selected; false if de-selected.
1059     toggleSelectOneRow(index: any) {
1060         if (this.rowSelector.contains(index)) {
1061             this.rowSelector.deselect(index);
1062             return false;
1063         }
1064
1065         this.rowSelector.select(index);
1066         this.lastSelectedIndex = index;
1067         return true;
1068     }
1069
1070     selectRowByPos(pos: number) {
1071         const row = this.dataSource.data[pos];
1072         if (row) {
1073             this.selectOneRow(this.getRowIndex(row));
1074         }
1075     }
1076
1077     selectPreviousRow() {
1078         if (!this.lastSelectedIndex) { return; }
1079         const pos = this.getRowPosition(this.lastSelectedIndex);
1080         if (pos === this.pager.offset) {
1081             this.toPrevPage().then(ok => this.selectLastRow(), err => {});
1082         } else {
1083             this.selectRowByPos(pos - 1);
1084         }
1085     }
1086
1087     selectNextRow() {
1088         if (!this.lastSelectedIndex) { return; }
1089         const pos = this.getRowPosition(this.lastSelectedIndex);
1090         if (pos === (this.pager.offset + this.pager.limit - 1)) {
1091             this.toNextPage().then(ok => this.selectFirstRow(), err => {});
1092         } else {
1093             this.selectRowByPos(pos + 1);
1094         }
1095     }
1096
1097     // shift-up-arrow
1098     // Select the previous row in addition to any currently selected row.
1099     // However, if the previous row is already selected, assume the user
1100     // has reversed direction and now wants to de-select the last selected row.
1101     selectMultiRowsPrevious() {
1102         if (!this.lastSelectedIndex) { return; }
1103         const pos = this.getRowPosition(this.lastSelectedIndex);
1104         const selectedIndexes = this.rowSelector.selected();
1105
1106         const promise = // load the previous page of data if needed
1107             (pos === this.pager.offset) ? this.toPrevPage() : Promise.resolve();
1108
1109         promise.then(
1110             ok => {
1111                 const row = this.dataSource.data[pos - 1];
1112                 const newIndex = this.getRowIndex(row);
1113                 if (selectedIndexes.filter(i => i === newIndex).length > 0) {
1114                     // Prev row is already selected.  User is reversing direction.
1115                     this.rowSelector.deselect(this.lastSelectedIndex);
1116                     this.lastSelectedIndex = newIndex;
1117                 } else {
1118                     this.selectMultipleRows(selectedIndexes.concat(newIndex));
1119                 }
1120             },
1121             err => {}
1122         );
1123     }
1124
1125     // Select all rows between the previously selected row and
1126     // the provided row, including the provided row.
1127     // This is additive only -- rows are never de-selected.
1128     selectRowRange(index: any) {
1129
1130         if (!this.lastSelectedIndex) {
1131             this.selectOneRow(index);
1132             return;
1133         }
1134
1135         const next = this.getRowPosition(index);
1136         const prev = this.getRowPosition(this.lastSelectedIndex);
1137         const start = Math.min(prev, next);
1138         const end = Math.max(prev, next);
1139
1140         for (let idx = start; idx <= end; idx++) {
1141             const row = this.dataSource.data[idx];
1142             if (row) {
1143                 this.rowSelector.select(this.getRowIndex(row));
1144             }
1145         }
1146
1147         this.lastSelectedIndex = index;
1148     }
1149
1150     // shift-down-arrow
1151     // Select the next row in addition to any currently selected row.
1152     // However, if the next row is already selected, assume the user
1153     // has reversed direction and wants to de-select the last selected row.
1154     selectMultiRowsNext() {
1155         if (!this.lastSelectedIndex) { return; }
1156         const pos = this.getRowPosition(this.lastSelectedIndex);
1157         const selectedIndexes = this.rowSelector.selected();
1158
1159         const promise = // load the next page of data if needed
1160             (pos === (this.pager.offset + this.pager.limit - 1)) ?
1161             this.toNextPage() : Promise.resolve();
1162
1163         promise.then(
1164             ok => {
1165                 const row = this.dataSource.data[pos + 1];
1166                 const newIndex = this.getRowIndex(row);
1167                 if (selectedIndexes.filter(i => i === newIndex).length > 0) {
1168                     // Next row is already selected.  User is reversing direction.
1169                     this.rowSelector.deselect(this.lastSelectedIndex);
1170                     this.lastSelectedIndex = newIndex;
1171                 } else {
1172                     this.selectMultipleRows(selectedIndexes.concat(newIndex));
1173                 }
1174             },
1175             err => {}
1176         );
1177     }
1178
1179     getFirstRowInPage(): any {
1180         return this.dataSource.data[this.pager.offset];
1181     }
1182
1183     getLastRowInPage(): any {
1184         return this.dataSource.data[this.pager.offset + this.pager.limit - 1];
1185     }
1186
1187     selectFirstRow() {
1188         this.selectOneRow(this.getRowIndex(this.getFirstRowInPage()));
1189     }
1190
1191     selectLastRow() {
1192         this.selectOneRow(this.getRowIndex(this.getLastRowInPage()));
1193     }
1194
1195     selectRowsInPage() {
1196         const rows = this.dataSource.getPageOfRows(this.pager);
1197         const indexes = rows.map(r => this.getRowIndex(r));
1198         this.rowSelector.select(indexes);
1199         this.selectRowsInPageEmitter.emit();
1200     }
1201
1202     toPrevPage(): Promise<any> {
1203         if (this.pager.isFirstPage()) {
1204             return Promise.reject('on first');
1205         }
1206         // temp ignore pager events since we're calling requestPage manually.
1207         this.ignorePager();
1208         this.pager.decrement();
1209         this.listenToPager();
1210         return this.dataSource.requestPage(this.pager);
1211     }
1212
1213     toNextPage(): Promise<any> {
1214         if (this.pager.isLastPage()) {
1215             return Promise.reject('on last');
1216         }
1217         // temp ignore pager events since we're calling requestPage manually.
1218         this.ignorePager();
1219         this.pager.increment();
1220         this.listenToPager();
1221         return this.dataSource.requestPage(this.pager);
1222     }
1223
1224     getAllRows(): Promise<any> {
1225         const pager = new Pager();
1226         pager.offset = 0;
1227         pager.limit = MAX_ALL_ROW_COUNT;
1228         return this.dataSource.requestPage(pager);
1229     }
1230
1231     // Returns a key/value pair object of visible column data as text.
1232     getRowAsFlatText(row: any): any {
1233         const flatRow = {};
1234         this.columnSet.displayColumns().forEach(col => {
1235             flatRow[col.name] =
1236                 this.getColumnTextContent(row, col);
1237         });
1238         return flatRow;
1239     }
1240
1241     getAllRowsAsText(): Observable<any> {
1242         return Observable.create(observer => {
1243             this.getAllRows().then(ok => {
1244                 this.dataSource.data.forEach(row => {
1245                     observer.next(this.getRowAsFlatText(row));
1246                 });
1247                 observer.complete();
1248             });
1249         });
1250     }
1251
1252     removeFilters(): void {
1253         this.dataSource.filters = {};
1254         this.columnSet.displayColumns().forEach(col => { col.removeFilter(); });
1255         this.filterControls.forEach(ctl => ctl.reset());
1256         this.reload();
1257     }
1258     filtersSet(): boolean {
1259         return Object.keys(this.dataSource.filters).length > 0;
1260     }
1261
1262     gridToCsv(): Promise<string> {
1263
1264         let csvStr = '';
1265         const columns = this.columnSet.displayColumns();
1266
1267         // CSV header
1268         columns.forEach(col => {
1269             csvStr += this.valueToCsv(col.label),
1270             csvStr += ',';
1271         });
1272
1273         csvStr = csvStr.replace(/,$/, '\n');
1274
1275         return new Promise(resolve => {
1276             this.getAllRowsAsText().subscribe(
1277                 row => {
1278                     columns.forEach(col => {
1279                         csvStr += this.valueToCsv(row[col.name]);
1280                         csvStr += ',';
1281                     });
1282                     csvStr = csvStr.replace(/,$/, '\n');
1283                 },
1284                 err => {},
1285                 ()  => resolve(csvStr)
1286             );
1287         });
1288     }
1289
1290
1291     // prepares a string for inclusion within a CSV document
1292     // by escaping commas and quotes and removing newlines.
1293     valueToCsv(str: string): string {
1294         str = '' + str;
1295         if (!str) { return ''; }
1296         str = str.replace(/\n/g, '');
1297         if (str.match(/\,/) || str.match(/"/)) {
1298             str = str.replace(/"/g, '""');
1299             str = '"' + str + '"';
1300         }
1301         return str;
1302     }
1303
1304     generateColumns() {
1305         if (!this.columnSet.idlClass) { return; }
1306
1307         const pkeyField = this.idl.classes[this.columnSet.idlClass].pkey;
1308         const specifiedColumnOrder = this.autoGeneratedColumnOrder ?
1309             this.autoGeneratedColumnOrder.split(/,/) : [];
1310
1311         // generate columns for all non-virtual fields on the IDL class
1312         const fields = this.idl.classes[this.columnSet.idlClass].fields
1313             .filter(field => !field.virtual);
1314
1315         const sortedFields = this.autoGeneratedColumnOrder ?
1316             this.idl.sortIdlFields(fields, this.autoGeneratedColumnOrder.split(/,/)) :
1317             fields;
1318
1319         sortedFields.forEach(field => {
1320             if (!this.ignoredFields.filter(ignored => ignored === field.name).length) {
1321                 const col = new GridColumn();
1322                 col.name = field.name;
1323                 col.label = field.label || field.name;
1324                 col.idlFieldDef = field;
1325                 col.idlClass = this.columnSet.idlClass;
1326                 col.datatype = field.datatype;
1327                 col.isIndex = (field.name === pkeyField);
1328                 col.isAuto = true;
1329
1330                 if (this.showDeclaredFieldsOnly) {
1331                     col.hidden = true;
1332                 }
1333
1334                 this.columnSet.add(col);
1335             }
1336         });
1337     }
1338
1339     saveGridConfig(): Promise<any> {
1340         if (!this.persistKey) {
1341             throw new Error('Grid persistKey required to save columns');
1342         }
1343         const conf = new GridPersistConf();
1344         conf.version = 2;
1345         conf.limit = this.pager.limit;
1346         conf.columns = this.columnSet.compileSaveObject();
1347
1348         // Avoid persisting group visibility since that may change
1349         // with the addition of new columns.  Always calculate that
1350         // in real time.
1351         conf.hideToolbarActions = this.toolbarActions
1352             .filter(action => !action.isGroup && action.hidden)
1353             .map(action => action.label);
1354
1355         return this.store.setItem('eg.grid.' + this.persistKey, conf);
1356     }
1357
1358     // TODO: saveGridConfigAsOrgSetting(...)
1359
1360     getGridConfig(persistKey: string): Promise<GridPersistConf> {
1361         if (!persistKey) { return Promise.resolve(null); }
1362         return this.store.getItem('eg.grid.' + persistKey);
1363     }
1364
1365     columnHasTextGenerator(col: GridColumn): boolean {
1366         return this.cellTextGenerator && col.name in this.cellTextGenerator;
1367     }
1368 }
1369
1370
1371 // Actions apply to specific rows
1372 export class GridToolbarAction {
1373     label: string;
1374     onClick: EventEmitter<any []>;
1375     action: (rows: any[]) => any; // DEPRECATED
1376     group: string;
1377     disabled: boolean;
1378     isGroup: boolean; // used for group placeholder entries
1379     isSeparator: boolean;
1380     disableOnRows: (rows: any[]) => boolean;
1381     hidden?: boolean;
1382 }
1383
1384 // Buttons are global actions
1385 export class GridToolbarButton {
1386     label: string;
1387     onClick: EventEmitter<any []>;
1388     action: () => any; // DEPRECATED
1389     disabled: boolean;
1390     routerLink: string;
1391 }
1392
1393 export class GridToolbarCheckbox {
1394     label: string;
1395     isChecked: boolean;
1396     onChange: EventEmitter<boolean>;
1397 }
1398
1399 export interface GridColumnSort {
1400     name: string;
1401     dir: string;
1402 }
1403
1404 export class GridDataSource {
1405
1406     data: any[];
1407     sort: GridColumnSort[];
1408     filters: Object;
1409     allRowsRetrieved: boolean;
1410     requestingData: boolean;
1411     retrievalError: boolean;
1412     getRows: (pager: Pager, sort: GridColumnSort[]) => Observable<any>;
1413
1414     constructor() {
1415         this.sort = [];
1416         this.filters = {};
1417         this.reset();
1418     }
1419
1420     reset() {
1421         this.data = [];
1422         this.allRowsRetrieved = false;
1423     }
1424
1425     // called from the template -- no data fetching
1426     getPageOfRows(pager: Pager): any[] {
1427         if (this.data) {
1428             return this.data.slice(
1429                 pager.offset, pager.limit + pager.offset
1430             ).filter(row => row !== undefined);
1431         }
1432         return [];
1433     }
1434
1435     // called on initial component load and user action (e.g. paging, sorting).
1436     requestPage(pager: Pager): Promise<any> {
1437
1438         if (
1439             this.getPageOfRows(pager).length === pager.limit
1440             // already have all data
1441             || this.allRowsRetrieved
1442             // have no way to get more data.
1443             || !this.getRows
1444         ) {
1445             return Promise.resolve();
1446         }
1447
1448         // If we have to call out for data, set inFetch
1449         this.requestingData = true;
1450         this.retrievalError = false;
1451
1452         return new Promise((resolve, reject) => {
1453             let idx = pager.offset;
1454             return this.getRows(pager, this.sort).subscribe(
1455                 row => {
1456                     this.data[idx++] = row;
1457                     // not updating this.requestingData, as having
1458                     // retrieved one row doesn't mean we're done
1459                     this.retrievalError = false;
1460                 },
1461                 err => {
1462                     console.error(`grid getRows() error ${err}`);
1463                     this.requestingData = false;
1464                     this.retrievalError = true;
1465                     reject(err);
1466                 },
1467                 ()  => {
1468                     this.checkAllRetrieved(pager, idx);
1469                     this.requestingData = false;
1470                     this.retrievalError = false;
1471                     resolve(null);
1472                 }
1473             );
1474         });
1475     }
1476
1477     // See if the last getRows() call resulted in the final set of data.
1478     checkAllRetrieved(pager: Pager, idx: number) {
1479         if (this.allRowsRetrieved) { return; }
1480
1481         if (idx === 0 || idx < (pager.limit + pager.offset)) {
1482             // last query returned nothing or less than one page.
1483             // confirm we have all of the preceding pages.
1484             if (!this.data.includes(undefined)) {
1485                 this.allRowsRetrieved = true;
1486                 pager.resultCount = this.data.length;
1487             }
1488         }
1489     }
1490 }
1491