2 * Collection of grid related classses and interfaces.
4 import {TemplateRef, EventEmitter, QueryList} from '@angular/core';
5 import {Observable, Subscription} from 'rxjs';
6 import {IdlService, IdlObject} from '@eg/core/idl.service';
7 import {OrgService} from '@eg/core/org.service';
8 import {ServerStoreService} from '@eg/core/server-store.service';
9 import {FormatService} from '@eg/core/format.service';
10 import {Pager} from '@eg/share/util/pager';
11 import {GridFilterControlComponent} from './grid-filter-control.component';
13 const MAX_ALL_ROW_COUNT = 10000;
15 export class GridColumn {
24 // IDL class of the object which contains this field.
25 // Not to be confused with the class of a linked object.
29 datePlusTime: boolean;
31 cellTemplate: TemplateRef<any>;
34 isDragTarget: boolean;
36 isFilterable: boolean;
38 isMultiSortable: boolean;
39 disableTooltip: boolean;
40 comparator: (valueA: any, valueB: any) => number;
42 // True if the column was automatically generated.
47 filterOperator: string;
48 filterInputDisabled: boolean;
49 filterIncludeOrgAncestors: boolean;
50 filterIncludeOrgDescendants: boolean;
52 flesher: (obj: any, col: GridColumn, item: any) => any;
54 getCellContext(row: any) {
58 userContext: this.cellContext
67 this.isFiltered = false;
68 this.filterValue = undefined;
69 this.filterOperator = '=';
70 this.filterInputDisabled = false;
71 this.filterIncludeOrgAncestors = false;
72 this.filterIncludeOrgDescendants = false;
76 export class GridColumnSet {
77 columns: GridColumn[];
79 indexColumn: GridColumn;
81 isFilterable: boolean;
82 isMultiSortable: boolean;
83 stockVisible: string[];
85 defaultHiddenFields: string[];
86 defaultVisibleFields: string[];
88 constructor(idl: IdlService, idlClass?: string) {
91 this.stockVisible = [];
92 this.idlClass = idlClass;
95 add(col: GridColumn) {
97 this.applyColumnDefaults(col);
99 if (!this.insertColumn(col)) {
100 // Column was rejected as a duplicate.
104 if (col.isIndex) { this.indexColumn = col; }
106 // track which fields are visible on page load.
108 this.stockVisible.push(col.name);
111 this.applyColumnSortability(col);
112 this.applyColumnFilterability(col);
115 // Returns true if the new column was inserted, false otherwise.
116 // Declared columns take precedence over auto-generated columns
117 // when collisions occur.
118 // Declared columns are inserted in front of auto columns.
119 insertColumn(col: GridColumn): boolean {
122 if (this.getColByName(col.name)) {
123 // New auto-generated column conflicts with existing
127 // No collisions. Add to the end of the list
128 this.columns.push(col);
133 // Adding a declared column.
136 for (let idx = 0; idx < this.columns.length; idx++) {
137 const testCol = this.columns[idx];
138 if (testCol.name === col.name) { // match found
139 if (testCol.isAuto) {
140 // new column takes precedence, remove the existing column.
141 this.columns.splice(idx, 1);
144 // New column does not take precedence. Avoid
151 // Delcared columns are inserted just before the first auto-column
152 for (let idx = 0; idx < this.columns.length; idx++) {
153 const testCol = this.columns[idx];
154 if (testCol.isAuto) {
156 this.columns.unshift(col);
158 this.columns.splice(idx, 0, col);
164 // No insertion point found. Toss the new column on the end.
165 this.columns.push(col);
169 getColByName(name: string): GridColumn {
170 return this.columns.filter(c => c.name === name)[0];
173 idlInfoFromDotpath(dotpath: string): any {
174 if (!dotpath || !this.idlClass) { return null; }
178 let idlClass = this.idl.classes[this.idlClass];
180 const pathParts = dotpath.split(/\./);
182 for (let i = 0; i < pathParts.length; i++) {
183 const part = pathParts[i];
184 idlParent = idlField;
185 idlField = idlClass.field_map[part];
188 if (idlField['class'] && (
189 idlField.datatype === 'link' ||
190 idlField.datatype === 'org_unit')) {
191 idlClass = this.idl.classes[idlField['class']];
199 idlParent: idlParent,
207 this.columns.forEach(col => {
211 col.visible = this.stockVisible.includes(col.name);
215 applyColumnDefaults(col: GridColumn) {
217 if (!col.idlFieldDef && col.path) {
218 const idlInfo = this.idlInfoFromDotpath(col.path);
220 col.idlFieldDef = idlInfo.idlField;
221 col.idlClass = idlInfo.idlClass.name;
223 col.label = col.idlFieldDef.label || col.idlFieldDef.name;
224 col.datatype = col.idlFieldDef.datatype;
229 if (!col.name) { col.name = col.path; }
230 if (!col.flex) { col.flex = 2; }
231 if (!col.align) { col.align = 'left'; }
232 if (!col.label) { col.label = col.name; }
233 if (!col.datatype) { col.datatype = 'text'; }
235 col.visible = !col.hidden;
238 applyColumnSortability(col: GridColumn) {
239 // column sortability defaults to the sortability of the column set.
240 if (col.isSortable === undefined && this.isSortable) {
241 col.isSortable = true;
244 if (col.isMultiSortable === undefined && this.isMultiSortable) {
245 col.isMultiSortable = true;
248 if (col.isMultiSortable) {
249 col.isSortable = true;
252 applyColumnFilterability(col: GridColumn) {
253 // column filterability defaults to the afilterability of the column set.
254 if (col.isFilterable === undefined && this.isFilterable) {
255 col.isFilterable = true;
259 displayColumns(): GridColumn[] {
260 return this.columns.filter(c => c.visible);
263 insertBefore(source: GridColumn, target: GridColumn) {
266 this.columns.forEach((col, idx) => {
267 if (col.name === target.name) { targetIdx = idx; }});
269 this.columns.forEach((col, idx) => {
270 if (col.name === source.name) { sourceIdx = idx; }});
272 if (sourceIdx >= 0) {
273 this.columns.splice(sourceIdx, 1);
276 this.columns.splice(targetIdx, 0, source);
279 // Move visible columns to the front of the list.
280 moveVisibleToFront() {
281 const newCols = this.displayColumns();
282 this.columns.forEach(col => {
283 if (!col.visible) { newCols.push(col); }});
284 this.columns = newCols;
287 moveColumn(col: GridColumn, diff: number) {
288 let srcIdx, targetIdx;
290 this.columns.forEach((c, i) => {
291 if (c.name === col.name) { srcIdx = i; }
294 targetIdx = srcIdx + diff;
297 } else if (targetIdx >= this.columns.length) {
298 // Target index follows the last visible column.
300 this.columns.forEach((c, idx) => {
301 if (c.visible) { lastVisible = idx; }
304 // When moving a column (down) causes one or more
305 // visible columns to shuffle forward, our column
306 // moves into the slot of the last visible column.
307 // Otherwise, put it into the slot directly following
308 // the last visible column.
309 targetIdx = srcIdx <= lastVisible ? lastVisible : lastVisible + 1;
312 // Splice column out of old position, insert at new position.
313 this.columns.splice(srcIdx, 1);
314 this.columns.splice(targetIdx, 0, col);
317 compileSaveObject(): GridColumnPersistConf[] {
318 // only store information about visible columns.
319 // scrunch the data down to just the needed info.
320 return this.displayColumns().map(col => {
321 const c: GridColumnPersistConf = {name : col.name};
322 if (col.align !== 'left') { c.align = col.align; }
323 if (col.flex !== 2) { c.flex = Number(col.flex); }
324 if (Number(col.sort)) { c.sort = Number(c.sort); }
329 applyColumnSettings(conf: GridColumnPersistConf[]) {
331 if (!conf || conf.length === 0) {
332 // No configuration is available, but we have a list of
333 // fields to show or hide by default
335 if (this.defaultVisibleFields) {
336 this.columns.forEach(col => {
337 if (this.defaultVisibleFields.includes(col.name)) {
344 } else if (this.defaultHiddenFields) {
345 this.defaultHiddenFields.forEach(name => {
346 const col = this.getColByName(name);
358 conf.forEach(colConf => {
359 const col = this.getColByName(colConf.name);
360 if (!col) { return; } // no such column in this grid.
363 if (colConf.align) { col.align = colConf.align; }
364 if (colConf.flex) { col.flex = Number(colConf.flex); }
365 if (colConf.sort) { col.sort = Number(colConf.sort); }
367 // Add to new columns array, avoid dupes.
368 if (newCols.filter(c => c.name === col.name).length === 0) {
373 // columns which are not expressed within the saved
374 // configuration are marked as non-visible and
375 // appended to the end of the new list of columns.
376 this.columns.forEach(c => {
377 if (conf.filter(cf => cf.name === c.name).length === 0) {
383 this.columns = newCols;
388 export class GridRowSelector {
389 indexes: {[string: string]: boolean};
395 // Returns true if all of the requested indexes exist in the selector.
396 contains(index: string | string[]): boolean {
397 const indexes = [].concat(index);
398 for (let i = 0; i < indexes.length; i++) { // early exit
399 if (!this.indexes[indexes[i]]) {
406 select(index: string | string[]) {
407 const indexes = [].concat(index);
408 indexes.forEach(i => this.indexes[i] = true);
411 deselect(index: string | string[]) {
412 const indexes = [].concat(index);
413 indexes.forEach(i => delete this.indexes[i]);
416 // Returns the list of selected index values.
417 // in some contexts (template checkboxes) the value for an index is
418 // set to false to deselect instead of having it removed (via deselect()).
420 return Object.keys(this.indexes).filter(
421 ind => Boolean(this.indexes[ind]));
425 return this.selected().length === 0;
433 export interface GridRowFlairEntry {
434 icon: string; // name of material icon
435 title?: string; // tooltip string
438 export class GridColumnPersistConf {
445 export class GridPersistConf {
448 columns: GridColumnPersistConf[];
451 export class GridContext {
456 isFilterable: boolean;
457 stickyGridHeader: boolean;
458 isMultiSortable: boolean;
459 useLocalSort: boolean;
461 disableMultiSelect: boolean;
462 disableSelect: boolean;
463 dataSource: GridDataSource;
464 columnSet: GridColumnSet;
465 rowSelector: GridRowSelector;
466 toolbarButtons: GridToolbarButton[];
467 toolbarCheckboxes: GridToolbarCheckbox[];
468 toolbarActions: GridToolbarAction[];
469 lastSelectedIndex: any;
470 pageChanges: Subscription;
471 rowFlairIsEnabled: boolean;
472 rowFlairCallback: (row: any) => GridRowFlairEntry;
473 rowClassCallback: (row: any) => string;
474 cellClassCallback: (row: any, col: GridColumn) => string;
475 defaultVisibleFields: string[];
476 defaultHiddenFields: string[];
477 overflowCells: boolean;
478 showLinkSelectors: boolean;
479 disablePaging: boolean;
480 showDeclaredFieldsOnly: boolean;
482 // Allow calling code to know when the select-all-rows-in-page
483 // action has occurred.
484 selectRowsInPageEmitter: EventEmitter<void>;
486 filterControls: QueryList<GridFilterControlComponent>;
488 // Services injected by our grid component
491 store: ServerStoreService;
492 format: FormatService;
497 store: ServerStoreService,
498 format: FormatService) {
503 this.format = format;
504 this.pager = new Pager();
505 this.rowSelector = new GridRowSelector();
506 this.toolbarButtons = [];
507 this.toolbarCheckboxes = [];
508 this.toolbarActions = [];
512 this.selectRowsInPageEmitter = new EventEmitter<void>();
513 this.columnSet = new GridColumnSet(this.idl, this.idlClass);
514 this.columnSet.isSortable = this.isSortable === true;
515 this.columnSet.isFilterable = this.isFilterable === true;
516 this.columnSet.isMultiSortable = this.isMultiSortable === true;
517 this.columnSet.defaultHiddenFields = this.defaultHiddenFields;
518 this.columnSet.defaultVisibleFields = this.defaultVisibleFields;
519 if (!this.pager.limit) {
520 this.pager.limit = this.disablePaging ? MAX_ALL_ROW_COUNT : 10;
522 this.generateColumns();
525 // Load initial settings and data.
527 this.applyGridConfig()
528 .then(ok => this.dataSource.requestPage(this.pager))
529 .then(ok => this.listenToPager());
536 applyGridConfig(): Promise<void> {
537 return this.getGridConfig(this.persistKey)
541 columns = conf.columns;
543 this.pager.limit = conf.limit;
547 // This is called regardless of the presence of saved
548 // settings so defaults can be applied.
549 this.columnSet.applyColumnSettings(columns);
554 // Give the UI time to settle before reloading grid data.
555 // This can help when data retrieval depends on a value
556 // getting modified by an angular digest cycle.
559 this.dataSource.reset();
560 this.dataSource.requestPage(this.pager);
564 reloadSansPagerReset() {
566 this.dataSource.reset();
567 this.dataSource.requestPage(this.pager);
571 // Sort the existing data source instead of requesting sorted
572 // data from the client. Reset pager to page 1. As with reload(),
573 // give the client a chance to setting before redisplaying.
577 this.sortLocalData();
578 this.dataSource.requestPage(this.pager);
582 // Subscribe or unsubscribe to page-change events from the pager.
584 if (this.pageChanges) { return; }
585 this.pageChanges = this.pager.onChange$.subscribe(
586 val => this.dataSource.requestPage(this.pager));
590 if (!this.pageChanges) { return; }
591 this.pageChanges.unsubscribe();
592 this.pageChanges = null;
595 // Sort data in the data source array
598 const sortDefs = this.dataSource.sort.map(sort => {
599 const column = this.columnSet.getColByName(sort.name);
607 if (!def.col.comparator) {
608 switch (def.col.datatype) {
612 def.col.comparator = (a, b) => {
615 if (a < b) { return -1; }
616 if (a > b) { return 1; }
621 def.col.comparator = (a, b) => {
622 if (a < b) { return -1; }
623 if (a > b) { return 1; }
632 this.dataSource.data.sort((rowA, rowB) => {
634 for (let idx = 0; idx < sortDefs.length; idx++) {
635 const sortDef = sortDefs[idx];
637 const valueA = this.getRowColumnValue(rowA, sortDef.col);
638 const valueB = this.getRowColumnValue(rowB, sortDef.col);
640 if (valueA === '' && valueB === '') { continue; }
641 if (valueA === '' && valueB !== '') { return 1; }
642 if (valueA !== '' && valueB === '') { return -1; }
644 const diff = sortDef.col.comparator(valueA, valueB);
645 if (diff === 0) { continue; }
647 return sortDef.dir === 'DESC' ? -diff : diff;
650 return 0; // No differences found.
654 getRowIndex(row: any): any {
655 const col = this.columnSet.indexColumn;
657 throw new Error('grid index column required');
659 return this.getRowColumnValue(row, col);
662 // Returns position in the data source array of the row with
663 // the provided index.
664 getRowPosition(index: any): number {
665 // for-loop for early exit
666 for (let idx = 0; idx < this.dataSource.data.length; idx++) {
667 const row = this.dataSource.data[idx];
668 if (row !== undefined && index === this.getRowIndex(row)) {
674 // Return the row with the provided index.
675 getRowByIndex(index: any): any {
676 for (let idx = 0; idx < this.dataSource.data.length; idx++) {
677 const row = this.dataSource.data[idx];
678 if (row !== undefined && index === this.getRowIndex(row)) {
684 // Returns all selected rows, regardless of whether they are
685 // currently visible in the grid display.
686 getSelectedRows(): any[] {
688 this.rowSelector.selected().forEach(index => {
689 const row = this.getRowByIndex(index);
697 getRowColumnValue(row: any, col: GridColumn): string {
701 val = this.nestedItemFieldValue(row, col);
702 } else if (col.name in row) {
703 val = this.getObjectFieldValue(row, col.name);
706 if (col.datatype === 'bool') {
707 // Avoid string-ifying bools so we can use an <eg-bool/>
708 // in the grid template.
712 return this.format.transform({
714 idlClass: col.idlClass,
715 idlField: col.idlFieldDef ? col.idlFieldDef.name : col.name,
716 datatype: col.datatype,
717 datePlusTime: Boolean(col.datePlusTime)
721 getObjectFieldValue(obj: any, name: string): any {
722 if (typeof obj[name] === 'function') {
729 nestedItemFieldValue(obj: any, col: GridColumn): string {
733 const original = obj;
734 const steps = col.path.split('.');
736 for (let i = 0; i < steps.length; i++) {
737 const step = steps[i];
739 if (obj === null || obj === undefined || typeof obj !== 'object') {
740 // We have run out of data to step through before
741 // reaching the end of the path. Conclude fleshing via
742 // callback if provided then exit.
743 if (col.flesher && obj !== undefined) {
744 return col.flesher(obj, col, original);
749 const class_ = obj.classname;
750 if (class_ && (idlClassDef = this.idl.classes[class_])) {
751 idlField = idlClassDef.field_map[step];
754 obj = this.getObjectFieldValue(obj, step);
757 // We found a nested IDL object which may or may not have
758 // been configured as a top-level column. Flesh the column
759 // metadata with our newly found IDL info.
762 col.datatype = idlField.datatype;
764 if (!col.idlFieldDef) {
765 idlField = col.idlFieldDef;
768 col.idlClass = idlClassDef.name;
771 col.label = idlField.label || idlField.name;
779 getColumnTextContent(row: any, col: GridColumn): string {
780 if (col.cellTemplate) {
782 // Extract the text content from the rendered template.
784 return this.getRowColumnValue(row, col);
788 selectOneRow(index: any) {
789 this.rowSelector.clear();
790 this.rowSelector.select(index);
791 this.lastSelectedIndex = index;
794 selectMultipleRows(indexes: any[]) {
795 this.rowSelector.clear();
796 this.rowSelector.select(indexes);
797 this.lastSelectedIndex = indexes[indexes.length - 1];
800 // selects or deselects an item, without affecting the others.
801 // returns true if the item is selected; false if de-selected.
802 toggleSelectOneRow(index: any) {
803 if (this.rowSelector.contains(index)) {
804 this.rowSelector.deselect(index);
808 this.rowSelector.select(index);
812 selectRowByPos(pos: number) {
813 const row = this.dataSource.data[pos];
815 this.selectOneRow(this.getRowIndex(row));
819 selectPreviousRow() {
820 if (!this.lastSelectedIndex) { return; }
821 const pos = this.getRowPosition(this.lastSelectedIndex);
822 if (pos === this.pager.offset) {
823 this.toPrevPage().then(ok => this.selectLastRow(), err => {});
825 this.selectRowByPos(pos - 1);
830 if (!this.lastSelectedIndex) { return; }
831 const pos = this.getRowPosition(this.lastSelectedIndex);
832 if (pos === (this.pager.offset + this.pager.limit - 1)) {
833 this.toNextPage().then(ok => this.selectFirstRow(), err => {});
835 this.selectRowByPos(pos + 1);
840 // Select the previous row in addition to any currently selected row.
841 // However, if the previous row is already selected, assume the user
842 // has reversed direction and now wants to de-select the last selected row.
843 selectMultiRowsPrevious() {
844 if (!this.lastSelectedIndex) { return; }
845 const pos = this.getRowPosition(this.lastSelectedIndex);
846 const selectedIndexes = this.rowSelector.selected();
848 const promise = // load the previous page of data if needed
849 (pos === this.pager.offset) ? this.toPrevPage() : Promise.resolve();
853 const row = this.dataSource.data[pos - 1];
854 const newIndex = this.getRowIndex(row);
855 if (selectedIndexes.filter(i => i === newIndex).length > 0) {
856 // Prev row is already selected. User is reversing direction.
857 this.rowSelector.deselect(this.lastSelectedIndex);
858 this.lastSelectedIndex = newIndex;
860 this.selectMultipleRows(selectedIndexes.concat(newIndex));
868 // Select the next row in addition to any currently selected row.
869 // However, if the next row is already selected, assume the user
870 // has reversed direction and wants to de-select the last selected row.
871 selectMultiRowsNext() {
872 if (!this.lastSelectedIndex) { return; }
873 const pos = this.getRowPosition(this.lastSelectedIndex);
874 const selectedIndexes = this.rowSelector.selected();
876 const promise = // load the next page of data if needed
877 (pos === (this.pager.offset + this.pager.limit - 1)) ?
878 this.toNextPage() : Promise.resolve();
882 const row = this.dataSource.data[pos + 1];
883 const newIndex = this.getRowIndex(row);
884 if (selectedIndexes.filter(i => i === newIndex).length > 0) {
885 // Next row is already selected. User is reversing direction.
886 this.rowSelector.deselect(this.lastSelectedIndex);
887 this.lastSelectedIndex = newIndex;
889 this.selectMultipleRows(selectedIndexes.concat(newIndex));
896 getFirstRowInPage(): any {
897 return this.dataSource.data[this.pager.offset];
900 getLastRowInPage(): any {
901 return this.dataSource.data[this.pager.offset + this.pager.limit - 1];
905 this.selectOneRow(this.getRowIndex(this.getFirstRowInPage()));
909 this.selectOneRow(this.getRowIndex(this.getLastRowInPage()));
913 const rows = this.dataSource.getPageOfRows(this.pager);
914 const indexes = rows.map(r => this.getRowIndex(r));
915 this.rowSelector.select(indexes);
916 this.selectRowsInPageEmitter.emit();
919 toPrevPage(): Promise<any> {
920 if (this.pager.isFirstPage()) {
921 return Promise.reject('on first');
923 // temp ignore pager events since we're calling requestPage manually.
925 this.pager.decrement();
926 this.listenToPager();
927 return this.dataSource.requestPage(this.pager);
930 toNextPage(): Promise<any> {
931 if (this.pager.isLastPage()) {
932 return Promise.reject('on last');
934 // temp ignore pager events since we're calling requestPage manually.
936 this.pager.increment();
937 this.listenToPager();
938 return this.dataSource.requestPage(this.pager);
941 getAllRows(): Promise<any> {
942 const pager = new Pager();
944 pager.limit = MAX_ALL_ROW_COUNT;
945 return this.dataSource.requestPage(pager);
948 // Returns a key/value pair object of visible column data as text.
949 getRowAsFlatText(row: any): any {
951 this.columnSet.displayColumns().forEach(col => {
953 this.getColumnTextContent(row, col);
958 getAllRowsAsText(): Observable<any> {
959 return Observable.create(observer => {
960 this.getAllRows().then(ok => {
961 this.dataSource.data.forEach(row => {
962 observer.next(this.getRowAsFlatText(row));
969 removeFilters(): void {
970 this.dataSource.filters = {};
971 this.columnSet.displayColumns().forEach(col => { col.removeFilter(); });
972 this.filterControls.forEach(ctl => ctl.reset());
975 filtersSet(): boolean {
976 return Object.keys(this.dataSource.filters).length > 0;
979 gridToCsv(): Promise<string> {
982 const columns = this.columnSet.displayColumns();
985 columns.forEach(col => {
986 csvStr += this.valueToCsv(col.label),
990 csvStr = csvStr.replace(/,$/, '\n');
992 return new Promise(resolve => {
993 this.getAllRowsAsText().subscribe(
995 columns.forEach(col => {
996 csvStr += this.valueToCsv(row[col.name]);
999 csvStr = csvStr.replace(/,$/, '\n');
1002 () => resolve(csvStr)
1008 // prepares a string for inclusion within a CSV document
1009 // by escaping commas and quotes and removing newlines.
1010 valueToCsv(str: string): string {
1012 if (!str) { return ''; }
1013 str = str.replace(/\n/g, '');
1014 if (str.match(/\,/) || str.match(/"/)) {
1015 str = str.replace(/"/g, '""');
1016 str = '"' + str + '"';
1022 if (!this.columnSet.idlClass) { return; }
1024 const pkeyField = this.idl.classes[this.columnSet.idlClass].pkey;
1026 // generate columns for all non-virtual fields on the IDL class
1027 this.idl.classes[this.columnSet.idlClass].fields
1028 .filter(field => !field.virtual)
1030 const col = new GridColumn();
1031 col.name = field.name;
1032 col.label = field.label || field.name;
1033 col.idlFieldDef = field;
1034 col.idlClass = this.columnSet.idlClass;
1035 col.datatype = field.datatype;
1036 col.isIndex = (field.name === pkeyField);
1039 if (this.showLinkSelectors) {
1040 const selector = this.idl.getLinkSelector(
1041 this.columnSet.idlClass, field.name);
1043 col.path = field.name + '.' + selector;
1047 if (this.showDeclaredFieldsOnly) {
1051 this.columnSet.add(col);
1055 saveGridConfig(): Promise<any> {
1056 if (!this.persistKey) {
1057 throw new Error('Grid persistKey required to save columns');
1059 const conf = new GridPersistConf();
1061 conf.limit = this.pager.limit;
1062 conf.columns = this.columnSet.compileSaveObject();
1064 return this.store.setItem('eg.grid.' + this.persistKey, conf);
1067 // TODO: saveGridConfigAsOrgSetting(...)
1069 getGridConfig(persistKey: string): Promise<GridPersistConf> {
1070 if (!persistKey) { return Promise.resolve(null); }
1071 return this.store.getItem('eg.grid.' + persistKey);
1076 // Actions apply to specific rows
1077 export class GridToolbarAction {
1079 onClick: EventEmitter<any []>;
1080 action: (rows: any[]) => any; // DEPRECATED
1083 isGroup: boolean; // used for group placeholder entries
1084 disableOnRows: (rows: any[]) => boolean;
1087 // Buttons are global actions
1088 export class GridToolbarButton {
1090 onClick: EventEmitter<any []>;
1091 action: () => any; // DEPRECATED
1095 export class GridToolbarCheckbox {
1098 onChange: EventEmitter<boolean>;
1101 export class GridDataSource {
1106 allRowsRetrieved: boolean;
1107 requestingData: boolean;
1108 getRows: (pager: Pager, sort: any[]) => Observable<any>;
1118 this.allRowsRetrieved = false;
1121 // called from the template -- no data fetching
1122 getPageOfRows(pager: Pager): any[] {
1124 return this.data.slice(
1125 pager.offset, pager.limit + pager.offset
1126 ).filter(row => row !== undefined);
1131 // called on initial component load and user action (e.g. paging, sorting).
1132 requestPage(pager: Pager): Promise<any> {
1135 this.getPageOfRows(pager).length === pager.limit
1136 // already have all data
1137 || this.allRowsRetrieved
1138 // have no way to get more data.
1141 return Promise.resolve();
1144 // If we have to call out for data, set inFetch
1145 this.requestingData = true;
1147 return new Promise((resolve, reject) => {
1148 let idx = pager.offset;
1149 return this.getRows(pager, this.sort).subscribe(
1151 this.data[idx++] = row;
1152 this.requestingData = false;
1155 console.error(`grid getRows() error ${err}`);
1159 this.checkAllRetrieved(pager, idx);
1160 this.requestingData = false;
1167 // See if the last getRows() call resulted in the final set of data.
1168 checkAllRetrieved(pager: Pager, idx: number) {
1169 if (this.allRowsRetrieved) { return; }
1171 if (idx === 0 || idx < (pager.limit + pager.offset)) {
1172 // last query returned nothing or less than one page.
1173 // confirm we have all of the preceding pages.
1174 if (!this.data.includes(undefined)) {
1175 this.allRowsRetrieved = true;
1176 pager.resultCount = this.data.length;