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