]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/eg2/src/app/share/grid/grid.ts
d40ac55eff5161926ca9896dcdb81a16b65fe165
[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     insertBefore(source: GridColumn, target: GridColumn) {
278         let targetIdx = -1;
279         let sourceIdx = -1;
280         this.columns.forEach((col, idx) => {
281             if (col.name === target.name) { targetIdx = idx; }});
282
283         this.columns.forEach((col, idx) => {
284             if (col.name === source.name) { sourceIdx = idx; }});
285
286         if (sourceIdx >= 0) {
287             this.columns.splice(sourceIdx, 1);
288         }
289
290         this.columns.splice(targetIdx, 0, source);
291     }
292
293     // Move visible columns to the front of the list.
294     moveVisibleToFront() {
295         const newCols = this.displayColumns();
296         this.columns.forEach(col => {
297             if (!col.visible) { newCols.push(col); }});
298         this.columns = newCols;
299     }
300
301     moveColumn(col: GridColumn, diff: number) {
302         let srcIdx, targetIdx;
303
304         this.columns.forEach((c, i) => {
305           if (c.name === col.name) { srcIdx = i; }
306         });
307
308         targetIdx = srcIdx + diff;
309         if (targetIdx < 0) {
310             targetIdx = 0;
311         } else if (targetIdx >= this.columns.length) {
312             // Target index follows the last visible column.
313             let lastVisible = 0;
314             this.columns.forEach((c, idx) => {
315                 if (c.visible) { lastVisible = idx; }
316             });
317
318             // When moving a column (down) causes one or more
319             // visible columns to shuffle forward, our column
320             // moves into the slot of the last visible column.
321             // Otherwise, put it into the slot directly following
322             // the last visible column.
323             targetIdx = srcIdx <= lastVisible ? lastVisible : lastVisible + 1;
324         }
325
326         // Splice column out of old position, insert at new position.
327         this.columns.splice(srcIdx, 1);
328         this.columns.splice(targetIdx, 0, col);
329     }
330
331     compileSaveObject(): GridColumnPersistConf[] {
332         // only store information about visible columns.
333         // scrunch the data down to just the needed info.
334         return this.displayColumns().map(col => {
335             const c: GridColumnPersistConf = {name : col.name};
336             if (col.align !== 'left') { c.align = col.align; }
337             if (col.flex !== 2) { c.flex = Number(col.flex); }
338             if (Number(col.sort)) { c.sort = Number(col.sort); }
339             return c;
340         });
341     }
342
343     applyColumnSettings(conf: GridColumnPersistConf[]) {
344
345         if (!conf || conf.length === 0) {
346             // No configuration is available, but we have a list of
347             // fields to show or hide by default
348
349             if (this.defaultVisibleFields) {
350                 this.columns.forEach(col => {
351                     if (this.defaultVisibleFields.includes(col.name)) {
352                         col.visible = true;
353                     } else {
354                         col.visible = false;
355                     }
356                 });
357
358             } else if (this.defaultHiddenFields) {
359                 this.defaultHiddenFields.forEach(name => {
360                     const col = this.getColByName(name);
361                     if (col) {
362                         col.visible = false;
363                     }
364                 });
365             }
366
367             return;
368         }
369
370         const newCols = [];
371
372         conf.forEach(colConf => {
373             const col = this.getColByName(colConf.name);
374             if (!col) { return; } // no such column in this grid.
375
376             col.visible = true;
377             if (colConf.align) { col.align = colConf.align; }
378             if (colConf.flex)  { col.flex = Number(colConf.flex); }
379             if (colConf.sort)  { col.sort = Number(colConf.sort); }
380
381             // Add to new columns array, avoid dupes.
382             if (newCols.filter(c => c.name === col.name).length === 0) {
383                 newCols.push(col);
384             }
385         });
386
387         // columns which are not expressed within the saved
388         // configuration are marked as non-visible and
389         // appended to the end of the new list of columns.
390         this.columns.forEach(c => {
391             if (conf.filter(cf => cf.name === c.name).length === 0) {
392                 c.visible = false;
393                 newCols.push(c);
394             }
395         });
396
397         this.columns = newCols;
398     }
399 }
400
401 // Maps colunm names to functions which return plain text values for
402 // each mapped column on a given row.  This is primarily useful for
403 // generating print-friendly content for grid cells rendered via
404 // cellTemplate.
405 //
406 // USAGE NOTE: Since a cellTemplate can be passed arbitrary context
407 //             but a GridCellTextGenerator only gets the row object,
408 //             if it's important to include content that's not available
409 //             by default in the row object, you may want to stick
410 //             it in the row object as an additional attribute.
411 //
412 export interface GridCellTextGenerator {
413     [columnName: string]: (row: any) => string;
414 }
415
416 export class GridRowSelector {
417     indexes: {[string: string]: boolean};
418
419     constructor() {
420         this.clear();
421     }
422
423     // Returns true if all of the requested indexes exist in the selector.
424     contains(index: string | string[]): boolean {
425         const indexes = [].concat(index);
426         for (let i = 0; i < indexes.length; i++) { // early exit
427             if (!this.indexes[indexes[i]]) {
428                 return false;
429             }
430         }
431         return true;
432     }
433
434     select(index: string | string[]) {
435         const indexes = [].concat(index);
436         indexes.forEach(i => this.indexes[i] = true);
437     }
438
439     deselect(index: string | string[]) {
440         const indexes = [].concat(index);
441         indexes.forEach(i => delete this.indexes[i]);
442     }
443
444     // Returns the list of selected index values.
445     // In some contexts (template checkboxes) the value for an index is
446     // set to false to deselect instead of having it removed (via deselect()).
447     // NOTE GridRowSelector has no knowledge of when a row is no longer
448     // present in the grid.  Use GridContext.getSelectedRows() to get
449     // list of selected rows that are still present in the grid.
450     selected() {
451         return Object.keys(this.indexes).filter(
452             ind => Boolean(this.indexes[ind]));
453     }
454
455     isEmpty(): boolean {
456         return this.selected().length === 0;
457     }
458
459     clear() {
460         this.indexes = {};
461     }
462 }
463
464 export interface GridRowFlairEntry {
465     icon: string;   // name of material icon
466     title?: string;  // tooltip string
467 }
468
469 export class GridColumnPersistConf {
470     name: string;
471     flex?: number;
472     sort?: number;
473     align?: string;
474 }
475
476 export class GridPersistConf {
477     version: number;
478     limit: number;
479     columns: GridColumnPersistConf[];
480 }
481
482 export class GridContext {
483
484     pager: Pager;
485     idlClass: string;
486     isSortable: boolean;
487     isFilterable: boolean;
488     stickyGridHeader: boolean;
489     isMultiSortable: boolean;
490     useLocalSort: boolean;
491     persistKey: string;
492     disableMultiSelect: boolean;
493     disableSelect: boolean;
494     dataSource: GridDataSource;
495     columnSet: GridColumnSet;
496     rowSelector: GridRowSelector;
497     toolbarButtons: GridToolbarButton[];
498     toolbarCheckboxes: GridToolbarCheckbox[];
499     toolbarActions: GridToolbarAction[];
500     lastSelectedIndex: any;
501     pageChanges: Subscription;
502     rowFlairIsEnabled: boolean;
503     rowFlairCallback: (row: any) => GridRowFlairEntry;
504     rowClassCallback: (row: any) => string;
505     cellClassCallback: (row: any, col: GridColumn) => string;
506     defaultVisibleFields: string[];
507     defaultHiddenFields: string[];
508     ignoredFields: string[];
509     overflowCells: boolean;
510     disablePaging: boolean;
511     showDeclaredFieldsOnly: boolean;
512     cellTextGenerator: GridCellTextGenerator;
513
514     // Allow calling code to know when the select-all-rows-in-page
515     // action has occurred.
516     selectRowsInPageEmitter: EventEmitter<void>;
517
518     filterControls: QueryList<GridFilterControlComponent>;
519
520     // Services injected by our grid component
521     idl: IdlService;
522     org: OrgService;
523     store: ServerStoreService;
524     format: FormatService;
525
526     constructor(
527         idl: IdlService,
528         org: OrgService,
529         store: ServerStoreService,
530         format: FormatService) {
531
532         this.idl = idl;
533         this.org = org;
534         this.store = store;
535         this.format = format;
536         this.pager = new Pager();
537         this.rowSelector = new GridRowSelector();
538         this.toolbarButtons = [];
539         this.toolbarCheckboxes = [];
540         this.toolbarActions = [];
541     }
542
543     init() {
544         this.selectRowsInPageEmitter = new EventEmitter<void>();
545         this.columnSet = new GridColumnSet(this.idl, this.idlClass);
546         this.columnSet.isSortable = this.isSortable === true;
547         this.columnSet.isFilterable = this.isFilterable === true;
548         this.columnSet.isMultiSortable = this.isMultiSortable === true;
549         this.columnSet.defaultHiddenFields = this.defaultHiddenFields;
550         this.columnSet.defaultVisibleFields = this.defaultVisibleFields;
551         if (!this.pager.limit) {
552             this.pager.limit = this.disablePaging ? MAX_ALL_ROW_COUNT : 10;
553         }
554         this.generateColumns();
555     }
556
557     // Load initial settings and data.
558     initData() {
559         this.applyGridConfig()
560         .then(ok => this.dataSource.requestPage(this.pager))
561         .then(ok => this.listenToPager());
562     }
563
564     destroy() {
565         this.ignorePager();
566     }
567
568     applyGridConfig(): Promise<void> {
569         return this.getGridConfig(this.persistKey)
570         .then(conf => {
571             let columns = [];
572             if (conf) {
573                 columns = conf.columns;
574                 if (conf.limit && !this.disablePaging) {
575                     this.pager.limit = conf.limit;
576                 }
577             }
578
579             // This is called regardless of the presence of saved
580             // settings so defaults can be applied.
581             this.columnSet.applyColumnSettings(columns);
582         });
583     }
584
585     reload() {
586         // Give the UI time to settle before reloading grid data.
587         // This can help when data retrieval depends on a value
588         // getting modified by an angular digest cycle.
589         setTimeout(() => {
590             this.pager.reset();
591             this.dataSource.reset();
592             this.dataSource.requestPage(this.pager);
593         });
594     }
595
596     reloadWithoutPagerReset() {
597         setTimeout(() => {
598             this.dataSource.reset();
599             this.dataSource.requestPage(this.pager);
600         });
601     }
602
603     // Sort the existing data source instead of requesting sorted
604     // data from the client.  Reset pager to page 1.  As with reload(),
605     // give the client a chance to setting before redisplaying.
606     sortLocal() {
607         setTimeout(() => {
608             this.pager.reset();
609             this.sortLocalData();
610             this.dataSource.requestPage(this.pager);
611         });
612     }
613
614     // Subscribe or unsubscribe to page-change events from the pager.
615     listenToPager() {
616         if (this.pageChanges) { return; }
617         this.pageChanges = this.pager.onChange$.subscribe(
618             val => this.dataSource.requestPage(this.pager));
619     }
620
621     ignorePager() {
622         if (!this.pageChanges) { return; }
623         this.pageChanges.unsubscribe();
624         this.pageChanges = null;
625     }
626
627     // Sort data in the data source array
628     sortLocalData() {
629
630         const sortDefs = this.dataSource.sort.map(sort => {
631             const column = this.columnSet.getColByName(sort.name);
632
633             const def = {
634                 name: sort.name,
635                 dir: sort.dir,
636                 col: column
637             };
638
639             if (!def.col.comparator) {
640                 switch (def.col.datatype) {
641                     case 'id':
642                     case 'money':
643                     case 'int':
644                         def.col.comparator = (a, b) => {
645                             a = Number(a);
646                             b = Number(b);
647                             if (a < b) { return -1; }
648                             if (a > b) { return 1; }
649                             return 0;
650                         };
651                         break;
652                     default:
653                         def.col.comparator = (a, b) => {
654                             if (a < b) { return -1; }
655                             if (a > b) { return 1; }
656                             return 0;
657                         };
658                 }
659             }
660
661             return def;
662         });
663
664         this.dataSource.data.sort((rowA, rowB) => {
665
666             for (let idx = 0; idx < sortDefs.length; idx++) {
667                 const sortDef = sortDefs[idx];
668
669                 const valueA = this.getRowColumnValue(rowA, sortDef.col);
670                 const valueB = this.getRowColumnValue(rowB, sortDef.col);
671
672                 if (valueA === '' && valueB === '') { continue; }
673                 if (valueA === '' && valueB !== '') { return 1; }
674                 if (valueA !== '' && valueB === '') { return -1; }
675
676                 const diff = sortDef.col.comparator(valueA, valueB);
677                 if (diff === 0) { continue; }
678
679                 return sortDef.dir === 'DESC' ? -diff : diff;
680             }
681
682             return 0; // No differences found.
683         });
684     }
685
686     getRowIndex(row: any): any {
687         const col = this.columnSet.indexColumn;
688         if (!col) {
689             throw new Error('grid index column required');
690         }
691         return this.getRowColumnValue(row, col);
692     }
693
694     // Returns position in the data source array of the row with
695     // the provided index.
696     getRowPosition(index: any): number {
697         // for-loop for early exit
698         for (let idx = 0; idx < this.dataSource.data.length; idx++) {
699             const row = this.dataSource.data[idx];
700             if (row !== undefined && index === this.getRowIndex(row)) {
701                 return idx;
702             }
703         }
704     }
705
706     // Return the row with the provided index.
707     getRowByIndex(index: any): any {
708         for (let idx = 0; idx < this.dataSource.data.length; idx++) {
709             const row = this.dataSource.data[idx];
710             if (row !== undefined && index === this.getRowIndex(row)) {
711                 return row;
712             }
713         }
714     }
715
716     // Returns all selected rows, regardless of whether they are
717     // currently visible in the grid display.
718     // De-selects previously selected rows which are no longer
719     // present in the grid.
720     getSelectedRows(): any[] {
721         const selected = [];
722         const deleted = [];
723
724         this.rowSelector.selected().forEach(index => {
725             const row = this.getRowByIndex(index);
726             if (row) {
727                 selected.push(row);
728             } else {
729                 deleted.push(index);
730             }
731         });
732
733         this.rowSelector.deselect(deleted);
734         return selected;
735     }
736
737     rowIsSelected(row: any): boolean {
738         const index = this.getRowIndex(row);
739         return this.rowSelector.selected().filter(
740             idx => idx === index
741         ).length > 0;
742     }
743
744     getRowColumnValue(row: any, col: GridColumn): string {
745         let val;
746
747         if (col.path) {
748             val = this.nestedItemFieldValue(row, col);
749         } else if (col.name in row) {
750             val = this.getObjectFieldValue(row, col.name);
751         }
752
753         if (col.datatype === 'bool') {
754             // Avoid string-ifying bools so we can use an <eg-bool/>
755             // in the grid template.
756             return val;
757         }
758
759         return this.format.transform({
760             value: val,
761             idlClass: col.idlClass,
762             idlField: col.idlFieldDef ? col.idlFieldDef.name : col.name,
763             datatype: col.datatype,
764             datePlusTime: Boolean(col.datePlusTime),
765             timezoneContextOrg: Number(col.timezoneContextOrg)
766         });
767     }
768
769     getObjectFieldValue(obj: any, name: string): any {
770         if (typeof obj[name] === 'function') {
771             return obj[name]();
772         } else {
773             return obj[name];
774         }
775     }
776
777     nestedItemFieldValue(obj: any, col: GridColumn): string {
778
779         let idlField;
780         let idlClassDef;
781         const original = obj;
782         const steps = col.path.split('.');
783
784         for (let i = 0; i < steps.length; i++) {
785             const step = steps[i];
786
787             if (obj === null || obj === undefined || typeof obj !== 'object') {
788                 // We have run out of data to step through before
789                 // reaching the end of the path.  Conclude fleshing via
790                 // callback if provided then exit.
791                 if (col.flesher && obj !== undefined) {
792                     return col.flesher(obj, col, original);
793                 }
794                 return obj;
795             }
796
797             const class_ = obj.classname;
798             if (class_ && (idlClassDef = this.idl.classes[class_])) {
799                 idlField = idlClassDef.field_map[step];
800             }
801
802             obj = this.getObjectFieldValue(obj, step);
803         }
804
805         // We found a nested IDL object which may or may not have
806         // been configured as a top-level column.  Flesh the column
807         // metadata with our newly found IDL info.
808         if (idlField) {
809             if (!col.datatype) {
810                 col.datatype = idlField.datatype;
811             }
812             if (!col.idlFieldDef) {
813                 idlField = col.idlFieldDef;
814             }
815             if (!col.idlClass) {
816                 col.idlClass = idlClassDef.name;
817             }
818             if (!col.label) {
819                 col.label = idlField.label || idlField.name;
820             }
821         }
822
823         return obj;
824     }
825
826
827     getColumnTextContent(row: any, col: GridColumn): string {
828         if (this.columnHasTextGenerator(col)) {
829             const str = this.cellTextGenerator[col.name](row);
830             return (str === null || str === undefined)  ? '' : str;
831         } else {
832             if (col.cellTemplate) {
833                 return ''; // avoid 'undefined' values
834             } else {
835                 return this.getRowColumnValue(row, col);
836             }
837         }
838     }
839
840     selectOneRow(index: any) {
841         this.rowSelector.clear();
842         this.rowSelector.select(index);
843         this.lastSelectedIndex = index;
844     }
845
846     selectMultipleRows(indexes: any[]) {
847         this.rowSelector.clear();
848         this.rowSelector.select(indexes);
849         this.lastSelectedIndex = indexes[indexes.length - 1];
850     }
851
852     // selects or deselects an item, without affecting the others.
853     // returns true if the item is selected; false if de-selected.
854     toggleSelectOneRow(index: any) {
855         if (this.rowSelector.contains(index)) {
856             this.rowSelector.deselect(index);
857             return false;
858         }
859
860         this.rowSelector.select(index);
861         this.lastSelectedIndex = index;
862         return true;
863     }
864
865     selectRowByPos(pos: number) {
866         const row = this.dataSource.data[pos];
867         if (row) {
868             this.selectOneRow(this.getRowIndex(row));
869         }
870     }
871
872     selectPreviousRow() {
873         if (!this.lastSelectedIndex) { return; }
874         const pos = this.getRowPosition(this.lastSelectedIndex);
875         if (pos === this.pager.offset) {
876             this.toPrevPage().then(ok => this.selectLastRow(), err => {});
877         } else {
878             this.selectRowByPos(pos - 1);
879         }
880     }
881
882     selectNextRow() {
883         if (!this.lastSelectedIndex) { return; }
884         const pos = this.getRowPosition(this.lastSelectedIndex);
885         if (pos === (this.pager.offset + this.pager.limit - 1)) {
886             this.toNextPage().then(ok => this.selectFirstRow(), err => {});
887         } else {
888             this.selectRowByPos(pos + 1);
889         }
890     }
891
892     // shift-up-arrow
893     // Select the previous row in addition to any currently selected row.
894     // However, if the previous row is already selected, assume the user
895     // has reversed direction and now wants to de-select the last selected row.
896     selectMultiRowsPrevious() {
897         if (!this.lastSelectedIndex) { return; }
898         const pos = this.getRowPosition(this.lastSelectedIndex);
899         const selectedIndexes = this.rowSelector.selected();
900
901         const promise = // load the previous page of data if needed
902             (pos === this.pager.offset) ? this.toPrevPage() : Promise.resolve();
903
904         promise.then(
905             ok => {
906                 const row = this.dataSource.data[pos - 1];
907                 const newIndex = this.getRowIndex(row);
908                 if (selectedIndexes.filter(i => i === newIndex).length > 0) {
909                     // Prev row is already selected.  User is reversing direction.
910                     this.rowSelector.deselect(this.lastSelectedIndex);
911                     this.lastSelectedIndex = newIndex;
912                 } else {
913                     this.selectMultipleRows(selectedIndexes.concat(newIndex));
914                 }
915             },
916             err => {}
917         );
918     }
919
920     // shift-down-arrow
921     // Select the next row in addition to any currently selected row.
922     // However, if the next row is already selected, assume the user
923     // has reversed direction and wants to de-select the last selected row.
924     selectMultiRowsNext() {
925         if (!this.lastSelectedIndex) { return; }
926         const pos = this.getRowPosition(this.lastSelectedIndex);
927         const selectedIndexes = this.rowSelector.selected();
928
929         const promise = // load the next page of data if needed
930             (pos === (this.pager.offset + this.pager.limit - 1)) ?
931             this.toNextPage() : Promise.resolve();
932
933         promise.then(
934             ok => {
935                 const row = this.dataSource.data[pos + 1];
936                 const newIndex = this.getRowIndex(row);
937                 if (selectedIndexes.filter(i => i === newIndex).length > 0) {
938                     // Next row is already selected.  User is reversing direction.
939                     this.rowSelector.deselect(this.lastSelectedIndex);
940                     this.lastSelectedIndex = newIndex;
941                 } else {
942                     this.selectMultipleRows(selectedIndexes.concat(newIndex));
943                 }
944             },
945             err => {}
946         );
947     }
948
949     getFirstRowInPage(): any {
950         return this.dataSource.data[this.pager.offset];
951     }
952
953     getLastRowInPage(): any {
954         return this.dataSource.data[this.pager.offset + this.pager.limit - 1];
955     }
956
957     selectFirstRow() {
958         this.selectOneRow(this.getRowIndex(this.getFirstRowInPage()));
959     }
960
961     selectLastRow() {
962         this.selectOneRow(this.getRowIndex(this.getLastRowInPage()));
963     }
964
965     selectRowsInPage() {
966         const rows = this.dataSource.getPageOfRows(this.pager);
967         const indexes = rows.map(r => this.getRowIndex(r));
968         this.rowSelector.select(indexes);
969         this.selectRowsInPageEmitter.emit();
970     }
971
972     toPrevPage(): Promise<any> {
973         if (this.pager.isFirstPage()) {
974             return Promise.reject('on first');
975         }
976         // temp ignore pager events since we're calling requestPage manually.
977         this.ignorePager();
978         this.pager.decrement();
979         this.listenToPager();
980         return this.dataSource.requestPage(this.pager);
981     }
982
983     toNextPage(): Promise<any> {
984         if (this.pager.isLastPage()) {
985             return Promise.reject('on last');
986         }
987         // temp ignore pager events since we're calling requestPage manually.
988         this.ignorePager();
989         this.pager.increment();
990         this.listenToPager();
991         return this.dataSource.requestPage(this.pager);
992     }
993
994     getAllRows(): Promise<any> {
995         const pager = new Pager();
996         pager.offset = 0;
997         pager.limit = MAX_ALL_ROW_COUNT;
998         return this.dataSource.requestPage(pager);
999     }
1000
1001     // Returns a key/value pair object of visible column data as text.
1002     getRowAsFlatText(row: any): any {
1003         const flatRow = {};
1004         this.columnSet.displayColumns().forEach(col => {
1005             flatRow[col.name] =
1006                 this.getColumnTextContent(row, col);
1007         });
1008         return flatRow;
1009     }
1010
1011     getAllRowsAsText(): Observable<any> {
1012         return Observable.create(observer => {
1013             this.getAllRows().then(ok => {
1014                 this.dataSource.data.forEach(row => {
1015                     observer.next(this.getRowAsFlatText(row));
1016                 });
1017                 observer.complete();
1018             });
1019         });
1020     }
1021
1022     removeFilters(): void {
1023         this.dataSource.filters = {};
1024         this.columnSet.displayColumns().forEach(col => { col.removeFilter(); });
1025         this.filterControls.forEach(ctl => ctl.reset());
1026         this.reload();
1027     }
1028     filtersSet(): boolean {
1029         return Object.keys(this.dataSource.filters).length > 0;
1030     }
1031
1032     gridToCsv(): Promise<string> {
1033
1034         let csvStr = '';
1035         const columns = this.columnSet.displayColumns();
1036
1037         // CSV header
1038         columns.forEach(col => {
1039             csvStr += this.valueToCsv(col.label),
1040             csvStr += ',';
1041         });
1042
1043         csvStr = csvStr.replace(/,$/, '\n');
1044
1045         return new Promise(resolve => {
1046             this.getAllRowsAsText().subscribe(
1047                 row => {
1048                     columns.forEach(col => {
1049                         csvStr += this.valueToCsv(row[col.name]);
1050                         csvStr += ',';
1051                     });
1052                     csvStr = csvStr.replace(/,$/, '\n');
1053                 },
1054                 err => {},
1055                 ()  => resolve(csvStr)
1056             );
1057         });
1058     }
1059
1060
1061     // prepares a string for inclusion within a CSV document
1062     // by escaping commas and quotes and removing newlines.
1063     valueToCsv(str: string): string {
1064         str = '' + str;
1065         if (!str) { return ''; }
1066         str = str.replace(/\n/g, '');
1067         if (str.match(/\,/) || str.match(/"/)) {
1068             str = str.replace(/"/g, '""');
1069             str = '"' + str + '"';
1070         }
1071         return str;
1072     }
1073
1074     generateColumns() {
1075         if (!this.columnSet.idlClass) { return; }
1076
1077         const pkeyField = this.idl.classes[this.columnSet.idlClass].pkey;
1078
1079         // generate columns for all non-virtual fields on the IDL class
1080         this.idl.classes[this.columnSet.idlClass].fields
1081         .filter(field => !field.virtual)
1082         .forEach(field => {
1083             if (!this.ignoredFields.filter(ignored => ignored === field.name).length) {
1084                 const col = new GridColumn();
1085                 col.name = field.name;
1086                 col.label = field.label || field.name;
1087                 col.idlFieldDef = field;
1088                 col.idlClass = this.columnSet.idlClass;
1089                 col.datatype = field.datatype;
1090                 col.isIndex = (field.name === pkeyField);
1091                 col.isAuto = true;
1092
1093                 if (this.showDeclaredFieldsOnly) {
1094                     col.hidden = true;
1095                 }
1096
1097                 this.columnSet.add(col);
1098             }
1099         });
1100     }
1101
1102     saveGridConfig(): Promise<any> {
1103         if (!this.persistKey) {
1104             throw new Error('Grid persistKey required to save columns');
1105         }
1106         const conf = new GridPersistConf();
1107         conf.version = 2;
1108         conf.limit = this.pager.limit;
1109         conf.columns = this.columnSet.compileSaveObject();
1110
1111         return this.store.setItem('eg.grid.' + this.persistKey, conf);
1112     }
1113
1114     // TODO: saveGridConfigAsOrgSetting(...)
1115
1116     getGridConfig(persistKey: string): Promise<GridPersistConf> {
1117         if (!persistKey) { return Promise.resolve(null); }
1118         return this.store.getItem('eg.grid.' + persistKey);
1119     }
1120
1121     columnHasTextGenerator(col: GridColumn): boolean {
1122         return this.cellTextGenerator && col.name in this.cellTextGenerator;
1123     }
1124 }
1125
1126
1127 // Actions apply to specific rows
1128 export class GridToolbarAction {
1129     label: string;
1130     onClick: EventEmitter<any []>;
1131     action: (rows: any[]) => any; // DEPRECATED
1132     group: string;
1133     disabled: boolean;
1134     isGroup: boolean; // used for group placeholder entries
1135     isSeparator: boolean;
1136     disableOnRows: (rows: any[]) => boolean;
1137 }
1138
1139 // Buttons are global actions
1140 export class GridToolbarButton {
1141     label: string;
1142     onClick: EventEmitter<any []>;
1143     action: () => any; // DEPRECATED
1144     disabled: boolean;
1145 }
1146
1147 export class GridToolbarCheckbox {
1148     label: string;
1149     isChecked: boolean;
1150     onChange: EventEmitter<boolean>;
1151 }
1152
1153 export class GridDataSource {
1154
1155     data: any[];
1156     sort: any[];
1157     filters: Object;
1158     allRowsRetrieved: boolean;
1159     requestingData: boolean;
1160     retrievalError: boolean;
1161     getRows: (pager: Pager, sort: any[]) => Observable<any>;
1162
1163     constructor() {
1164         this.sort = [];
1165         this.filters = {};
1166         this.reset();
1167     }
1168
1169     reset() {
1170         this.data = [];
1171         this.allRowsRetrieved = false;
1172     }
1173
1174     // called from the template -- no data fetching
1175     getPageOfRows(pager: Pager): any[] {
1176         if (this.data) {
1177             return this.data.slice(
1178                 pager.offset, pager.limit + pager.offset
1179             ).filter(row => row !== undefined);
1180         }
1181         return [];
1182     }
1183
1184     // called on initial component load and user action (e.g. paging, sorting).
1185     requestPage(pager: Pager): Promise<any> {
1186
1187         if (
1188             this.getPageOfRows(pager).length === pager.limit
1189             // already have all data
1190             || this.allRowsRetrieved
1191             // have no way to get more data.
1192             || !this.getRows
1193         ) {
1194             return Promise.resolve();
1195         }
1196
1197         // If we have to call out for data, set inFetch
1198         this.requestingData = true;
1199         this.retrievalError = false;
1200
1201         return new Promise((resolve, reject) => {
1202             let idx = pager.offset;
1203             return this.getRows(pager, this.sort).subscribe(
1204                 row => {
1205                     this.data[idx++] = row;
1206                     this.requestingData = false;
1207                     this.retrievalError = false;
1208                 },
1209                 err => {
1210                     console.error(`grid getRows() error ${err}`);
1211                     this.requestingData = false;
1212                     this.retrievalError = true;
1213                     reject(err);
1214                 },
1215                 ()  => {
1216                     this.checkAllRetrieved(pager, idx);
1217                     this.requestingData = false;
1218                     this.retrievalError = false;
1219                     resolve();
1220                 }
1221             );
1222         });
1223     }
1224
1225     // See if the last getRows() call resulted in the final set of data.
1226     checkAllRetrieved(pager: Pager, idx: number) {
1227         if (this.allRowsRetrieved) { return; }
1228
1229         if (idx === 0 || idx < (pager.limit + pager.offset)) {
1230             // last query returned nothing or less than one page.
1231             // confirm we have all of the preceding pages.
1232             if (!this.data.includes(undefined)) {
1233                 this.allRowsRetrieved = true;
1234                 pager.resultCount = this.data.length;
1235             }
1236         }
1237     }
1238 }
1239
1240