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