]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/eg2/src/app/share/grid/grid.ts
e04940dd1acf3bc4130e42828f957e4ad330c798
[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     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     dataSource: GridDataSource;
425     columnSet: GridColumnSet;
426     rowSelector: GridRowSelector;
427     toolbarButtons: GridToolbarButton[];
428     toolbarCheckboxes: GridToolbarCheckbox[];
429     toolbarActions: GridToolbarAction[];
430     lastSelectedIndex: any;
431     pageChanges: Subscription;
432     rowFlairIsEnabled: boolean;
433     rowFlairCallback: (row: any) => GridRowFlairEntry;
434     rowClassCallback: (row: any) => string;
435     cellClassCallback: (row: any, col: GridColumn) => string;
436     defaultVisibleFields: string[];
437     defaultHiddenFields: string[];
438     overflowCells: boolean;
439
440     // Services injected by our grid component
441     idl: IdlService;
442     org: OrgService;
443     store: ServerStoreService;
444     format: FormatService;
445
446     constructor(
447         idl: IdlService,
448         org: OrgService,
449         store: ServerStoreService,
450         format: FormatService) {
451
452         this.idl = idl;
453         this.org = org;
454         this.store = store;
455         this.format = format;
456         this.pager = new Pager();
457         this.pager.limit = 10;
458         this.rowSelector = new GridRowSelector();
459         this.toolbarButtons = [];
460         this.toolbarCheckboxes = [];
461         this.toolbarActions = [];
462     }
463
464     init() {
465         this.columnSet = new GridColumnSet(this.idl, this.idlClass);
466         this.columnSet.isSortable = this.isSortable === true;
467         this.columnSet.isMultiSortable = this.isMultiSortable === true;
468         this.columnSet.defaultHiddenFields = this.defaultHiddenFields;
469         this.columnSet.defaultVisibleFields = this.defaultVisibleFields;
470         this.generateColumns();
471     }
472
473     // Load initial settings and data.
474     initData() {
475         this.applyGridConfig()
476         .then(ok => this.dataSource.requestPage(this.pager))
477         .then(ok => this.listenToPager());
478     }
479
480     destroy() {
481         this.ignorePager();
482     }
483
484     applyGridConfig(): Promise<void> {
485         return this.getGridConfig(this.persistKey)
486         .then(conf => {
487             let columns = [];
488             if (conf) {
489                 columns = conf.columns;
490                 if (conf.limit) {
491                     this.pager.limit = conf.limit;
492                 }
493             }
494
495             // This is called regardless of the presence of saved
496             // settings so defaults can be applied.
497             this.columnSet.applyColumnSettings(columns);
498         });
499     }
500
501     reload() {
502         // Give the UI time to settle before reloading grid data.
503         // This can help when data retrieval depends on a value
504         // getting modified by an angular digest cycle.
505         setTimeout(() => {
506             this.pager.reset();
507             this.dataSource.reset();
508             this.dataSource.requestPage(this.pager);
509         });
510     }
511
512     // Sort the existing data source instead of requesting sorted
513     // data from the client.  Reset pager to page 1.  As with reload(),
514     // give the client a chance to setting before redisplaying.
515     sortLocal() {
516         setTimeout(() => {
517             this.pager.reset();
518             this.sortLocalData();
519             this.dataSource.requestPage(this.pager);
520         });
521     }
522
523     // Subscribe or unsubscribe to page-change events from the pager.
524     listenToPager() {
525         if (this.pageChanges) { return; }
526         this.pageChanges = this.pager.onChange$.subscribe(
527             val => this.dataSource.requestPage(this.pager));
528     }
529
530     ignorePager() {
531         if (!this.pageChanges) { return; }
532         this.pageChanges.unsubscribe();
533         this.pageChanges = null;
534     }
535
536     // Sort data in the data source array
537     sortLocalData() {
538
539         const sortDefs = this.dataSource.sort.map(sort => {
540             const def = {
541                 name: sort.name,
542                 dir: sort.dir,
543                 col: this.columnSet.getColByName(sort.name)
544             };
545
546             if (!def.col.comparator) {
547                 def.col.comparator = (a, b) => {
548                     if (a < b) { return -1; }
549                     if (a > b) { return 1; }
550                     return 0;
551                 };
552             }
553
554             return def;
555         });
556
557         this.dataSource.data.sort((rowA, rowB) => {
558
559             for (let idx = 0; idx < sortDefs.length; idx++) {
560                 const sortDef = sortDefs[idx];
561
562                 const valueA = this.getRowColumnValue(rowA, sortDef.col);
563                 const valueB = this.getRowColumnValue(rowB, sortDef.col);
564
565                 if (valueA === '' && valueB === '') { continue; }
566                 if (valueA === '' && valueB !== '') { return 1; }
567                 if (valueA !== '' && valueB === '') { return -1; }
568
569                 const diff = sortDef.col.comparator(valueA, valueB);
570                 if (diff === 0) { continue; }
571
572                 console.log(valueA, valueB, diff);
573
574                 return sortDef.dir === 'DESC' ? -diff : diff;
575             }
576
577             return 0; // No differences found.
578         });
579     }
580
581     getRowIndex(row: any): any {
582         const col = this.columnSet.indexColumn;
583         if (!col) {
584             throw new Error('grid index column required');
585         }
586         return this.getRowColumnValue(row, col);
587     }
588
589     // Returns position in the data source array of the row with
590     // the provided index.
591     getRowPosition(index: any): number {
592         // for-loop for early exit
593         for (let idx = 0; idx < this.dataSource.data.length; idx++) {
594             const row = this.dataSource.data[idx];
595             if (row !== undefined && index === this.getRowIndex(row)) {
596                 return idx;
597             }
598         }
599     }
600
601     // Return the row with the provided index.
602     getRowByIndex(index: any): any {
603         for (let idx = 0; idx < this.dataSource.data.length; idx++) {
604             const row = this.dataSource.data[idx];
605             if (row !== undefined && index === this.getRowIndex(row)) {
606                 return row;
607             }
608         }
609     }
610
611     // Returns all selected rows, regardless of whether they are
612     // currently visible in the grid display.
613     getSelectedRows(): any[] {
614         const selected = [];
615         this.rowSelector.selected().forEach(index => {
616             const row = this.getRowByIndex(index);
617             if (row) {
618                 selected.push(row);
619             }
620         });
621         return selected;
622     }
623
624     getRowColumnValue(row: any, col: GridColumn): string {
625         let val;
626         if (col.name in row) {
627             val = this.getObjectFieldValue(row, col.name);
628         } else {
629             if (col.path) {
630                 val = this.nestedItemFieldValue(row, col);
631             }
632         }
633         return this.format.transform({value: val, datatype: col.datatype});
634     }
635
636     getObjectFieldValue(obj: any, name: string): any {
637         if (typeof obj[name] === 'function') {
638             return obj[name]();
639         } else {
640             return obj[name];
641         }
642     }
643
644     nestedItemFieldValue(obj: any, col: GridColumn): string {
645
646         let idlField;
647         let idlClassDef;
648         const original = obj;
649         const steps = col.path.split('.');
650
651         for (let i = 0; i < steps.length; i++) {
652             const step = steps[i];
653
654             if (typeof obj !== 'object') {
655                 // We have run out of data to step through before
656                 // reaching the end of the path.  Conclude fleshing via
657                 // callback if provided then exit.
658                 if (col.flesher && obj !== undefined) {
659                     return col.flesher(obj, col, original);
660                 }
661                 return obj;
662             }
663
664             const class_ = obj.classname;
665             if (class_ && (idlClassDef = this.idl.classes[class_])) {
666                 idlField = idlClassDef.field_map[step];
667             }
668
669             obj = this.getObjectFieldValue(obj, step);
670         }
671
672         // We found a nested IDL object which may or may not have
673         // been configured as a top-level column.  Flesh the column
674         // metadata with our newly found IDL info.
675         if (idlField) {
676             if (!col.datatype) {
677                 col.datatype = idlField.datatype;
678             }
679             if (!col.label) {
680                 col.label = idlField.label || idlField.name;
681             }
682         }
683
684         return obj;
685     }
686
687
688     getColumnTextContent(row: any, col: GridColumn): string {
689         if (col.cellTemplate) {
690             // TODO
691             // Extract the text content from the rendered template.
692         } else {
693             return this.getRowColumnValue(row, col);
694         }
695     }
696
697     selectOneRow(index: any) {
698         this.rowSelector.clear();
699         this.rowSelector.select(index);
700         this.lastSelectedIndex = index;
701     }
702
703     // selects or deselects an item, without affecting the others.
704     // returns true if the item is selected; false if de-selected.
705     toggleSelectOneRow(index: any) {
706         if (this.rowSelector.contains(index)) {
707             this.rowSelector.deselect(index);
708             return false;
709         }
710
711         this.rowSelector.select(index);
712         return true;
713     }
714
715     selectRowByPos(pos: number) {
716         const row = this.dataSource.data[pos];
717         if (row) {
718             this.selectOneRow(this.getRowIndex(row));
719         }
720     }
721
722     selectPreviousRow() {
723         if (!this.lastSelectedIndex) { return; }
724         const pos = this.getRowPosition(this.lastSelectedIndex);
725         if (pos === this.pager.offset) {
726             this.toPrevPage().then(ok => this.selectLastRow(), err => {});
727         } else {
728             this.selectRowByPos(pos - 1);
729         }
730     }
731
732     selectNextRow() {
733         if (!this.lastSelectedIndex) { return; }
734         const pos = this.getRowPosition(this.lastSelectedIndex);
735         if (pos === (this.pager.offset + this.pager.limit - 1)) {
736             this.toNextPage().then(ok => this.selectFirstRow(), err => {});
737         } else {
738             this.selectRowByPos(pos + 1);
739         }
740     }
741
742     selectFirstRow() {
743         this.selectRowByPos(this.pager.offset);
744     }
745
746     selectLastRow() {
747         this.selectRowByPos(this.pager.offset + this.pager.limit - 1);
748     }
749
750     toPrevPage(): Promise<any> {
751         if (this.pager.isFirstPage()) {
752             return Promise.reject('on first');
753         }
754         // temp ignore pager events since we're calling requestPage manually.
755         this.ignorePager();
756         this.pager.decrement();
757         this.listenToPager();
758         return this.dataSource.requestPage(this.pager);
759     }
760
761     toNextPage(): Promise<any> {
762         if (this.pager.isLastPage()) {
763             return Promise.reject('on last');
764         }
765         // temp ignore pager events since we're calling requestPage manually.
766         this.ignorePager();
767         this.pager.increment();
768         this.listenToPager();
769         return this.dataSource.requestPage(this.pager);
770     }
771
772     getAllRows(): Promise<any> {
773         const pager = new Pager();
774         pager.offset = 0;
775         pager.limit = MAX_ALL_ROW_COUNT;
776         return this.dataSource.requestPage(pager);
777     }
778
779     // Returns a key/value pair object of visible column data as text.
780     getRowAsFlatText(row: any): any {
781         const flatRow = {};
782         this.columnSet.displayColumns().forEach(col => {
783             flatRow[col.name] =
784                 this.getColumnTextContent(row, col);
785         });
786         return flatRow;
787     }
788
789     getAllRowsAsText(): Observable<any> {
790         return Observable.create(observer => {
791             this.getAllRows().then(ok => {
792                 this.dataSource.data.forEach(row => {
793                     observer.next(this.getRowAsFlatText(row));
794                 });
795                 observer.complete();
796             });
797         });
798     }
799
800     gridToCsv(): Promise<string> {
801
802         let csvStr = '';
803         const columns = this.columnSet.displayColumns();
804
805         // CSV header
806         columns.forEach(col => {
807             csvStr += this.valueToCsv(col.label),
808             csvStr += ',';
809         });
810
811         csvStr = csvStr.replace(/,$/, '\n');
812
813         return new Promise(resolve => {
814             this.getAllRowsAsText().subscribe(
815                 row => {
816                     columns.forEach(col => {
817                         csvStr += this.valueToCsv(row[col.name]);
818                         csvStr += ',';
819                     });
820                     csvStr = csvStr.replace(/,$/, '\n');
821                 },
822                 err => {},
823                 ()  => resolve(csvStr)
824             );
825         });
826     }
827
828
829     // prepares a string for inclusion within a CSV document
830     // by escaping commas and quotes and removing newlines.
831     valueToCsv(str: string): string {
832         str = '' + str;
833         if (!str) { return ''; }
834         str = str.replace(/\n/g, '');
835         if (str.match(/\,/) || str.match(/"/)) {
836             str = str.replace(/"/g, '""');
837             str = '"' + str + '"';
838         }
839         return str;
840     }
841
842     generateColumns() {
843         if (!this.columnSet.idlClass) { return; }
844
845         const pkeyField = this.idl.classes[this.columnSet.idlClass].pkey;
846
847         // generate columns for all non-virtual fields on the IDL class
848         this.idl.classes[this.columnSet.idlClass].fields
849         .filter(field => !field.virtual)
850         .forEach(field => {
851             const col = new GridColumn();
852             col.name = field.name;
853             col.label = field.label || field.name;
854             col.idlFieldDef = field;
855             col.datatype = field.datatype;
856             col.isIndex = (field.name === pkeyField);
857             col.isAuto = true;
858             this.columnSet.add(col);
859         });
860     }
861
862     saveGridConfig(): Promise<any> {
863         if (!this.persistKey) {
864             throw new Error('Grid persistKey required to save columns');
865         }
866         const conf = new GridPersistConf();
867         conf.version = 2;
868         conf.limit = this.pager.limit;
869         conf.columns = this.columnSet.compileSaveObject();
870
871         return this.store.setItem('eg.grid.' + this.persistKey, conf);
872     }
873
874     // TODO: saveGridConfigAsOrgSetting(...)
875
876     getGridConfig(persistKey: string): Promise<GridPersistConf> {
877         if (!persistKey) { return Promise.resolve(null); }
878         return this.store.getItem('eg.grid.' + persistKey);
879     }
880 }
881
882
883 // Actions apply to specific rows
884 export class GridToolbarAction {
885     label: string;
886     action: (rows: any[]) => any;
887 }
888
889 // Buttons are global actions
890 export class GridToolbarButton {
891     label: string;
892     action: () => any;
893     disabled: boolean;
894 }
895
896 export class GridToolbarCheckbox {
897     label: string;
898     onChange: (checked: boolean) => void;
899 }
900
901 export class GridDataSource {
902
903     data: any[];
904     sort: any[];
905     allRowsRetrieved: boolean;
906     getRows: (pager: Pager, sort: any[]) => Observable<any>;
907
908     constructor() {
909         this.sort = [];
910         this.reset();
911     }
912
913     reset() {
914         this.data = [];
915         this.allRowsRetrieved = false;
916     }
917
918     // called from the template -- no data fetching
919     getPageOfRows(pager: Pager): any[] {
920         if (this.data) {
921             return this.data.slice(
922                 pager.offset, pager.limit + pager.offset
923             ).filter(row => row !== undefined);
924         }
925         return [];
926     }
927
928     // called on initial component load and user action (e.g. paging, sorting).
929     requestPage(pager: Pager): Promise<any> {
930
931         if (
932             this.getPageOfRows(pager).length === pager.limit
933             // already have all data
934             || this.allRowsRetrieved
935             // have no way to get more data.
936             || !this.getRows
937         ) {
938             return Promise.resolve();
939         }
940
941         return new Promise((resolve, reject) => {
942             let idx = pager.offset;
943             return this.getRows(pager, this.sort).subscribe(
944                 row => this.data[idx++] = row,
945                 err => {
946                     console.error(`grid getRows() error ${err}`);
947                     reject(err);
948                 },
949                 ()  => {
950                     this.checkAllRetrieved(pager, idx);
951                     resolve();
952                 }
953             );
954         });
955     }
956
957     // See if the last getRows() call resulted in the final set of data.
958     checkAllRetrieved(pager: Pager, idx: number) {
959         if (this.allRowsRetrieved) { return; }
960
961         if (idx === 0 || idx < (pager.limit + pager.offset)) {
962             // last query returned nothing or less than one page.
963             // confirm we have all of the preceding pages.
964             if (!this.data.includes(undefined)) {
965                 this.allRowsRetrieved = true;
966                 pager.resultCount = this.data.length;
967             }
968         }
969     }
970 }
971
972