]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/eg2/src/app/share/grid/grid.ts
8a777e4b562440dca4cbe2f5d535c699faec5b11
[working/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} from 'rxjs/Observable';
6 import {Subscription} from 'rxjs/Subscription';
7 import {IdlService, IdlObject} from '@eg/core/idl.service';
8 import {OrgService} from '@eg/core/org.service';
9 import {ServerStoreService} from '@eg/core/server-store.service';
10 import {FormatService} from '@eg/core/format.service';
11 import {Pager} from '@eg/share/util/pager';
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     idlClass: string;
25     idlFieldDef: any;
26     datatype: string;
27     datePlusTime: boolean;
28     cellTemplate: TemplateRef<any>;
29     cellContext: any;
30     isIndex: boolean;
31     isDragTarget: boolean;
32     isSortable: boolean;
33     isMultiSortable: boolean;
34     comparator: (valueA: any, valueB: any) => number;
35
36     // True if the column was automatically generated.
37     isAuto: boolean;
38
39     flesher: (obj: any, col: GridColumn, item: any) => any;
40
41     getCellContext(row: any) {
42         return {
43           col: this,
44           row: row,
45           userContext: this.cellContext
46         };
47     }
48 }
49
50 export class GridColumnSet {
51     columns: GridColumn[];
52     idlClass: string;
53     indexColumn: GridColumn;
54     isSortable: boolean;
55     isMultiSortable: boolean;
56     stockVisible: string[];
57     idl: IdlService;
58     defaultHiddenFields: string[];
59     defaultVisibleFields: string[];
60
61     constructor(idl: IdlService, idlClass?: string) {
62         this.idl = idl;
63         this.columns = [];
64         this.stockVisible = [];
65         this.idlClass = idlClass;
66     }
67
68     add(col: GridColumn) {
69
70         this.applyColumnDefaults(col);
71
72         if (!this.insertColumn(col)) {
73             // Column was rejected as a duplicate.
74             return;
75         }
76
77         if (col.isIndex) { this.indexColumn = col; }
78
79         // track which fields are visible on page load.
80         if (col.visible) {
81             this.stockVisible.push(col.name);
82         }
83
84         this.applyColumnSortability(col);
85     }
86
87     // Returns true if the new column was inserted, false otherwise.
88     // Declared columns take precedence over auto-generated columns
89     // when collisions occur.
90     // Declared columns are inserted in front of auto columns.
91     insertColumn(col: GridColumn): boolean {
92
93         if (col.isAuto) {
94             if (this.getColByName(col.name)) {
95                 // New auto-generated column conflicts with existing
96                 // column.  Skip it.
97                 return false;
98             } else {
99                 // No collisions.  Add to the end of the list
100                 this.columns.push(col);
101                 return true;
102             }
103         }
104
105         // Adding a declared column.
106
107         // Check for dupes.
108         for (let idx = 0; idx < this.columns.length; idx++) {
109             const testCol = this.columns[idx];
110             if (testCol.name === col.name) { // match found
111                 if (testCol.isAuto) {
112                     // new column takes precedence, remove the existing column.
113                     this.columns.splice(idx, 1);
114                     break;
115                 } else {
116                     // New column does not take precedence.  Avoid
117                     // inserting it.
118                     return false;
119                 }
120             }
121         }
122
123         // Delcared columns are inserted just before the first auto-column
124         for (let idx = 0; idx < this.columns.length; idx++) {
125             const testCol = this.columns[idx];
126             if (testCol.isAuto) {
127                 if (idx === 0) {
128                     this.columns.unshift(col);
129                 } else {
130                     this.columns.splice(idx - 1, 0, col);
131                 }
132                 return true;
133             }
134         }
135
136         // No insertion point found.  Toss the new column on the end.
137         this.columns.push(col);
138         return true;
139     }
140
141     getColByName(name: string): GridColumn {
142         return this.columns.filter(c => c.name === name)[0];
143     }
144
145     idlInfoFromDotpath(dotpath: string): any {
146         if (!dotpath || !this.idlClass) { return null; }
147
148         let idlParent;
149         let idlField;
150         let idlClass = this.idl.classes[this.idlClass];
151
152         const pathParts = dotpath.split(/\./);
153
154         for (let i = 0; i < pathParts.length; i++) {
155             const part = pathParts[i];
156             idlParent = idlField;
157             idlField = idlClass.field_map[part];
158
159             if (idlField) {
160                 if (idlField['class'] && (
161                     idlField.datatype === 'link' ||
162                     idlField.datatype === 'org_unit')) {
163                     idlClass = this.idl.classes[idlField['class']];
164                 }
165             } else {
166                 return null;
167             }
168         }
169
170         return {
171             idlParent: idlParent,
172             idlField : idlField,
173             idlClass : idlClass
174         };
175     }
176
177
178     reset() {
179         this.columns.forEach(col => {
180             col.flex = 2;
181             col.sort = 0;
182             col.align = 'left';
183             col.visible = this.stockVisible.includes(col.name);
184         });
185     }
186
187     applyColumnDefaults(col: GridColumn) {
188
189         if (!col.idlFieldDef && col.path) {
190             const idlInfo = this.idlInfoFromDotpath(col.path);
191             if (idlInfo) {
192                 col.idlFieldDef = idlInfo.idlField;
193                 if (!col.label) {
194                     col.label = col.idlFieldDef.label || col.idlFieldDef.name;
195                     col.datatype = col.idlFieldDef.datatype;
196                 }
197             }
198         }
199
200         if (!col.name) { col.name = col.path; }
201         if (!col.flex) { col.flex = 2; }
202         if (!col.align) { col.align = 'left'; }
203         if (!col.label) { col.label = col.name; }
204         if (!col.datatype) { col.datatype = 'text'; }
205
206         col.visible = !col.hidden;
207     }
208
209     applyColumnSortability(col: GridColumn) {
210         // column sortability defaults to the sortability of the column set.
211         if (col.isSortable === undefined && this.isSortable) {
212             col.isSortable = true;
213         }
214
215         if (col.isMultiSortable === undefined && this.isMultiSortable) {
216             col.isMultiSortable = true;
217         }
218
219         if (col.isMultiSortable) {
220             col.isSortable = true;
221         }
222     }
223
224     displayColumns(): GridColumn[] {
225         return this.columns.filter(c => c.visible);
226     }
227
228     insertBefore(source: GridColumn, target: GridColumn) {
229         let targetIdx = -1;
230         let sourceIdx = -1;
231         this.columns.forEach((col, idx) => {
232             if (col.name === target.name) { targetIdx = idx; }});
233
234         this.columns.forEach((col, idx) => {
235             if (col.name === source.name) { sourceIdx = idx; }});
236
237         if (sourceIdx >= 0) {
238             this.columns.splice(sourceIdx, 1);
239         }
240
241         this.columns.splice(targetIdx, 0, source);
242     }
243
244     // Move visible columns to the front of the list.
245     moveVisibleToFront() {
246         const newCols = this.displayColumns();
247         this.columns.forEach(col => {
248             if (!col.visible) { newCols.push(col); }});
249         this.columns = newCols;
250     }
251
252     moveColumn(col: GridColumn, diff: number) {
253         let srcIdx, targetIdx;
254
255         this.columns.forEach((c, i) => {
256           if (c.name === col.name) { srcIdx = i; }
257         });
258
259         targetIdx = srcIdx + diff;
260         if (targetIdx < 0) {
261             targetIdx = 0;
262         } else if (targetIdx >= this.columns.length) {
263             // Target index follows the last visible column.
264             let lastVisible = 0;
265             this.columns.forEach((c, idx) => {
266                 if (c.visible) { lastVisible = idx; }
267             });
268
269             // When moving a column (down) causes one or more
270             // visible columns to shuffle forward, our column
271             // moves into the slot of the last visible column.
272             // Otherwise, put it into the slot directly following
273             // the last visible column.
274             targetIdx = srcIdx <= lastVisible ? lastVisible : lastVisible + 1;
275         }
276
277         // Splice column out of old position, insert at new position.
278         this.columns.splice(srcIdx, 1);
279         this.columns.splice(targetIdx, 0, col);
280     }
281
282     compileSaveObject(): GridColumnPersistConf[] {
283         // only store information about visible columns.
284         // scrunch the data down to just the needed info.
285         return this.displayColumns().map(col => {
286             const c: GridColumnPersistConf = {name : col.name};
287             if (col.align !== 'left') { c.align = col.align; }
288             if (col.flex !== 2) { c.flex = Number(col.flex); }
289             if (Number(col.sort)) { c.sort = Number(c.sort); }
290             return c;
291         });
292     }
293
294     applyColumnSettings(conf: GridColumnPersistConf[]) {
295
296         if (!conf || conf.length === 0) {
297             // No configuration is available, but we have a list of
298             // fields to show or hide by default
299
300             if (this.defaultVisibleFields) {
301                 this.columns.forEach(col => {
302                     if (this.defaultVisibleFields.includes(col.name)) {
303                         col.visible = true;
304                     } else {
305                         col.visible = false;
306                     }
307                 });
308
309             } else if (this.defaultHiddenFields) {
310                 this.defaultHiddenFields.forEach(name => {
311                     const col = this.getColByName(name);
312                     if (col) {
313                         col.visible = false;
314                     }
315                 });
316             }
317
318             return;
319         }
320
321         const newCols = [];
322
323         conf.forEach(colConf => {
324             const col = this.getColByName(colConf.name);
325             if (!col) { return; } // no such column in this grid.
326
327             col.visible = true;
328             if (colConf.align) { col.align = colConf.align; }
329             if (colConf.flex)  { col.flex = Number(colConf.flex); }
330             if (colConf.sort)  { col.sort = Number(colConf.sort); }
331
332             // Add to new columns array, avoid dupes.
333             if (newCols.filter(c => c.name === col.name).length === 0) {
334                 newCols.push(col);
335             }
336         });
337
338         // columns which are not expressed within the saved
339         // configuration are marked as non-visible and
340         // appended to the end of the new list of columns.
341         this.columns.forEach(c => {
342             if (conf.filter(cf => cf.name === c.name).length === 0) {
343                 c.visible = false;
344                 newCols.push(c);
345             }
346         });
347
348         this.columns = newCols;
349     }
350 }
351
352
353 export class GridRowSelector {
354     indexes: {[string: string]: boolean};
355
356     constructor() {
357         this.clear();
358     }
359
360     // Returns true if all of the requested indexes exist in the selector.
361     contains(index: string | string[]): boolean {
362         const indexes = [].concat(index);
363         for (let i = 0; i < indexes.length; i++) { // early exit
364             if (!this.indexes[indexes[i]]) {
365                 return false;
366             }
367         }
368         return true;
369     }
370
371     select(index: string | string[]) {
372         const indexes = [].concat(index);
373         indexes.forEach(i => this.indexes[i] = true);
374     }
375
376     deselect(index: string | string[]) {
377         const indexes = [].concat(index);
378         indexes.forEach(i => delete this.indexes[i]);
379     }
380
381     // Returns the list of selected index values.
382     // in some contexts (template checkboxes) the value for an index is
383     // set to false to deselect instead of having it removed (via deselect()).
384     selected() {
385         return Object.keys(this.indexes).filter(
386             ind => Boolean(this.indexes[ind]));
387     }
388
389     isEmpty(): boolean {
390         return this.selected().length === 0;
391     }
392
393     clear() {
394         this.indexes = {};
395     }
396 }
397
398 export interface GridRowFlairEntry {
399     icon: string;   // name of material icon
400     title: string;  // tooltip string
401 }
402
403 export class GridColumnPersistConf {
404     name: string;
405     flex?: number;
406     sort?: number;
407     align?: string;
408 }
409
410 export class GridPersistConf {
411     version: number;
412     limit: number;
413     columns: GridColumnPersistConf[];
414 }
415
416 export class GridContext {
417
418     pager: Pager;
419     idlClass: string;
420     isSortable: boolean;
421     isMultiSortable: boolean;
422     useLocalSort: boolean;
423     persistKey: string;
424     disableMultiSelect: 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
441     // Services injected by our grid component
442     idl: IdlService;
443     org: OrgService;
444     store: ServerStoreService;
445     format: FormatService;
446
447     constructor(
448         idl: IdlService,
449         org: OrgService,
450         store: ServerStoreService,
451         format: FormatService) {
452
453         this.idl = idl;
454         this.org = org;
455         this.store = store;
456         this.format = format;
457         this.pager = new Pager();
458         this.pager.limit = 10;
459         this.rowSelector = new GridRowSelector();
460         this.toolbarButtons = [];
461         this.toolbarCheckboxes = [];
462         this.toolbarActions = [];
463     }
464
465     init() {
466         this.columnSet = new GridColumnSet(this.idl, this.idlClass);
467         this.columnSet.isSortable = this.isSortable === true;
468         this.columnSet.isMultiSortable = this.isMultiSortable === true;
469         this.columnSet.defaultHiddenFields = this.defaultHiddenFields;
470         this.columnSet.defaultVisibleFields = this.defaultVisibleFields;
471         this.generateColumns();
472     }
473
474     // Load initial settings and data.
475     initData() {
476         this.applyGridConfig()
477         .then(ok => this.dataSource.requestPage(this.pager))
478         .then(ok => this.listenToPager());
479     }
480
481     destroy() {
482         this.ignorePager();
483     }
484
485     applyGridConfig(): Promise<void> {
486         return this.getGridConfig(this.persistKey)
487         .then(conf => {
488             let columns = [];
489             if (conf) {
490                 columns = conf.columns;
491                 if (conf.limit) {
492                     this.pager.limit = conf.limit;
493                 }
494             }
495
496             // This is called regardless of the presence of saved
497             // settings so defaults can be applied.
498             this.columnSet.applyColumnSettings(columns);
499         });
500     }
501
502     reload() {
503         // Give the UI time to settle before reloading grid data.
504         // This can help when data retrieval depends on a value
505         // getting modified by an angular digest cycle.
506         setTimeout(() => {
507             this.pager.reset();
508             this.dataSource.reset();
509             this.dataSource.requestPage(this.pager);
510         });
511     }
512
513     // Sort the existing data source instead of requesting sorted
514     // data from the client.  Reset pager to page 1.  As with reload(),
515     // give the client a chance to setting before redisplaying.
516     sortLocal() {
517         setTimeout(() => {
518             this.pager.reset();
519             this.sortLocalData();
520             this.dataSource.requestPage(this.pager);
521         });
522     }
523
524     // Subscribe or unsubscribe to page-change events from the pager.
525     listenToPager() {
526         if (this.pageChanges) { return; }
527         this.pageChanges = this.pager.onChange$.subscribe(
528             val => this.dataSource.requestPage(this.pager));
529     }
530
531     ignorePager() {
532         if (!this.pageChanges) { return; }
533         this.pageChanges.unsubscribe();
534         this.pageChanges = null;
535     }
536
537     // Sort data in the data source array
538     sortLocalData() {
539
540         const sortDefs = this.dataSource.sort.map(sort => {
541             const def = {
542                 name: sort.name,
543                 dir: sort.dir,
544                 col: this.columnSet.getColByName(sort.name)
545             };
546
547             if (!def.col.comparator) {
548                 def.col.comparator = (a, b) => {
549                     if (a < b) { return -1; }
550                     if (a > b) { return 1; }
551                     return 0;
552                 };
553             }
554
555             return def;
556         });
557
558         this.dataSource.data.sort((rowA, rowB) => {
559
560             for (let idx = 0; idx < sortDefs.length; idx++) {
561                 const sortDef = sortDefs[idx];
562
563                 const valueA = this.getRowColumnValue(rowA, sortDef.col);
564                 const valueB = this.getRowColumnValue(rowB, sortDef.col);
565
566                 if (valueA === '' && valueB === '') { continue; }
567                 if (valueA === '' && valueB !== '') { return 1; }
568                 if (valueA !== '' && valueB === '') { return -1; }
569
570                 const diff = sortDef.col.comparator(valueA, valueB);
571                 if (diff === 0) { continue; }
572
573                 console.log(valueA, valueB, diff);
574
575                 return sortDef.dir === 'DESC' ? -diff : diff;
576             }
577
578             return 0; // No differences found.
579         });
580     }
581
582     getRowIndex(row: any): any {
583         const col = this.columnSet.indexColumn;
584         if (!col) {
585             throw new Error('grid index column required');
586         }
587         return this.getRowColumnValue(row, col);
588     }
589
590     // Returns position in the data source array of the row with
591     // the provided index.
592     getRowPosition(index: any): number {
593         // for-loop for early exit
594         for (let idx = 0; idx < this.dataSource.data.length; idx++) {
595             const row = this.dataSource.data[idx];
596             if (row !== undefined && index === this.getRowIndex(row)) {
597                 return idx;
598             }
599         }
600     }
601
602     // Return the row with the provided index.
603     getRowByIndex(index: any): any {
604         for (let idx = 0; idx < this.dataSource.data.length; idx++) {
605             const row = this.dataSource.data[idx];
606             if (row !== undefined && index === this.getRowIndex(row)) {
607                 return row;
608             }
609         }
610     }
611
612     // Returns all selected rows, regardless of whether they are
613     // currently visible in the grid display.
614     getSelectedRows(): any[] {
615         const selected = [];
616         this.rowSelector.selected().forEach(index => {
617             const row = this.getRowByIndex(index);
618             if (row) {
619                 selected.push(row);
620             }
621         });
622         return selected;
623     }
624
625     getRowColumnValue(row: any, col: GridColumn): string {
626         let val;
627         if (col.name in row) {
628             val = this.getObjectFieldValue(row, col.name);
629         } else {
630             if (col.path) {
631                 val = this.nestedItemFieldValue(row, col);
632             }
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 (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             this.columnSet.add(col);
865         });
866     }
867
868     saveGridConfig(): Promise<any> {
869         if (!this.persistKey) {
870             throw new Error('Grid persistKey required to save columns');
871         }
872         const conf = new GridPersistConf();
873         conf.version = 2;
874         conf.limit = this.pager.limit;
875         conf.columns = this.columnSet.compileSaveObject();
876
877         return this.store.setItem('eg.grid.' + this.persistKey, conf);
878     }
879
880     // TODO: saveGridConfigAsOrgSetting(...)
881
882     getGridConfig(persistKey: string): Promise<GridPersistConf> {
883         if (!persistKey) { return Promise.resolve(null); }
884         return this.store.getItem('eg.grid.' + persistKey);
885     }
886 }
887
888
889 // Actions apply to specific rows
890 export class GridToolbarAction {
891     label: string;
892     action: (rows: any[]) => any;
893     disableOnRows: (rows: any[]) => boolean;
894 }
895
896 // Buttons are global actions
897 export class GridToolbarButton {
898     label: string;
899     action: () => any;
900     disabled: boolean;
901 }
902
903 export class GridToolbarCheckbox {
904     label: string;
905     onChange: (checked: boolean) => void;
906 }
907
908 export class GridDataSource {
909
910     data: any[];
911     sort: any[];
912     allRowsRetrieved: boolean;
913     getRows: (pager: Pager, sort: any[]) => Observable<any>;
914
915     constructor() {
916         this.sort = [];
917         this.reset();
918     }
919
920     reset() {
921         this.data = [];
922         this.allRowsRetrieved = false;
923     }
924
925     // called from the template -- no data fetching
926     getPageOfRows(pager: Pager): any[] {
927         if (this.data) {
928             return this.data.slice(
929                 pager.offset, pager.limit + pager.offset
930             ).filter(row => row !== undefined);
931         }
932         return [];
933     }
934
935     // called on initial component load and user action (e.g. paging, sorting).
936     requestPage(pager: Pager): Promise<any> {
937
938         if (
939             this.getPageOfRows(pager).length === pager.limit
940             // already have all data
941             || this.allRowsRetrieved
942             // have no way to get more data.
943             || !this.getRows
944         ) {
945             return Promise.resolve();
946         }
947
948         return new Promise((resolve, reject) => {
949             let idx = pager.offset;
950             return this.getRows(pager, this.sort).subscribe(
951                 row => this.data[idx++] = row,
952                 err => {
953                     console.error(`grid getRows() error ${err}`);
954                     reject(err);
955                 },
956                 ()  => {
957                     this.checkAllRetrieved(pager, idx);
958                     resolve();
959                 }
960             );
961         });
962     }
963
964     // See if the last getRows() call resulted in the final set of data.
965     checkAllRetrieved(pager: Pager, idx: number) {
966         if (this.allRowsRetrieved) { return; }
967
968         if (idx === 0 || idx < (pager.limit + pager.offset)) {
969             // last query returned nothing or less than one page.
970             // confirm we have all of the preceding pages.
971             if (!this.data.includes(undefined)) {
972                 this.allRowsRetrieved = true;
973                 pager.resultCount = this.data.length;
974             }
975         }
976     }
977 }
978
979