]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/eg2/src/app/share/grid/grid.ts
LP1812670 Angular grid shows selector labels
[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} 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
12 const MAX_ALL_ROW_COUNT = 10000;
13
14 export class GridColumn {
15     name: string;
16     path: string;
17     label: string;
18     flex: number;
19     align: string;
20     hidden: boolean;
21     visible: boolean;
22     sort: number;
23     idlClass: string;
24     idlFieldDef: any;
25     datatype: string;
26     datePlusTime: boolean;
27     cellTemplate: TemplateRef<any>;
28     cellContext: any;
29     isIndex: boolean;
30     isDragTarget: boolean;
31     isSortable: boolean;
32     isMultiSortable: boolean;
33     comparator: (valueA: any, valueB: any) => number;
34
35     // True if the column was automatically generated.
36     isAuto: boolean;
37
38     flesher: (obj: any, col: GridColumn, item: any) => any;
39
40     getCellContext(row: any) {
41         return {
42           col: this,
43           row: row,
44           userContext: this.cellContext
45         };
46     }
47 }
48
49 export class GridColumnSet {
50     columns: GridColumn[];
51     idlClass: string;
52     indexColumn: GridColumn;
53     isSortable: boolean;
54     isMultiSortable: boolean;
55     stockVisible: string[];
56     idl: IdlService;
57     defaultHiddenFields: string[];
58     defaultVisibleFields: string[];
59
60     constructor(idl: IdlService, idlClass?: string) {
61         this.idl = idl;
62         this.columns = [];
63         this.stockVisible = [];
64         this.idlClass = idlClass;
65     }
66
67     add(col: GridColumn) {
68
69         this.applyColumnDefaults(col);
70
71         if (!this.insertColumn(col)) {
72             // Column was rejected as a duplicate.
73             return;
74         }
75
76         if (col.isIndex) { this.indexColumn = col; }
77
78         // track which fields are visible on page load.
79         if (col.visible) {
80             this.stockVisible.push(col.name);
81         }
82
83         this.applyColumnSortability(col);
84     }
85
86     // Returns true if the new column was inserted, false otherwise.
87     // Declared columns take precedence over auto-generated columns
88     // when collisions occur.
89     // Declared columns are inserted in front of auto columns.
90     insertColumn(col: GridColumn): boolean {
91
92         if (col.isAuto) {
93             if (this.getColByName(col.name)) {
94                 // New auto-generated column conflicts with existing
95                 // column.  Skip it.
96                 return false;
97             } else {
98                 // No collisions.  Add to the end of the list
99                 this.columns.push(col);
100                 return true;
101             }
102         }
103
104         // Adding a declared column.
105
106         // Check for dupes.
107         for (let idx = 0; idx < this.columns.length; idx++) {
108             const testCol = this.columns[idx];
109             if (testCol.name === col.name) { // match found
110                 if (testCol.isAuto) {
111                     // new column takes precedence, remove the existing column.
112                     this.columns.splice(idx, 1);
113                     break;
114                 } else {
115                     // New column does not take precedence.  Avoid
116                     // inserting it.
117                     return false;
118                 }
119             }
120         }
121
122         // Delcared columns are inserted just before the first auto-column
123         for (let idx = 0; idx < this.columns.length; idx++) {
124             const testCol = this.columns[idx];
125             if (testCol.isAuto) {
126                 if (idx === 0) {
127                     this.columns.unshift(col);
128                 } else {
129                     this.columns.splice(idx - 1, 0, col);
130                 }
131                 return true;
132             }
133         }
134
135         // No insertion point found.  Toss the new column on the end.
136         this.columns.push(col);
137         return true;
138     }
139
140     getColByName(name: string): GridColumn {
141         return this.columns.filter(c => c.name === name)[0];
142     }
143
144     idlInfoFromDotpath(dotpath: string): any {
145         if (!dotpath || !this.idlClass) { return null; }
146
147         let idlParent;
148         let idlField;
149         let idlClass = this.idl.classes[this.idlClass];
150
151         const pathParts = dotpath.split(/\./);
152
153         for (let i = 0; i < pathParts.length; i++) {
154             const part = pathParts[i];
155             idlParent = idlField;
156             idlField = idlClass.field_map[part];
157
158             if (idlField) {
159                 if (idlField['class'] && (
160                     idlField.datatype === 'link' ||
161                     idlField.datatype === 'org_unit')) {
162                     idlClass = this.idl.classes[idlField['class']];
163                 }
164             } else {
165                 return null;
166             }
167         }
168
169         return {
170             idlParent: idlParent,
171             idlField : idlField,
172             idlClass : idlClass
173         };
174     }
175
176
177     reset() {
178         this.columns.forEach(col => {
179             col.flex = 2;
180             col.sort = 0;
181             col.align = 'left';
182             col.visible = this.stockVisible.includes(col.name);
183         });
184     }
185
186     applyColumnDefaults(col: GridColumn) {
187
188         if (!col.idlFieldDef && col.path) {
189             const idlInfo = this.idlInfoFromDotpath(col.path);
190             if (idlInfo) {
191                 col.idlFieldDef = idlInfo.idlField;
192                 if (!col.label) {
193                     col.label = col.idlFieldDef.label || col.idlFieldDef.name;
194                     col.datatype = col.idlFieldDef.datatype;
195                 }
196             }
197         }
198
199         if (!col.name) { col.name = col.path; }
200         if (!col.flex) { col.flex = 2; }
201         if (!col.align) { col.align = 'left'; }
202         if (!col.label) { col.label = col.name; }
203         if (!col.datatype) { col.datatype = 'text'; }
204
205         col.visible = !col.hidden;
206     }
207
208     applyColumnSortability(col: GridColumn) {
209         // column sortability defaults to the sortability of the column set.
210         if (col.isSortable === undefined && this.isSortable) {
211             col.isSortable = true;
212         }
213
214         if (col.isMultiSortable === undefined && this.isMultiSortable) {
215             col.isMultiSortable = true;
216         }
217
218         if (col.isMultiSortable) {
219             col.isSortable = true;
220         }
221     }
222
223     displayColumns(): GridColumn[] {
224         return this.columns.filter(c => c.visible);
225     }
226
227     insertBefore(source: GridColumn, target: GridColumn) {
228         let targetIdx = -1;
229         let sourceIdx = -1;
230         this.columns.forEach((col, idx) => {
231             if (col.name === target.name) { targetIdx = idx; }});
232
233         this.columns.forEach((col, idx) => {
234             if (col.name === source.name) { sourceIdx = idx; }});
235
236         if (sourceIdx >= 0) {
237             this.columns.splice(sourceIdx, 1);
238         }
239
240         this.columns.splice(targetIdx, 0, source);
241     }
242
243     // Move visible columns to the front of the list.
244     moveVisibleToFront() {
245         const newCols = this.displayColumns();
246         this.columns.forEach(col => {
247             if (!col.visible) { newCols.push(col); }});
248         this.columns = newCols;
249     }
250
251     moveColumn(col: GridColumn, diff: number) {
252         let srcIdx, targetIdx;
253
254         this.columns.forEach((c, i) => {
255           if (c.name === col.name) { srcIdx = i; }
256         });
257
258         targetIdx = srcIdx + diff;
259         if (targetIdx < 0) {
260             targetIdx = 0;
261         } else if (targetIdx >= this.columns.length) {
262             // Target index follows the last visible column.
263             let lastVisible = 0;
264             this.columns.forEach((c, idx) => {
265                 if (c.visible) { lastVisible = idx; }
266             });
267
268             // When moving a column (down) causes one or more
269             // visible columns to shuffle forward, our column
270             // moves into the slot of the last visible column.
271             // Otherwise, put it into the slot directly following
272             // the last visible column.
273             targetIdx = srcIdx <= lastVisible ? lastVisible : lastVisible + 1;
274         }
275
276         // Splice column out of old position, insert at new position.
277         this.columns.splice(srcIdx, 1);
278         this.columns.splice(targetIdx, 0, col);
279     }
280
281     compileSaveObject(): GridColumnPersistConf[] {
282         // only store information about visible columns.
283         // scrunch the data down to just the needed info.
284         return this.displayColumns().map(col => {
285             const c: GridColumnPersistConf = {name : col.name};
286             if (col.align !== 'left') { c.align = col.align; }
287             if (col.flex !== 2) { c.flex = Number(col.flex); }
288             if (Number(col.sort)) { c.sort = Number(c.sort); }
289             return c;
290         });
291     }
292
293     applyColumnSettings(conf: GridColumnPersistConf[]) {
294
295         if (!conf || conf.length === 0) {
296             // No configuration is available, but we have a list of
297             // fields to show or hide by default
298
299             if (this.defaultVisibleFields) {
300                 this.columns.forEach(col => {
301                     if (this.defaultVisibleFields.includes(col.name)) {
302                         col.visible = true;
303                     } else {
304                         col.visible = false;
305                     }
306                 });
307
308             } else if (this.defaultHiddenFields) {
309                 this.defaultHiddenFields.forEach(name => {
310                     const col = this.getColByName(name);
311                     if (col) {
312                         col.visible = false;
313                     }
314                 });
315             }
316
317             return;
318         }
319
320         const newCols = [];
321
322         conf.forEach(colConf => {
323             const col = this.getColByName(colConf.name);
324             if (!col) { return; } // no such column in this grid.
325
326             col.visible = true;
327             if (colConf.align) { col.align = colConf.align; }
328             if (colConf.flex)  { col.flex = Number(colConf.flex); }
329             if (colConf.sort)  { col.sort = Number(colConf.sort); }
330
331             // Add to new columns array, avoid dupes.
332             if (newCols.filter(c => c.name === col.name).length === 0) {
333                 newCols.push(col);
334             }
335         });
336
337         // columns which are not expressed within the saved
338         // configuration are marked as non-visible and
339         // appended to the end of the new list of columns.
340         this.columns.forEach(c => {
341             if (conf.filter(cf => cf.name === c.name).length === 0) {
342                 c.visible = false;
343                 newCols.push(c);
344             }
345         });
346
347         this.columns = newCols;
348     }
349 }
350
351
352 export class GridRowSelector {
353     indexes: {[string: string]: boolean};
354
355     constructor() {
356         this.clear();
357     }
358
359     // Returns true if all of the requested indexes exist in the selector.
360     contains(index: string | string[]): boolean {
361         const indexes = [].concat(index);
362         for (let i = 0; i < indexes.length; i++) { // early exit
363             if (!this.indexes[indexes[i]]) {
364                 return false;
365             }
366         }
367         return true;
368     }
369
370     select(index: string | string[]) {
371         const indexes = [].concat(index);
372         indexes.forEach(i => this.indexes[i] = true);
373     }
374
375     deselect(index: string | string[]) {
376         const indexes = [].concat(index);
377         indexes.forEach(i => delete this.indexes[i]);
378     }
379
380     // Returns the list of selected index values.
381     // in some contexts (template checkboxes) the value for an index is
382     // set to false to deselect instead of having it removed (via deselect()).
383     selected() {
384         return Object.keys(this.indexes).filter(
385             ind => Boolean(this.indexes[ind]));
386     }
387
388     isEmpty(): boolean {
389         return this.selected().length === 0;
390     }
391
392     clear() {
393         this.indexes = {};
394     }
395 }
396
397 export interface GridRowFlairEntry {
398     icon: string;   // name of material icon
399     title?: string;  // tooltip string
400 }
401
402 export class GridColumnPersistConf {
403     name: string;
404     flex?: number;
405     sort?: number;
406     align?: string;
407 }
408
409 export class GridPersistConf {
410     version: number;
411     limit: number;
412     columns: GridColumnPersistConf[];
413 }
414
415 export class GridContext {
416
417     pager: Pager;
418     idlClass: string;
419     isSortable: boolean;
420     isMultiSortable: boolean;
421     useLocalSort: boolean;
422     persistKey: string;
423     disableMultiSelect: boolean;
424     disableSelect: boolean;
425     dataSource: GridDataSource;
426     columnSet: GridColumnSet;
427     rowSelector: GridRowSelector;
428     toolbarButtons: GridToolbarButton[];
429     toolbarCheckboxes: GridToolbarCheckbox[];
430     toolbarActions: GridToolbarAction[];
431     lastSelectedIndex: any;
432     pageChanges: Subscription;
433     rowFlairIsEnabled: boolean;
434     rowFlairCallback: (row: any) => GridRowFlairEntry;
435     rowClassCallback: (row: any) => string;
436     cellClassCallback: (row: any, col: GridColumn) => string;
437     defaultVisibleFields: string[];
438     defaultHiddenFields: string[];
439     overflowCells: boolean;
440     showLinkSelectors: boolean;
441
442     // Services injected by our grid component
443     idl: IdlService;
444     org: OrgService;
445     store: ServerStoreService;
446     format: FormatService;
447
448     constructor(
449         idl: IdlService,
450         org: OrgService,
451         store: ServerStoreService,
452         format: FormatService) {
453
454         this.idl = idl;
455         this.org = org;
456         this.store = store;
457         this.format = format;
458         this.pager = new Pager();
459         this.pager.limit = 10;
460         this.rowSelector = new GridRowSelector();
461         this.toolbarButtons = [];
462         this.toolbarCheckboxes = [];
463         this.toolbarActions = [];
464     }
465
466     init() {
467         this.columnSet = new GridColumnSet(this.idl, this.idlClass);
468         this.columnSet.isSortable = this.isSortable === true;
469         this.columnSet.isMultiSortable = this.isMultiSortable === true;
470         this.columnSet.defaultHiddenFields = this.defaultHiddenFields;
471         this.columnSet.defaultVisibleFields = this.defaultVisibleFields;
472         this.generateColumns();
473     }
474
475     // Load initial settings and data.
476     initData() {
477         this.applyGridConfig()
478         .then(ok => this.dataSource.requestPage(this.pager))
479         .then(ok => this.listenToPager());
480     }
481
482     destroy() {
483         this.ignorePager();
484     }
485
486     applyGridConfig(): Promise<void> {
487         return this.getGridConfig(this.persistKey)
488         .then(conf => {
489             let columns = [];
490             if (conf) {
491                 columns = conf.columns;
492                 if (conf.limit) {
493                     this.pager.limit = conf.limit;
494                 }
495             }
496
497             // This is called regardless of the presence of saved
498             // settings so defaults can be applied.
499             this.columnSet.applyColumnSettings(columns);
500         });
501     }
502
503     reload() {
504         // Give the UI time to settle before reloading grid data.
505         // This can help when data retrieval depends on a value
506         // getting modified by an angular digest cycle.
507         setTimeout(() => {
508             this.pager.reset();
509             this.dataSource.reset();
510             this.dataSource.requestPage(this.pager);
511         });
512     }
513
514     // Sort the existing data source instead of requesting sorted
515     // data from the client.  Reset pager to page 1.  As with reload(),
516     // give the client a chance to setting before redisplaying.
517     sortLocal() {
518         setTimeout(() => {
519             this.pager.reset();
520             this.sortLocalData();
521             this.dataSource.requestPage(this.pager);
522         });
523     }
524
525     // Subscribe or unsubscribe to page-change events from the pager.
526     listenToPager() {
527         if (this.pageChanges) { return; }
528         this.pageChanges = this.pager.onChange$.subscribe(
529             val => this.dataSource.requestPage(this.pager));
530     }
531
532     ignorePager() {
533         if (!this.pageChanges) { return; }
534         this.pageChanges.unsubscribe();
535         this.pageChanges = null;
536     }
537
538     // Sort data in the data source array
539     sortLocalData() {
540
541         const sortDefs = this.dataSource.sort.map(sort => {
542             const def = {
543                 name: sort.name,
544                 dir: sort.dir,
545                 col: this.columnSet.getColByName(sort.name)
546             };
547
548             if (!def.col.comparator) {
549                 def.col.comparator = (a, b) => {
550                     if (a < b) { return -1; }
551                     if (a > b) { return 1; }
552                     return 0;
553                 };
554             }
555
556             return def;
557         });
558
559         this.dataSource.data.sort((rowA, rowB) => {
560
561             for (let idx = 0; idx < sortDefs.length; idx++) {
562                 const sortDef = sortDefs[idx];
563
564                 const valueA = this.getRowColumnValue(rowA, sortDef.col);
565                 const valueB = this.getRowColumnValue(rowB, sortDef.col);
566
567                 if (valueA === '' && valueB === '') { continue; }
568                 if (valueA === '' && valueB !== '') { return 1; }
569                 if (valueA !== '' && valueB === '') { return -1; }
570
571                 const diff = sortDef.col.comparator(valueA, valueB);
572                 if (diff === 0) { continue; }
573
574                 console.log(valueA, valueB, diff);
575
576                 return sortDef.dir === 'DESC' ? -diff : diff;
577             }
578
579             return 0; // No differences found.
580         });
581     }
582
583     getRowIndex(row: any): any {
584         const col = this.columnSet.indexColumn;
585         if (!col) {
586             throw new Error('grid index column required');
587         }
588         return this.getRowColumnValue(row, col);
589     }
590
591     // Returns position in the data source array of the row with
592     // the provided index.
593     getRowPosition(index: any): number {
594         // for-loop for early exit
595         for (let idx = 0; idx < this.dataSource.data.length; idx++) {
596             const row = this.dataSource.data[idx];
597             if (row !== undefined && index === this.getRowIndex(row)) {
598                 return idx;
599             }
600         }
601     }
602
603     // Return the row with the provided index.
604     getRowByIndex(index: any): any {
605         for (let idx = 0; idx < this.dataSource.data.length; idx++) {
606             const row = this.dataSource.data[idx];
607             if (row !== undefined && index === this.getRowIndex(row)) {
608                 return row;
609             }
610         }
611     }
612
613     // Returns all selected rows, regardless of whether they are
614     // currently visible in the grid display.
615     getSelectedRows(): any[] {
616         const selected = [];
617         this.rowSelector.selected().forEach(index => {
618             const row = this.getRowByIndex(index);
619             if (row) {
620                 selected.push(row);
621             }
622         });
623         return selected;
624     }
625
626     getRowColumnValue(row: any, col: GridColumn): string {
627         let val;
628
629         if (col.path) {
630             val = this.nestedItemFieldValue(row, col);
631         } else if (col.name in row) {
632             val = this.getObjectFieldValue(row, col.name);
633         }
634
635         return this.format.transform({
636             value: val,
637             datatype: col.datatype,
638             datePlusTime: Boolean(col.datePlusTime)
639         });
640     }
641
642     getObjectFieldValue(obj: any, name: string): any {
643         if (typeof obj[name] === 'function') {
644             return obj[name]();
645         } else {
646             return obj[name];
647         }
648     }
649
650     nestedItemFieldValue(obj: any, col: GridColumn): string {
651
652         let idlField;
653         let idlClassDef;
654         const original = obj;
655         const steps = col.path.split('.');
656
657         for (let i = 0; i < steps.length; i++) {
658             const step = steps[i];
659
660             if (obj === null || obj === undefined || typeof obj !== 'object') {
661                 // We have run out of data to step through before
662                 // reaching the end of the path.  Conclude fleshing via
663                 // callback if provided then exit.
664                 if (col.flesher && obj !== undefined) {
665                     return col.flesher(obj, col, original);
666                 }
667                 return obj;
668             }
669
670             const class_ = obj.classname;
671             if (class_ && (idlClassDef = this.idl.classes[class_])) {
672                 idlField = idlClassDef.field_map[step];
673             }
674
675             obj = this.getObjectFieldValue(obj, step);
676         }
677
678         // We found a nested IDL object which may or may not have
679         // been configured as a top-level column.  Flesh the column
680         // metadata with our newly found IDL info.
681         if (idlField) {
682             if (!col.datatype) {
683                 col.datatype = idlField.datatype;
684             }
685             if (!col.label) {
686                 col.label = idlField.label || idlField.name;
687             }
688         }
689
690         return obj;
691     }
692
693
694     getColumnTextContent(row: any, col: GridColumn): string {
695         if (col.cellTemplate) {
696             // TODO
697             // Extract the text content from the rendered template.
698         } else {
699             return this.getRowColumnValue(row, col);
700         }
701     }
702
703     selectOneRow(index: any) {
704         this.rowSelector.clear();
705         this.rowSelector.select(index);
706         this.lastSelectedIndex = index;
707     }
708
709     // selects or deselects an item, without affecting the others.
710     // returns true if the item is selected; false if de-selected.
711     toggleSelectOneRow(index: any) {
712         if (this.rowSelector.contains(index)) {
713             this.rowSelector.deselect(index);
714             return false;
715         }
716
717         this.rowSelector.select(index);
718         return true;
719     }
720
721     selectRowByPos(pos: number) {
722         const row = this.dataSource.data[pos];
723         if (row) {
724             this.selectOneRow(this.getRowIndex(row));
725         }
726     }
727
728     selectPreviousRow() {
729         if (!this.lastSelectedIndex) { return; }
730         const pos = this.getRowPosition(this.lastSelectedIndex);
731         if (pos === this.pager.offset) {
732             this.toPrevPage().then(ok => this.selectLastRow(), err => {});
733         } else {
734             this.selectRowByPos(pos - 1);
735         }
736     }
737
738     selectNextRow() {
739         if (!this.lastSelectedIndex) { return; }
740         const pos = this.getRowPosition(this.lastSelectedIndex);
741         if (pos === (this.pager.offset + this.pager.limit - 1)) {
742             this.toNextPage().then(ok => this.selectFirstRow(), err => {});
743         } else {
744             this.selectRowByPos(pos + 1);
745         }
746     }
747
748     selectFirstRow() {
749         this.selectRowByPos(this.pager.offset);
750     }
751
752     selectLastRow() {
753         this.selectRowByPos(this.pager.offset + this.pager.limit - 1);
754     }
755
756     toPrevPage(): Promise<any> {
757         if (this.pager.isFirstPage()) {
758             return Promise.reject('on first');
759         }
760         // temp ignore pager events since we're calling requestPage manually.
761         this.ignorePager();
762         this.pager.decrement();
763         this.listenToPager();
764         return this.dataSource.requestPage(this.pager);
765     }
766
767     toNextPage(): Promise<any> {
768         if (this.pager.isLastPage()) {
769             return Promise.reject('on last');
770         }
771         // temp ignore pager events since we're calling requestPage manually.
772         this.ignorePager();
773         this.pager.increment();
774         this.listenToPager();
775         return this.dataSource.requestPage(this.pager);
776     }
777
778     getAllRows(): Promise<any> {
779         const pager = new Pager();
780         pager.offset = 0;
781         pager.limit = MAX_ALL_ROW_COUNT;
782         return this.dataSource.requestPage(pager);
783     }
784
785     // Returns a key/value pair object of visible column data as text.
786     getRowAsFlatText(row: any): any {
787         const flatRow = {};
788         this.columnSet.displayColumns().forEach(col => {
789             flatRow[col.name] =
790                 this.getColumnTextContent(row, col);
791         });
792         return flatRow;
793     }
794
795     getAllRowsAsText(): Observable<any> {
796         return Observable.create(observer => {
797             this.getAllRows().then(ok => {
798                 this.dataSource.data.forEach(row => {
799                     observer.next(this.getRowAsFlatText(row));
800                 });
801                 observer.complete();
802             });
803         });
804     }
805
806     gridToCsv(): Promise<string> {
807
808         let csvStr = '';
809         const columns = this.columnSet.displayColumns();
810
811         // CSV header
812         columns.forEach(col => {
813             csvStr += this.valueToCsv(col.label),
814             csvStr += ',';
815         });
816
817         csvStr = csvStr.replace(/,$/, '\n');
818
819         return new Promise(resolve => {
820             this.getAllRowsAsText().subscribe(
821                 row => {
822                     columns.forEach(col => {
823                         csvStr += this.valueToCsv(row[col.name]);
824                         csvStr += ',';
825                     });
826                     csvStr = csvStr.replace(/,$/, '\n');
827                 },
828                 err => {},
829                 ()  => resolve(csvStr)
830             );
831         });
832     }
833
834
835     // prepares a string for inclusion within a CSV document
836     // by escaping commas and quotes and removing newlines.
837     valueToCsv(str: string): string {
838         str = '' + str;
839         if (!str) { return ''; }
840         str = str.replace(/\n/g, '');
841         if (str.match(/\,/) || str.match(/"/)) {
842             str = str.replace(/"/g, '""');
843             str = '"' + str + '"';
844         }
845         return str;
846     }
847
848     generateColumns() {
849         if (!this.columnSet.idlClass) { return; }
850
851         const pkeyField = this.idl.classes[this.columnSet.idlClass].pkey;
852
853         // generate columns for all non-virtual fields on the IDL class
854         this.idl.classes[this.columnSet.idlClass].fields
855         .filter(field => !field.virtual)
856         .forEach(field => {
857             const col = new GridColumn();
858             col.name = field.name;
859             col.label = field.label || field.name;
860             col.idlFieldDef = field;
861             col.datatype = field.datatype;
862             col.isIndex = (field.name === pkeyField);
863             col.isAuto = true;
864
865             if (this.showLinkSelectors) {
866                 const selector = this.idl.getLinkSelector(
867                     this.columnSet.idlClass, field.name);
868                 if (selector) {
869                     col.path = field.name + '.' + selector;
870                 }
871             }
872
873             this.columnSet.add(col);
874         });
875     }
876
877     saveGridConfig(): Promise<any> {
878         if (!this.persistKey) {
879             throw new Error('Grid persistKey required to save columns');
880         }
881         const conf = new GridPersistConf();
882         conf.version = 2;
883         conf.limit = this.pager.limit;
884         conf.columns = this.columnSet.compileSaveObject();
885
886         return this.store.setItem('eg.grid.' + this.persistKey, conf);
887     }
888
889     // TODO: saveGridConfigAsOrgSetting(...)
890
891     getGridConfig(persistKey: string): Promise<GridPersistConf> {
892         if (!persistKey) { return Promise.resolve(null); }
893         return this.store.getItem('eg.grid.' + persistKey);
894     }
895 }
896
897
898 // Actions apply to specific rows
899 export class GridToolbarAction {
900     label: string;
901     action: (rows: any[]) => any;
902     disableOnRows: (rows: any[]) => boolean;
903 }
904
905 // Buttons are global actions
906 export class GridToolbarButton {
907     label: string;
908     action: () => any;
909     disabled: boolean;
910 }
911
912 export class GridToolbarCheckbox {
913     label: string;
914     onChange: (checked: boolean) => void;
915 }
916
917 export class GridDataSource {
918
919     data: any[];
920     sort: any[];
921     allRowsRetrieved: boolean;
922     getRows: (pager: Pager, sort: any[]) => Observable<any>;
923
924     constructor() {
925         this.sort = [];
926         this.reset();
927     }
928
929     reset() {
930         this.data = [];
931         this.allRowsRetrieved = false;
932     }
933
934     // called from the template -- no data fetching
935     getPageOfRows(pager: Pager): any[] {
936         if (this.data) {
937             return this.data.slice(
938                 pager.offset, pager.limit + pager.offset
939             ).filter(row => row !== undefined);
940         }
941         return [];
942     }
943
944     // called on initial component load and user action (e.g. paging, sorting).
945     requestPage(pager: Pager): Promise<any> {
946
947         if (
948             this.getPageOfRows(pager).length === pager.limit
949             // already have all data
950             || this.allRowsRetrieved
951             // have no way to get more data.
952             || !this.getRows
953         ) {
954             return Promise.resolve();
955         }
956
957         return new Promise((resolve, reject) => {
958             let idx = pager.offset;
959             return this.getRows(pager, this.sort).subscribe(
960                 row => this.data[idx++] = row,
961                 err => {
962                     console.error(`grid getRows() error ${err}`);
963                     reject(err);
964                 },
965                 ()  => {
966                     this.checkAllRetrieved(pager, idx);
967                     resolve();
968                 }
969             );
970         });
971     }
972
973     // See if the last getRows() call resulted in the final set of data.
974     checkAllRetrieved(pager: Pager, idx: number) {
975         if (this.allRowsRetrieved) { return; }
976
977         if (idx === 0 || idx < (pager.limit + pager.offset)) {
978             // last query returned nothing or less than one page.
979             // confirm we have all of the preceding pages.
980             if (!this.data.includes(undefined)) {
981                 this.allRowsRetrieved = true;
982                 pager.resultCount = this.data.length;
983             }
984         }
985     }
986 }
987
988