]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/eg2/src/app/share/grid/grid.ts
LP1904036 Grid wildcard column support
[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     insertBefore(source: GridColumn, target: GridColumn) {
404         let targetIdx = -1;
405         let sourceIdx = -1;
406         this.columns.forEach((col, idx) => {
407             if (col.name === target.name) { targetIdx = idx; }});
408
409         this.columns.forEach((col, idx) => {
410             if (col.name === source.name) { sourceIdx = idx; }});
411
412         if (sourceIdx >= 0) {
413             this.columns.splice(sourceIdx, 1);
414         }
415
416         this.columns.splice(targetIdx, 0, source);
417     }
418
419     // Move visible columns to the front of the list.
420     moveVisibleToFront() {
421         const newCols = this.displayColumns();
422         this.columns.forEach(col => {
423             if (!col.visible) { newCols.push(col); }});
424         this.columns = newCols;
425     }
426
427     moveColumn(col: GridColumn, diff: number) {
428         let srcIdx, targetIdx;
429
430         this.columns.forEach((c, i) => {
431           if (c.name === col.name) { srcIdx = i; }
432         });
433
434         targetIdx = srcIdx + diff;
435         if (targetIdx < 0) {
436             targetIdx = 0;
437         } else if (targetIdx >= this.columns.length) {
438             // Target index follows the last visible column.
439             let lastVisible = 0;
440             this.columns.forEach((c, idx) => {
441                 if (c.visible) { lastVisible = idx; }
442             });
443
444             // When moving a column (down) causes one or more
445             // visible columns to shuffle forward, our column
446             // moves into the slot of the last visible column.
447             // Otherwise, put it into the slot directly following
448             // the last visible column.
449             targetIdx = srcIdx <= lastVisible ? lastVisible : lastVisible + 1;
450         }
451
452         // Splice column out of old position, insert at new position.
453         this.columns.splice(srcIdx, 1);
454         this.columns.splice(targetIdx, 0, col);
455     }
456
457     compileSaveObject(): GridColumnPersistConf[] {
458         // only store information about visible columns.
459         // scrunch the data down to just the needed info.
460         return this.displayColumns().map(col => {
461             const c: GridColumnPersistConf = {name : col.name};
462             if (col.align !== 'left') { c.align = col.align; }
463             if (col.flex !== 2) { c.flex = Number(col.flex); }
464             if (Number(col.sort)) { c.sort = Number(col.sort); }
465             return c;
466         });
467     }
468
469     applyColumnSettings(conf: GridColumnPersistConf[]) {
470
471         if (!conf || conf.length === 0) {
472             // No configuration is available, but we have a list of
473             // fields to show or hide by default
474
475             if (this.defaultVisibleFields) {
476                 this.columns.forEach(col => {
477                     if (this.defaultVisibleFields.includes(col.name)) {
478                         col.visible = true;
479                     } else {
480                         col.visible = false;
481                     }
482                 });
483
484             } else if (this.defaultHiddenFields) {
485                 this.defaultHiddenFields.forEach(name => {
486                     const col = this.getColByName(name);
487                     if (col) {
488                         col.visible = false;
489                     }
490                 });
491             }
492
493             return;
494         }
495
496         const newCols = [];
497
498         conf.forEach(colConf => {
499             const col = this.getColByName(colConf.name);
500             if (!col) { return; } // no such column in this grid.
501
502             col.visible = true;
503             if (colConf.align) { col.align = colConf.align; }
504             if (colConf.flex)  { col.flex = Number(colConf.flex); }
505             if (colConf.sort)  { col.sort = Number(colConf.sort); }
506
507             // Add to new columns array, avoid dupes.
508             if (newCols.filter(c => c.name === col.name).length === 0) {
509                 newCols.push(col);
510             }
511         });
512
513         // columns which are not expressed within the saved
514         // configuration are marked as non-visible and
515         // appended to the end of the new list of columns.
516         this.columns.forEach(c => {
517             if (conf.filter(cf => cf.name === c.name).length === 0) {
518                 c.visible = false;
519                 newCols.push(c);
520             }
521         });
522
523         this.columns = newCols;
524     }
525 }
526
527 // Maps colunm names to functions which return plain text values for
528 // each mapped column on a given row.  This is primarily useful for
529 // generating print-friendly content for grid cells rendered via
530 // cellTemplate.
531 //
532 // USAGE NOTE: Since a cellTemplate can be passed arbitrary context
533 //             but a GridCellTextGenerator only gets the row object,
534 //             if it's important to include content that's not available
535 //             by default in the row object, you may want to stick
536 //             it in the row object as an additional attribute.
537 //
538 export interface GridCellTextGenerator {
539     [columnName: string]: (row: any) => string;
540 }
541
542 export class GridRowSelector {
543     indexes: {[string: string]: boolean};
544
545     // Track these so we can emit the selectionChange event
546     // only when the selection actually changes.
547     previousSelection: string[] = [];
548
549     // Emits the selected indexes on selection change
550     selectionChange: EventEmitter<string[]> = new EventEmitter<string[]>();
551
552     constructor() {
553         this.clear();
554     }
555
556     // Returns true if all of the requested indexes exist in the selector.
557     contains(index: string | string[]): boolean {
558         const indexes = [].concat(index);
559         for (let i = 0; i < indexes.length; i++) { // early exit
560             if (!this.indexes[indexes[i]]) {
561                 return false;
562             }
563         }
564         return true;
565     }
566
567     emitChange() {
568         const keys = this.selected();
569
570         if (keys.length === this.previousSelection.length &&
571             this.contains(this.previousSelection)) {
572             return; // No change has occurred
573         }
574
575         this.previousSelection = keys;
576         this.selectionChange.emit(keys);
577     }
578
579     select(index: string | string[]) {
580         const indexes = [].concat(index);
581         indexes.forEach(i => this.indexes[i] = true);
582         this.emitChange();
583     }
584
585     deselect(index: string | string[]) {
586         const indexes = [].concat(index);
587         indexes.forEach(i => delete this.indexes[i]);
588         this.emitChange();
589     }
590
591     toggle(index: string) {
592         if (this.indexes[index]) {
593             this.deselect(index);
594         } else {
595             this.select(index);
596         }
597     }
598
599     selected(): string[] {
600         return Object.keys(this.indexes);
601     }
602
603     isEmpty(): boolean {
604         return this.selected().length === 0;
605     }
606
607     clear() {
608         this.indexes = {};
609         this.emitChange();
610     }
611 }
612
613 export interface GridRowFlairEntry {
614     icon: string;   // name of material icon
615     title?: string;  // tooltip string
616 }
617
618 export class GridColumnPersistConf {
619     name: string;
620     flex?: number;
621     sort?: number;
622     align?: string;
623 }
624
625 export class GridPersistConf {
626     version: number;
627     limit: number;
628     columns: GridColumnPersistConf[];
629     hideToolbarActions: string[];
630 }
631
632 export class GridContext {
633
634     pager: Pager;
635     idlClass: string;
636     isSortable: boolean;
637     isFilterable: boolean;
638     stickyGridHeader: boolean;
639     isMultiSortable: boolean;
640     useLocalSort: boolean;
641     persistKey: string;
642     disableMultiSelect: boolean;
643     disableSelect: boolean;
644     dataSource: GridDataSource;
645     columnSet: GridColumnSet;
646     autoGeneratedColumnOrder: string;
647     rowSelector: GridRowSelector;
648     toolbarLabel: string;
649     toolbarButtons: GridToolbarButton[];
650     toolbarCheckboxes: GridToolbarCheckbox[];
651     toolbarActions: GridToolbarAction[];
652     lastSelectedIndex: any;
653     pageChanges: Subscription;
654     rowFlairIsEnabled: boolean;
655     rowFlairCallback: (row: any) => GridRowFlairEntry;
656     rowClassCallback: (row: any) => string;
657     cellClassCallback: (row: any, col: GridColumn) => string;
658     defaultVisibleFields: string[];
659     defaultHiddenFields: string[];
660     ignoredFields: string[];
661     overflowCells: boolean;
662     disablePaging: boolean;
663     showDeclaredFieldsOnly: boolean;
664     cellTextGenerator: GridCellTextGenerator;
665     reloadOnColumnChange: boolean;
666
667     // Allow calling code to know when the select-all-rows-in-page
668     // action has occurred.
669     selectRowsInPageEmitter: EventEmitter<void>;
670
671     filterControls: QueryList<GridFilterControlComponent>;
672
673     // Services injected by our grid component
674     idl: IdlService;
675     org: OrgService;
676     store: ServerStoreService;
677     format: FormatService;
678
679     constructor(
680         idl: IdlService,
681         org: OrgService,
682         store: ServerStoreService,
683         format: FormatService) {
684
685         this.idl = idl;
686         this.org = org;
687         this.store = store;
688         this.format = format;
689         this.pager = new Pager();
690         this.rowSelector = new GridRowSelector();
691         this.toolbarButtons = [];
692         this.toolbarCheckboxes = [];
693         this.toolbarActions = [];
694     }
695
696     init() {
697         this.selectRowsInPageEmitter = new EventEmitter<void>();
698         this.columnSet = new GridColumnSet(this.idl, this.idlClass);
699         this.columnSet.isSortable = this.isSortable === true;
700         this.columnSet.isFilterable = this.isFilterable === true;
701         this.columnSet.isMultiSortable = this.isMultiSortable === true;
702         this.columnSet.defaultHiddenFields = this.defaultHiddenFields;
703         this.columnSet.defaultVisibleFields = this.defaultVisibleFields;
704         if (!this.pager.limit) {
705             this.pager.limit = this.disablePaging ? MAX_ALL_ROW_COUNT : 10;
706         }
707         this.generateColumns();
708     }
709
710     // Load initial settings and data.
711     initData() {
712         this.applyGridConfig()
713         .then(ok => this.dataSource.requestPage(this.pager))
714         .then(ok => this.listenToPager());
715     }
716
717     destroy() {
718         this.ignorePager();
719     }
720
721     applyGridConfig(): Promise<void> {
722         return this.getGridConfig(this.persistKey)
723         .then(conf => {
724             let columns = [];
725             if (conf) {
726                 columns = conf.columns;
727                 if (conf.limit && !this.disablePaging) {
728                     this.pager.limit = conf.limit;
729                 }
730                 this.applyToolbarActionVisibility(conf.hideToolbarActions);
731             }
732
733             // This is called regardless of the presence of saved
734             // settings so defaults can be applied.
735             this.columnSet.applyColumnSettings(columns);
736         });
737     }
738
739     applyToolbarActionVisibility(hidden: string[]) {
740         if (!hidden || hidden.length === 0) { return; }
741
742         const groups = [];
743         this.toolbarActions.forEach(action => {
744             if (action.isGroup) {
745                 groups.push(action);
746             } else if (!action.isSeparator) {
747                 action.hidden = hidden.includes(action.label);
748             }
749         });
750
751         // If all actions in a group are hidden, hide the group as well.
752         // Note the group may be marked as hidden in the configuration,
753         // but the addition of new entries within a group should cause
754         // it to be visible again.
755         groups.forEach(group => {
756             const visible = this.toolbarActions
757                 .filter(action => action.group === group.label && !action.hidden);
758             group.hidden = visible.length === 0;
759         });
760     }
761
762     reload() {
763         // Give the UI time to settle before reloading grid data.
764         // This can help when data retrieval depends on a value
765         // getting modified by an angular digest cycle.
766         setTimeout(() => {
767             this.pager.reset();
768             this.dataSource.reset();
769             this.dataSource.requestPage(this.pager);
770         });
771     }
772
773     reloadWithoutPagerReset() {
774         setTimeout(() => {
775             this.dataSource.reset();
776             this.dataSource.requestPage(this.pager);
777         });
778     }
779
780     // Sort the existing data source instead of requesting sorted
781     // data from the client.  Reset pager to page 1.  As with reload(),
782     // give the client a chance to setting before redisplaying.
783     sortLocal() {
784         setTimeout(() => {
785             this.pager.reset();
786             this.sortLocalData();
787             this.dataSource.requestPage(this.pager);
788         });
789     }
790
791     // Subscribe or unsubscribe to page-change events from the pager.
792     listenToPager() {
793         if (this.pageChanges) { return; }
794         this.pageChanges = this.pager.onChange$.subscribe(
795             val => this.dataSource.requestPage(this.pager));
796     }
797
798     ignorePager() {
799         if (!this.pageChanges) { return; }
800         this.pageChanges.unsubscribe();
801         this.pageChanges = null;
802     }
803
804     // Sort data in the data source array
805     sortLocalData() {
806
807         const sortDefs = this.dataSource.sort.map(sort => {
808             const column = this.columnSet.getColByName(sort.name);
809
810             const def = {
811                 name: sort.name,
812                 dir: sort.dir,
813                 col: column
814             };
815
816             if (!def.col.comparator) {
817                 switch (def.col.datatype) {
818                     case 'id':
819                     case 'money':
820                     case 'int':
821                         def.col.comparator = (a, b) => {
822                             a = Number(a);
823                             b = Number(b);
824                             if (a < b) { return -1; }
825                             if (a > b) { return 1; }
826                             return 0;
827                         };
828                         break;
829                     default:
830                         def.col.comparator = (a, b) => {
831                             if (a < b) { return -1; }
832                             if (a > b) { return 1; }
833                             return 0;
834                         };
835                 }
836             }
837
838             return def;
839         });
840
841         this.dataSource.data.sort((rowA, rowB) => {
842
843             for (let idx = 0; idx < sortDefs.length; idx++) {
844                 const sortDef = sortDefs[idx];
845
846                 const valueA = this.getRowColumnValue(rowA, sortDef.col);
847                 const valueB = this.getRowColumnValue(rowB, sortDef.col);
848
849                 if (valueA === '' && valueB === '') { continue; }
850                 if (valueA === '' && valueB !== '') { return 1; }
851                 if (valueA !== '' && valueB === '') { return -1; }
852
853                 const diff = sortDef.col.comparator(valueA, valueB);
854                 if (diff === 0) { continue; }
855
856                 return sortDef.dir === 'DESC' ? -diff : diff;
857             }
858
859             return 0; // No differences found.
860         });
861     }
862
863     getRowIndex(row: any): any {
864         const col = this.columnSet.indexColumn;
865         if (!col) {
866             throw new Error('grid index column required');
867         }
868         return this.getRowColumnValue(row, col);
869     }
870
871     // Returns position in the data source array of the row with
872     // the provided index.
873     getRowPosition(index: any): number {
874         // for-loop for early exit
875         for (let idx = 0; idx < this.dataSource.data.length; idx++) {
876             const row = this.dataSource.data[idx];
877             if (row !== undefined && index === this.getRowIndex(row)) {
878                 return idx;
879             }
880         }
881     }
882
883     // Return the row with the provided index.
884     getRowByIndex(index: any): any {
885         for (let idx = 0; idx < this.dataSource.data.length; idx++) {
886             const row = this.dataSource.data[idx];
887             if (row !== undefined && index === this.getRowIndex(row)) {
888                 return row;
889             }
890         }
891     }
892
893     // Returns all selected rows, regardless of whether they are
894     // currently visible in the grid display.
895     // De-selects previously selected rows which are no longer
896     // present in the grid.
897     getSelectedRows(): any[] {
898         const selected = [];
899         const deleted = [];
900
901         this.rowSelector.selected().forEach(index => {
902             const row = this.getRowByIndex(index);
903             if (row) {
904                 selected.push(row);
905             } else {
906                 deleted.push(index);
907             }
908         });
909
910         this.rowSelector.deselect(deleted);
911         return selected;
912     }
913
914     rowIsSelected(row: any): boolean {
915         const index = this.getRowIndex(row);
916         return this.rowSelector.selected().filter(
917             idx => idx === index
918         ).length > 0;
919     }
920
921     getRowColumnBareValue(row: any, col: GridColumn): any {
922         if (col.name in row) {
923             return this.getObjectFieldValue(row, col.name);
924         } else if (col.path) {
925             return this.nestedItemFieldValue(row, col);
926         }
927     }
928
929     getRowColumnValue(row: any, col: GridColumn): any {
930         const val = this.getRowColumnBareValue(row, col);
931
932         if (col.datatype === 'bool') {
933             // Avoid string-ifying bools so we can use an <eg-bool/>
934             // in the grid template.
935             return val;
936         }
937
938         let interval;
939         const intField = col.dateOnlyIntervalField;
940         if (intField) {
941             const intCol =
942                 this.columnSet.columns.filter(c => c.path === intField)[0];
943             if (intCol) {
944                 interval = this.getRowColumnBareValue(row, intCol);
945             }
946         }
947
948         return this.format.transform({
949             value: val,
950             idlClass: col.idlClass,
951             idlField: col.idlFieldDef ? col.idlFieldDef.name : col.name,
952             datatype: col.datatype,
953             datePlusTime: Boolean(col.datePlusTime),
954             timezoneContextOrg: Number(col.timezoneContextOrg),
955             dateOnlyInterval: interval
956         });
957     }
958
959     getObjectFieldValue(obj: any, name: string): any {
960         if (typeof obj[name] === 'function') {
961             return obj[name]();
962         } else {
963             return obj[name];
964         }
965     }
966
967     nestedItemFieldValue(obj: any, col: GridColumn): string {
968
969         let idlField;
970         let idlClassDef;
971         const original = obj;
972         const steps = col.path.split('.');
973
974         for (let i = 0; i < steps.length; i++) {
975             const step = steps[i];
976
977             if (obj === null || obj === undefined || typeof obj !== 'object') {
978                 // We have run out of data to step through before
979                 // reaching the end of the path.  Conclude fleshing via
980                 // callback if provided then exit.
981                 if (col.flesher && obj !== undefined) {
982                     return col.flesher(obj, col, original);
983                 }
984                 return obj;
985             }
986
987             const class_ = obj.classname;
988             if (class_ && (idlClassDef = this.idl.classes[class_])) {
989                 idlField = idlClassDef.field_map[step];
990             }
991
992             obj = this.getObjectFieldValue(obj, step);
993         }
994
995         // We found a nested IDL object which may or may not have
996         // been configured as a top-level column.  Flesh the column
997         // metadata with our newly found IDL info.
998         if (idlField) {
999             if (!col.datatype) {
1000                 col.datatype = idlField.datatype;
1001             }
1002             if (!col.idlFieldDef) {
1003                 idlField = col.idlFieldDef;
1004             }
1005             if (!col.idlClass) {
1006                 col.idlClass = idlClassDef.name;
1007             }
1008             if (!col.label) {
1009                 col.label = idlField.label || idlField.name;
1010             }
1011         }
1012
1013         return obj;
1014     }
1015
1016
1017     getColumnTextContent(row: any, col: GridColumn): string {
1018         if (this.columnHasTextGenerator(col)) {
1019             const str = this.cellTextGenerator[col.name](row);
1020             return (str === null || str === undefined)  ? '' : str;
1021         } else {
1022             if (col.cellTemplate) {
1023                 return ''; // avoid 'undefined' values
1024             } else {
1025                 return this.getRowColumnValue(row, col);
1026             }
1027         }
1028     }
1029
1030     selectOneRow(index: any) {
1031         this.rowSelector.clear();
1032         this.rowSelector.select(index);
1033         this.lastSelectedIndex = index;
1034     }
1035
1036     selectMultipleRows(indexes: any[]) {
1037         this.rowSelector.clear();
1038         this.rowSelector.select(indexes);
1039         this.lastSelectedIndex = indexes[indexes.length - 1];
1040     }
1041
1042     // selects or deselects an item, without affecting the others.
1043     // returns true if the item is selected; false if de-selected.
1044     toggleSelectOneRow(index: any) {
1045         if (this.rowSelector.contains(index)) {
1046             this.rowSelector.deselect(index);
1047             return false;
1048         }
1049
1050         this.rowSelector.select(index);
1051         this.lastSelectedIndex = index;
1052         return true;
1053     }
1054
1055     selectRowByPos(pos: number) {
1056         const row = this.dataSource.data[pos];
1057         if (row) {
1058             this.selectOneRow(this.getRowIndex(row));
1059         }
1060     }
1061
1062     selectPreviousRow() {
1063         if (!this.lastSelectedIndex) { return; }
1064         const pos = this.getRowPosition(this.lastSelectedIndex);
1065         if (pos === this.pager.offset) {
1066             this.toPrevPage().then(ok => this.selectLastRow(), err => {});
1067         } else {
1068             this.selectRowByPos(pos - 1);
1069         }
1070     }
1071
1072     selectNextRow() {
1073         if (!this.lastSelectedIndex) { return; }
1074         const pos = this.getRowPosition(this.lastSelectedIndex);
1075         if (pos === (this.pager.offset + this.pager.limit - 1)) {
1076             this.toNextPage().then(ok => this.selectFirstRow(), err => {});
1077         } else {
1078             this.selectRowByPos(pos + 1);
1079         }
1080     }
1081
1082     // shift-up-arrow
1083     // Select the previous row in addition to any currently selected row.
1084     // However, if the previous row is already selected, assume the user
1085     // has reversed direction and now wants to de-select the last selected row.
1086     selectMultiRowsPrevious() {
1087         if (!this.lastSelectedIndex) { return; }
1088         const pos = this.getRowPosition(this.lastSelectedIndex);
1089         const selectedIndexes = this.rowSelector.selected();
1090
1091         const promise = // load the previous page of data if needed
1092             (pos === this.pager.offset) ? this.toPrevPage() : Promise.resolve();
1093
1094         promise.then(
1095             ok => {
1096                 const row = this.dataSource.data[pos - 1];
1097                 const newIndex = this.getRowIndex(row);
1098                 if (selectedIndexes.filter(i => i === newIndex).length > 0) {
1099                     // Prev row is already selected.  User is reversing direction.
1100                     this.rowSelector.deselect(this.lastSelectedIndex);
1101                     this.lastSelectedIndex = newIndex;
1102                 } else {
1103                     this.selectMultipleRows(selectedIndexes.concat(newIndex));
1104                 }
1105             },
1106             err => {}
1107         );
1108     }
1109
1110     // Select all rows between the previously selected row and
1111     // the provided row, including the provided row.
1112     // This is additive only -- rows are never de-selected.
1113     selectRowRange(index: any) {
1114
1115         if (!this.lastSelectedIndex) {
1116             this.selectOneRow(index);
1117             return;
1118         }
1119
1120         const next = this.getRowPosition(index);
1121         const prev = this.getRowPosition(this.lastSelectedIndex);
1122         const start = Math.min(prev, next);
1123         const end = Math.max(prev, next);
1124
1125         for (let idx = start; idx <= end; idx++) {
1126             const row = this.dataSource.data[idx];
1127             if (row) {
1128                 this.rowSelector.select(this.getRowIndex(row));
1129             }
1130         }
1131
1132         this.lastSelectedIndex = index;
1133     }
1134
1135     // shift-down-arrow
1136     // Select the next row in addition to any currently selected row.
1137     // However, if the next row is already selected, assume the user
1138     // has reversed direction and wants to de-select the last selected row.
1139     selectMultiRowsNext() {
1140         if (!this.lastSelectedIndex) { return; }
1141         const pos = this.getRowPosition(this.lastSelectedIndex);
1142         const selectedIndexes = this.rowSelector.selected();
1143
1144         const promise = // load the next page of data if needed
1145             (pos === (this.pager.offset + this.pager.limit - 1)) ?
1146             this.toNextPage() : Promise.resolve();
1147
1148         promise.then(
1149             ok => {
1150                 const row = this.dataSource.data[pos + 1];
1151                 const newIndex = this.getRowIndex(row);
1152                 if (selectedIndexes.filter(i => i === newIndex).length > 0) {
1153                     // Next row is already selected.  User is reversing direction.
1154                     this.rowSelector.deselect(this.lastSelectedIndex);
1155                     this.lastSelectedIndex = newIndex;
1156                 } else {
1157                     this.selectMultipleRows(selectedIndexes.concat(newIndex));
1158                 }
1159             },
1160             err => {}
1161         );
1162     }
1163
1164     getFirstRowInPage(): any {
1165         return this.dataSource.data[this.pager.offset];
1166     }
1167
1168     getLastRowInPage(): any {
1169         return this.dataSource.data[this.pager.offset + this.pager.limit - 1];
1170     }
1171
1172     selectFirstRow() {
1173         this.selectOneRow(this.getRowIndex(this.getFirstRowInPage()));
1174     }
1175
1176     selectLastRow() {
1177         this.selectOneRow(this.getRowIndex(this.getLastRowInPage()));
1178     }
1179
1180     selectRowsInPage() {
1181         const rows = this.dataSource.getPageOfRows(this.pager);
1182         const indexes = rows.map(r => this.getRowIndex(r));
1183         this.rowSelector.select(indexes);
1184         this.selectRowsInPageEmitter.emit();
1185     }
1186
1187     toPrevPage(): Promise<any> {
1188         if (this.pager.isFirstPage()) {
1189             return Promise.reject('on first');
1190         }
1191         // temp ignore pager events since we're calling requestPage manually.
1192         this.ignorePager();
1193         this.pager.decrement();
1194         this.listenToPager();
1195         return this.dataSource.requestPage(this.pager);
1196     }
1197
1198     toNextPage(): Promise<any> {
1199         if (this.pager.isLastPage()) {
1200             return Promise.reject('on last');
1201         }
1202         // temp ignore pager events since we're calling requestPage manually.
1203         this.ignorePager();
1204         this.pager.increment();
1205         this.listenToPager();
1206         return this.dataSource.requestPage(this.pager);
1207     }
1208
1209     getAllRows(): Promise<any> {
1210         const pager = new Pager();
1211         pager.offset = 0;
1212         pager.limit = MAX_ALL_ROW_COUNT;
1213         return this.dataSource.requestPage(pager);
1214     }
1215
1216     // Returns a key/value pair object of visible column data as text.
1217     getRowAsFlatText(row: any): any {
1218         const flatRow = {};
1219         this.columnSet.displayColumns().forEach(col => {
1220             flatRow[col.name] =
1221                 this.getColumnTextContent(row, col);
1222         });
1223         return flatRow;
1224     }
1225
1226     getAllRowsAsText(): Observable<any> {
1227         return Observable.create(observer => {
1228             this.getAllRows().then(ok => {
1229                 this.dataSource.data.forEach(row => {
1230                     observer.next(this.getRowAsFlatText(row));
1231                 });
1232                 observer.complete();
1233             });
1234         });
1235     }
1236
1237     removeFilters(): void {
1238         this.dataSource.filters = {};
1239         this.columnSet.displayColumns().forEach(col => { col.removeFilter(); });
1240         this.filterControls.forEach(ctl => ctl.reset());
1241         this.reload();
1242     }
1243     filtersSet(): boolean {
1244         return Object.keys(this.dataSource.filters).length > 0;
1245     }
1246
1247     gridToCsv(): Promise<string> {
1248
1249         let csvStr = '';
1250         const columns = this.columnSet.displayColumns();
1251
1252         // CSV header
1253         columns.forEach(col => {
1254             csvStr += this.valueToCsv(col.label),
1255             csvStr += ',';
1256         });
1257
1258         csvStr = csvStr.replace(/,$/, '\n');
1259
1260         return new Promise(resolve => {
1261             this.getAllRowsAsText().subscribe(
1262                 row => {
1263                     columns.forEach(col => {
1264                         csvStr += this.valueToCsv(row[col.name]);
1265                         csvStr += ',';
1266                     });
1267                     csvStr = csvStr.replace(/,$/, '\n');
1268                 },
1269                 err => {},
1270                 ()  => resolve(csvStr)
1271             );
1272         });
1273     }
1274
1275
1276     // prepares a string for inclusion within a CSV document
1277     // by escaping commas and quotes and removing newlines.
1278     valueToCsv(str: string): string {
1279         str = '' + str;
1280         if (!str) { return ''; }
1281         str = str.replace(/\n/g, '');
1282         if (str.match(/\,/) || str.match(/"/)) {
1283             str = str.replace(/"/g, '""');
1284             str = '"' + str + '"';
1285         }
1286         return str;
1287     }
1288
1289     generateColumns() {
1290         if (!this.columnSet.idlClass) { return; }
1291
1292         const pkeyField = this.idl.classes[this.columnSet.idlClass].pkey;
1293         const specifiedColumnOrder = this.autoGeneratedColumnOrder ?
1294             this.autoGeneratedColumnOrder.split(/,/) : [];
1295
1296         // generate columns for all non-virtual fields on the IDL class
1297         const fields = this.idl.classes[this.columnSet.idlClass].fields
1298             .filter(field => !field.virtual);
1299
1300         const sortedFields = this.autoGeneratedColumnOrder ?
1301             this.idl.sortIdlFields(fields, this.autoGeneratedColumnOrder.split(/,/)) :
1302             fields;
1303
1304         sortedFields.forEach(field => {
1305             if (!this.ignoredFields.filter(ignored => ignored === field.name).length) {
1306                 const col = new GridColumn();
1307                 col.name = field.name;
1308                 col.label = field.label || field.name;
1309                 col.idlFieldDef = field;
1310                 col.idlClass = this.columnSet.idlClass;
1311                 col.datatype = field.datatype;
1312                 col.isIndex = (field.name === pkeyField);
1313                 col.isAuto = true;
1314
1315                 if (this.showDeclaredFieldsOnly) {
1316                     col.hidden = true;
1317                 }
1318
1319                 this.columnSet.add(col);
1320             }
1321         });
1322     }
1323
1324     saveGridConfig(): Promise<any> {
1325         if (!this.persistKey) {
1326             throw new Error('Grid persistKey required to save columns');
1327         }
1328         const conf = new GridPersistConf();
1329         conf.version = 2;
1330         conf.limit = this.pager.limit;
1331         conf.columns = this.columnSet.compileSaveObject();
1332
1333         // Avoid persisting group visibility since that may change
1334         // with the addition of new columns.  Always calculate that
1335         // in real time.
1336         conf.hideToolbarActions = this.toolbarActions
1337             .filter(action => !action.isGroup && action.hidden)
1338             .map(action => action.label);
1339
1340         return this.store.setItem('eg.grid.' + this.persistKey, conf);
1341     }
1342
1343     // TODO: saveGridConfigAsOrgSetting(...)
1344
1345     getGridConfig(persistKey: string): Promise<GridPersistConf> {
1346         if (!persistKey) { return Promise.resolve(null); }
1347         return this.store.getItem('eg.grid.' + persistKey);
1348     }
1349
1350     columnHasTextGenerator(col: GridColumn): boolean {
1351         return this.cellTextGenerator && col.name in this.cellTextGenerator;
1352     }
1353 }
1354
1355
1356 // Actions apply to specific rows
1357 export class GridToolbarAction {
1358     label: string;
1359     onClick: EventEmitter<any []>;
1360     action: (rows: any[]) => any; // DEPRECATED
1361     group: string;
1362     disabled: boolean;
1363     isGroup: boolean; // used for group placeholder entries
1364     isSeparator: boolean;
1365     disableOnRows: (rows: any[]) => boolean;
1366     hidden?: boolean;
1367 }
1368
1369 // Buttons are global actions
1370 export class GridToolbarButton {
1371     label: string;
1372     onClick: EventEmitter<any []>;
1373     action: () => any; // DEPRECATED
1374     disabled: boolean;
1375     routerLink: string;
1376 }
1377
1378 export class GridToolbarCheckbox {
1379     label: string;
1380     isChecked: boolean;
1381     onChange: EventEmitter<boolean>;
1382 }
1383
1384 export interface GridColumnSort {
1385     name: string;
1386     dir: string;
1387 }
1388
1389 export class GridDataSource {
1390
1391     data: any[];
1392     sort: GridColumnSort[];
1393     filters: Object;
1394     allRowsRetrieved: boolean;
1395     requestingData: boolean;
1396     retrievalError: boolean;
1397     getRows: (pager: Pager, sort: GridColumnSort[]) => Observable<any>;
1398
1399     constructor() {
1400         this.sort = [];
1401         this.filters = {};
1402         this.reset();
1403     }
1404
1405     reset() {
1406         this.data = [];
1407         this.allRowsRetrieved = false;
1408     }
1409
1410     // called from the template -- no data fetching
1411     getPageOfRows(pager: Pager): any[] {
1412         if (this.data) {
1413             return this.data.slice(
1414                 pager.offset, pager.limit + pager.offset
1415             ).filter(row => row !== undefined);
1416         }
1417         return [];
1418     }
1419
1420     // called on initial component load and user action (e.g. paging, sorting).
1421     requestPage(pager: Pager): Promise<any> {
1422
1423         if (
1424             this.getPageOfRows(pager).length === pager.limit
1425             // already have all data
1426             || this.allRowsRetrieved
1427             // have no way to get more data.
1428             || !this.getRows
1429         ) {
1430             return Promise.resolve();
1431         }
1432
1433         // If we have to call out for data, set inFetch
1434         this.requestingData = true;
1435         this.retrievalError = false;
1436
1437         return new Promise((resolve, reject) => {
1438             let idx = pager.offset;
1439             return this.getRows(pager, this.sort).subscribe(
1440                 row => {
1441                     this.data[idx++] = row;
1442                     // not updating this.requestingData, as having
1443                     // retrieved one row doesn't mean we're done
1444                     this.retrievalError = false;
1445                 },
1446                 err => {
1447                     console.error(`grid getRows() error ${err}`);
1448                     this.requestingData = false;
1449                     this.retrievalError = true;
1450                     reject(err);
1451                 },
1452                 ()  => {
1453                     this.checkAllRetrieved(pager, idx);
1454                     this.requestingData = false;
1455                     this.retrievalError = false;
1456                     resolve(null);
1457                 }
1458             );
1459         });
1460     }
1461
1462     // See if the last getRows() call resulted in the final set of data.
1463     checkAllRetrieved(pager: Pager, idx: number) {
1464         if (this.allRowsRetrieved) { return; }
1465
1466         if (idx === 0 || idx < (pager.limit + pager.offset)) {
1467             // last query returned nothing or less than one page.
1468             // confirm we have all of the preceding pages.
1469             if (!this.data.includes(undefined)) {
1470                 this.allRowsRetrieved = true;
1471                 pager.resultCount = this.data.length;
1472             }
1473         }
1474     }
1475 }
1476