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