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 timezoneContextOrg: number;
32 cellTemplate: TemplateRef<any>;
36 isDragTarget: boolean;
38 isFilterable: boolean;
40 isMultiSortable: boolean;
41 disableTooltip: boolean;
42 asyncSupportsEmptyTermClick: boolean;
43 comparator: (valueA: any, valueB: any) => number;
45 // True if the column was automatically generated.
50 filterOperator: string;
51 filterInputDisabled: boolean;
52 filterIncludeOrgAncestors: boolean;
53 filterIncludeOrgDescendants: boolean;
55 flesher: (obj: any, col: GridColumn, item: any) => any;
57 getCellContext(row: any) {
61 userContext: this.cellContext
70 this.isFiltered = false;
71 this.filterValue = undefined;
72 this.filterOperator = '=';
73 this.filterInputDisabled = false;
74 this.filterIncludeOrgAncestors = false;
75 this.filterIncludeOrgDescendants = false;
79 export class GridColumnSet {
80 columns: GridColumn[];
82 indexColumn: GridColumn;
84 isFilterable: boolean;
85 isMultiSortable: boolean;
86 stockVisible: string[];
88 defaultHiddenFields: string[];
89 defaultVisibleFields: string[];
91 constructor(idl: IdlService, idlClass?: string) {
94 this.stockVisible = [];
95 this.idlClass = idlClass;
98 add(col: GridColumn) {
100 this.applyColumnDefaults(col);
102 if (!this.insertColumn(col)) {
103 // Column was rejected as a duplicate.
107 if (col.isIndex) { this.indexColumn = col; }
109 // track which fields are visible on page load.
111 this.stockVisible.push(col.name);
114 this.applyColumnSortability(col);
115 this.applyColumnFilterability(col);
118 // Returns true if the new column was inserted, false otherwise.
119 // Declared columns take precedence over auto-generated columns
120 // when collisions occur.
121 // Declared columns are inserted in front of auto columns.
122 insertColumn(col: GridColumn): boolean {
125 if (this.getColByName(col.name)) {
126 // New auto-generated column conflicts with existing
130 // No collisions. Add to the end of the list
131 this.columns.push(col);
136 // Adding a declared column.
139 for (let idx = 0; idx < this.columns.length; idx++) {
140 const testCol = this.columns[idx];
141 if (testCol.name === col.name) { // match found
142 if (testCol.isAuto) {
143 // new column takes precedence, remove the existing column.
144 this.columns.splice(idx, 1);
147 // New column does not take precedence. Avoid
154 // Delcared columns are inserted just before the first auto-column
155 for (let idx = 0; idx < this.columns.length; idx++) {
156 const testCol = this.columns[idx];
157 if (testCol.isAuto) {
159 this.columns.unshift(col);
161 this.columns.splice(idx, 0, col);
167 // No insertion point found. Toss the new column on the end.
168 this.columns.push(col);
172 getColByName(name: string): GridColumn {
173 return this.columns.filter(c => c.name === name)[0];
176 idlInfoFromDotpath(dotpath: string): any {
177 if (!dotpath || !this.idlClass) { return null; }
182 let nextIdlClass = this.idl.classes[this.idlClass];
184 const pathParts = dotpath.split(/\./);
186 for (let i = 0; i < pathParts.length; i++) {
188 const part = pathParts[i];
189 idlParent = idlField;
190 idlClass = nextIdlClass;
191 idlField = idlClass.field_map[part];
193 if (!idlField) { return null; } // invalid IDL path
195 if (i === pathParts.length - 1) {
196 // No more links to process.
200 if (idlField['class'] && (
201 idlField.datatype === 'link' ||
202 idlField.datatype === 'org_unit')) {
203 // The link class on the current field refers to the
204 // class of the link destination, not the current field.
205 // Mark it for processing during the next iteration.
206 nextIdlClass = this.idl.classes[idlField['class']];
211 idlParent: idlParent,
219 this.columns.forEach(col => {
223 col.visible = this.stockVisible.includes(col.name);
227 applyColumnDefaults(col: GridColumn) {
229 if (!col.idlFieldDef) {
230 const idlInfo = this.idlInfoFromDotpath(col.path || col.name);
232 col.idlFieldDef = idlInfo.idlField;
233 col.idlClass = idlInfo.idlClass.name;
235 col.datatype = col.idlFieldDef.datatype;
238 col.label = col.idlFieldDef.label || col.idlFieldDef.name;
243 if (!col.name) { col.name = col.path; }
244 if (!col.flex) { col.flex = 2; }
245 if (!col.align) { col.align = 'left'; }
246 if (!col.label) { col.label = col.name; }
247 if (!col.datatype) { col.datatype = 'text'; }
249 col.visible = !col.hidden;
252 applyColumnSortability(col: GridColumn) {
253 // column sortability defaults to the sortability of the column set.
254 if (col.isSortable === undefined && this.isSortable) {
255 col.isSortable = true;
258 if (col.isMultiSortable === undefined && this.isMultiSortable) {
259 col.isMultiSortable = true;
262 if (col.isMultiSortable) {
263 col.isSortable = true;
266 applyColumnFilterability(col: GridColumn) {
267 // column filterability defaults to the afilterability of the column set.
268 if (col.isFilterable === undefined && this.isFilterable) {
269 col.isFilterable = true;
273 displayColumns(): GridColumn[] {
274 return this.columns.filter(c => c.visible);
277 // Sorted visible columns followed by sorted non-visible columns.
278 // Note we don't sort this.columns directly as it would impact
279 // grid column display ordering.
280 sortForColPicker(): GridColumn[] {
281 const visible = this.columns.filter(c => c.visible);
282 const invisible = this.columns.filter(c => !c.visible);
284 visible.sort((a, b) => a.label < b.label ? -1 : 1);
285 invisible.sort((a, b) => a.label < b.label ? -1 : 1);
287 return visible.concat(invisible);
290 insertBefore(source: GridColumn, target: GridColumn) {
293 this.columns.forEach((col, idx) => {
294 if (col.name === target.name) { targetIdx = idx; }});
296 this.columns.forEach((col, idx) => {
297 if (col.name === source.name) { sourceIdx = idx; }});
299 if (sourceIdx >= 0) {
300 this.columns.splice(sourceIdx, 1);
303 this.columns.splice(targetIdx, 0, source);
306 // Move visible columns to the front of the list.
307 moveVisibleToFront() {
308 const newCols = this.displayColumns();
309 this.columns.forEach(col => {
310 if (!col.visible) { newCols.push(col); }});
311 this.columns = newCols;
314 moveColumn(col: GridColumn, diff: number) {
315 let srcIdx, targetIdx;
317 this.columns.forEach((c, i) => {
318 if (c.name === col.name) { srcIdx = i; }
321 targetIdx = srcIdx + diff;
324 } else if (targetIdx >= this.columns.length) {
325 // Target index follows the last visible column.
327 this.columns.forEach((c, idx) => {
328 if (c.visible) { lastVisible = idx; }
331 // When moving a column (down) causes one or more
332 // visible columns to shuffle forward, our column
333 // moves into the slot of the last visible column.
334 // Otherwise, put it into the slot directly following
335 // the last visible column.
336 targetIdx = srcIdx <= lastVisible ? lastVisible : lastVisible + 1;
339 // Splice column out of old position, insert at new position.
340 this.columns.splice(srcIdx, 1);
341 this.columns.splice(targetIdx, 0, col);
344 compileSaveObject(): GridColumnPersistConf[] {
345 // only store information about visible columns.
346 // scrunch the data down to just the needed info.
347 return this.displayColumns().map(col => {
348 const c: GridColumnPersistConf = {name : col.name};
349 if (col.align !== 'left') { c.align = col.align; }
350 if (col.flex !== 2) { c.flex = Number(col.flex); }
351 if (Number(col.sort)) { c.sort = Number(col.sort); }
356 applyColumnSettings(conf: GridColumnPersistConf[]) {
358 if (!conf || conf.length === 0) {
359 // No configuration is available, but we have a list of
360 // fields to show or hide by default
362 if (this.defaultVisibleFields) {
363 this.columns.forEach(col => {
364 if (this.defaultVisibleFields.includes(col.name)) {
371 } else if (this.defaultHiddenFields) {
372 this.defaultHiddenFields.forEach(name => {
373 const col = this.getColByName(name);
385 conf.forEach(colConf => {
386 const col = this.getColByName(colConf.name);
387 if (!col) { return; } // no such column in this grid.
390 if (colConf.align) { col.align = colConf.align; }
391 if (colConf.flex) { col.flex = Number(colConf.flex); }
392 if (colConf.sort) { col.sort = Number(colConf.sort); }
394 // Add to new columns array, avoid dupes.
395 if (newCols.filter(c => c.name === col.name).length === 0) {
400 // columns which are not expressed within the saved
401 // configuration are marked as non-visible and
402 // appended to the end of the new list of columns.
403 this.columns.forEach(c => {
404 if (conf.filter(cf => cf.name === c.name).length === 0) {
410 this.columns = newCols;
414 // Maps colunm names to functions which return plain text values for
415 // each mapped column on a given row. This is primarily useful for
416 // generating print-friendly content for grid cells rendered via
419 // USAGE NOTE: Since a cellTemplate can be passed arbitrary context
420 // but a GridCellTextGenerator only gets the row object,
421 // if it's important to include content that's not available
422 // by default in the row object, you may want to stick
423 // it in the row object as an additional attribute.
425 export interface GridCellTextGenerator {
426 [columnName: string]: (row: any) => string;
429 export class GridRowSelector {
430 indexes: {[string: string]: boolean};
436 // Returns true if all of the requested indexes exist in the selector.
437 contains(index: string | string[]): boolean {
438 const indexes = [].concat(index);
439 for (let i = 0; i < indexes.length; i++) { // early exit
440 if (!this.indexes[indexes[i]]) {
447 select(index: string | string[]) {
448 const indexes = [].concat(index);
449 indexes.forEach(i => this.indexes[i] = true);
452 deselect(index: string | string[]) {
453 const indexes = [].concat(index);
454 indexes.forEach(i => delete this.indexes[i]);
457 // Returns the list of selected index values.
458 // In some contexts (template checkboxes) the value for an index is
459 // set to false to deselect instead of having it removed (via deselect()).
460 // NOTE GridRowSelector has no knowledge of when a row is no longer
461 // present in the grid. Use GridContext.getSelectedRows() to get
462 // list of selected rows that are still present in the grid.
464 return Object.keys(this.indexes).filter(
465 ind => Boolean(this.indexes[ind]));
469 return this.selected().length === 0;
477 export interface GridRowFlairEntry {
478 icon: string; // name of material icon
479 title?: string; // tooltip string
482 export class GridColumnPersistConf {
489 export class GridPersistConf {
492 columns: GridColumnPersistConf[];
493 hideToolbarActions: string[];
496 export class GridContext {
501 isFilterable: boolean;
502 stickyGridHeader: boolean;
503 isMultiSortable: boolean;
504 useLocalSort: boolean;
506 disableMultiSelect: boolean;
507 disableSelect: boolean;
508 dataSource: GridDataSource;
509 columnSet: GridColumnSet;
510 autoGeneratedColumnOrder: string;
511 rowSelector: GridRowSelector;
512 toolbarButtons: GridToolbarButton[];
513 toolbarCheckboxes: GridToolbarCheckbox[];
514 toolbarActions: GridToolbarAction[];
515 lastSelectedIndex: any;
516 pageChanges: Subscription;
517 rowFlairIsEnabled: boolean;
518 rowFlairCallback: (row: any) => GridRowFlairEntry;
519 rowClassCallback: (row: any) => string;
520 cellClassCallback: (row: any, col: GridColumn) => string;
521 defaultVisibleFields: string[];
522 defaultHiddenFields: string[];
523 ignoredFields: string[];
524 overflowCells: boolean;
525 disablePaging: boolean;
526 showDeclaredFieldsOnly: boolean;
527 cellTextGenerator: GridCellTextGenerator;
529 // Allow calling code to know when the select-all-rows-in-page
530 // action has occurred.
531 selectRowsInPageEmitter: EventEmitter<void>;
533 filterControls: QueryList<GridFilterControlComponent>;
535 // Services injected by our grid component
538 store: ServerStoreService;
539 format: FormatService;
544 store: ServerStoreService,
545 format: FormatService) {
550 this.format = format;
551 this.pager = new Pager();
552 this.rowSelector = new GridRowSelector();
553 this.toolbarButtons = [];
554 this.toolbarCheckboxes = [];
555 this.toolbarActions = [];
559 this.selectRowsInPageEmitter = new EventEmitter<void>();
560 this.columnSet = new GridColumnSet(this.idl, this.idlClass);
561 this.columnSet.isSortable = this.isSortable === true;
562 this.columnSet.isFilterable = this.isFilterable === true;
563 this.columnSet.isMultiSortable = this.isMultiSortable === true;
564 this.columnSet.defaultHiddenFields = this.defaultHiddenFields;
565 this.columnSet.defaultVisibleFields = this.defaultVisibleFields;
566 if (!this.pager.limit) {
567 this.pager.limit = this.disablePaging ? MAX_ALL_ROW_COUNT : 10;
569 this.generateColumns();
572 // Load initial settings and data.
574 this.applyGridConfig()
575 .then(ok => this.dataSource.requestPage(this.pager))
576 .then(ok => this.listenToPager());
583 applyGridConfig(): Promise<void> {
584 return this.getGridConfig(this.persistKey)
588 columns = conf.columns;
589 if (conf.limit && !this.disablePaging) {
590 this.pager.limit = conf.limit;
592 this.applyToolbarActionVisibility(conf.hideToolbarActions);
595 // This is called regardless of the presence of saved
596 // settings so defaults can be applied.
597 this.columnSet.applyColumnSettings(columns);
601 applyToolbarActionVisibility(hidden: string[]) {
602 if (!hidden || hidden.length === 0) { return; }
605 this.toolbarActions.forEach(action => {
606 if (action.isGroup) {
608 } else if (!action.isSeparator) {
609 action.hidden = hidden.includes(action.label);
613 // If all actions in a group are hidden, hide the group as well.
614 // Note the group may be marked as hidden in the configuration,
615 // but the addition of new entries within a group should cause
616 // it to be visible again.
617 groups.forEach(group => {
618 const visible = this.toolbarActions
619 .filter(action => action.group === group.label && !action.hidden);
620 group.hidden = visible.length === 0;
625 // Give the UI time to settle before reloading grid data.
626 // This can help when data retrieval depends on a value
627 // getting modified by an angular digest cycle.
630 this.dataSource.reset();
631 this.dataSource.requestPage(this.pager);
635 reloadWithoutPagerReset() {
637 this.dataSource.reset();
638 this.dataSource.requestPage(this.pager);
642 // Sort the existing data source instead of requesting sorted
643 // data from the client. Reset pager to page 1. As with reload(),
644 // give the client a chance to setting before redisplaying.
648 this.sortLocalData();
649 this.dataSource.requestPage(this.pager);
653 // Subscribe or unsubscribe to page-change events from the pager.
655 if (this.pageChanges) { return; }
656 this.pageChanges = this.pager.onChange$.subscribe(
657 val => this.dataSource.requestPage(this.pager));
661 if (!this.pageChanges) { return; }
662 this.pageChanges.unsubscribe();
663 this.pageChanges = null;
666 // Sort data in the data source array
669 const sortDefs = this.dataSource.sort.map(sort => {
670 const column = this.columnSet.getColByName(sort.name);
678 if (!def.col.comparator) {
679 switch (def.col.datatype) {
683 def.col.comparator = (a, b) => {
686 if (a < b) { return -1; }
687 if (a > b) { return 1; }
692 def.col.comparator = (a, b) => {
693 if (a < b) { return -1; }
694 if (a > b) { return 1; }
703 this.dataSource.data.sort((rowA, rowB) => {
705 for (let idx = 0; idx < sortDefs.length; idx++) {
706 const sortDef = sortDefs[idx];
708 const valueA = this.getRowColumnValue(rowA, sortDef.col);
709 const valueB = this.getRowColumnValue(rowB, sortDef.col);
711 if (valueA === '' && valueB === '') { continue; }
712 if (valueA === '' && valueB !== '') { return 1; }
713 if (valueA !== '' && valueB === '') { return -1; }
715 const diff = sortDef.col.comparator(valueA, valueB);
716 if (diff === 0) { continue; }
718 return sortDef.dir === 'DESC' ? -diff : diff;
721 return 0; // No differences found.
725 getRowIndex(row: any): any {
726 const col = this.columnSet.indexColumn;
728 throw new Error('grid index column required');
730 return this.getRowColumnValue(row, col);
733 // Returns position in the data source array of the row with
734 // the provided index.
735 getRowPosition(index: any): number {
736 // for-loop for early exit
737 for (let idx = 0; idx < this.dataSource.data.length; idx++) {
738 const row = this.dataSource.data[idx];
739 if (row !== undefined && index === this.getRowIndex(row)) {
745 // Return the row with the provided index.
746 getRowByIndex(index: any): any {
747 for (let idx = 0; idx < this.dataSource.data.length; idx++) {
748 const row = this.dataSource.data[idx];
749 if (row !== undefined && index === this.getRowIndex(row)) {
755 // Returns all selected rows, regardless of whether they are
756 // currently visible in the grid display.
757 // De-selects previously selected rows which are no longer
758 // present in the grid.
759 getSelectedRows(): any[] {
763 this.rowSelector.selected().forEach(index => {
764 const row = this.getRowByIndex(index);
772 this.rowSelector.deselect(deleted);
776 rowIsSelected(row: any): boolean {
777 const index = this.getRowIndex(row);
778 return this.rowSelector.selected().filter(
783 getRowColumnValue(row: any, col: GridColumn): string {
787 val = this.nestedItemFieldValue(row, col);
788 } else if (col.name in row) {
789 val = this.getObjectFieldValue(row, col.name);
792 if (col.datatype === 'bool') {
793 // Avoid string-ifying bools so we can use an <eg-bool/>
794 // in the grid template.
798 return this.format.transform({
800 idlClass: col.idlClass,
801 idlField: col.idlFieldDef ? col.idlFieldDef.name : col.name,
802 datatype: col.datatype,
803 datePlusTime: Boolean(col.datePlusTime),
804 timezoneContextOrg: Number(col.timezoneContextOrg)
808 getObjectFieldValue(obj: any, name: string): any {
809 if (typeof obj[name] === 'function') {
816 nestedItemFieldValue(obj: any, col: GridColumn): string {
820 const original = obj;
821 const steps = col.path.split('.');
823 for (let i = 0; i < steps.length; i++) {
824 const step = steps[i];
826 if (obj === null || obj === undefined || typeof obj !== 'object') {
827 // We have run out of data to step through before
828 // reaching the end of the path. Conclude fleshing via
829 // callback if provided then exit.
830 if (col.flesher && obj !== undefined) {
831 return col.flesher(obj, col, original);
836 const class_ = obj.classname;
837 if (class_ && (idlClassDef = this.idl.classes[class_])) {
838 idlField = idlClassDef.field_map[step];
841 obj = this.getObjectFieldValue(obj, step);
844 // We found a nested IDL object which may or may not have
845 // been configured as a top-level column. Flesh the column
846 // metadata with our newly found IDL info.
849 col.datatype = idlField.datatype;
851 if (!col.idlFieldDef) {
852 idlField = col.idlFieldDef;
855 col.idlClass = idlClassDef.name;
858 col.label = idlField.label || idlField.name;
866 getColumnTextContent(row: any, col: GridColumn): string {
867 if (this.columnHasTextGenerator(col)) {
868 const str = this.cellTextGenerator[col.name](row);
869 return (str === null || str === undefined) ? '' : str;
871 if (col.cellTemplate) {
872 return ''; // avoid 'undefined' values
874 return this.getRowColumnValue(row, col);
879 selectOneRow(index: any) {
880 this.rowSelector.clear();
881 this.rowSelector.select(index);
882 this.lastSelectedIndex = index;
885 selectMultipleRows(indexes: any[]) {
886 this.rowSelector.clear();
887 this.rowSelector.select(indexes);
888 this.lastSelectedIndex = indexes[indexes.length - 1];
891 // selects or deselects an item, without affecting the others.
892 // returns true if the item is selected; false if de-selected.
893 toggleSelectOneRow(index: any) {
894 if (this.rowSelector.contains(index)) {
895 this.rowSelector.deselect(index);
899 this.rowSelector.select(index);
900 this.lastSelectedIndex = index;
904 selectRowByPos(pos: number) {
905 const row = this.dataSource.data[pos];
907 this.selectOneRow(this.getRowIndex(row));
911 selectPreviousRow() {
912 if (!this.lastSelectedIndex) { return; }
913 const pos = this.getRowPosition(this.lastSelectedIndex);
914 if (pos === this.pager.offset) {
915 this.toPrevPage().then(ok => this.selectLastRow(), err => {});
917 this.selectRowByPos(pos - 1);
922 if (!this.lastSelectedIndex) { return; }
923 const pos = this.getRowPosition(this.lastSelectedIndex);
924 if (pos === (this.pager.offset + this.pager.limit - 1)) {
925 this.toNextPage().then(ok => this.selectFirstRow(), err => {});
927 this.selectRowByPos(pos + 1);
932 // Select the previous row in addition to any currently selected row.
933 // However, if the previous row is already selected, assume the user
934 // has reversed direction and now wants to de-select the last selected row.
935 selectMultiRowsPrevious() {
936 if (!this.lastSelectedIndex) { return; }
937 const pos = this.getRowPosition(this.lastSelectedIndex);
938 const selectedIndexes = this.rowSelector.selected();
940 const promise = // load the previous page of data if needed
941 (pos === this.pager.offset) ? this.toPrevPage() : Promise.resolve();
945 const row = this.dataSource.data[pos - 1];
946 const newIndex = this.getRowIndex(row);
947 if (selectedIndexes.filter(i => i === newIndex).length > 0) {
948 // Prev row is already selected. User is reversing direction.
949 this.rowSelector.deselect(this.lastSelectedIndex);
950 this.lastSelectedIndex = newIndex;
952 this.selectMultipleRows(selectedIndexes.concat(newIndex));
959 // Select all rows between the previously selected row and
960 // the provided row, including the provided row.
961 // This is additive only -- rows are never de-selected.
962 selectRowRange(index: any) {
964 if (!this.lastSelectedIndex) {
965 this.selectOneRow(index);
969 const next = this.getRowPosition(index);
970 const prev = this.getRowPosition(this.lastSelectedIndex);
971 const start = Math.min(prev, next);
972 const end = Math.max(prev, next);
974 for (let idx = start; idx <= end; idx++) {
975 const row = this.dataSource.data[idx];
977 this.rowSelector.select(this.getRowIndex(row));
981 this.lastSelectedIndex = index;
985 // Select the next row in addition to any currently selected row.
986 // However, if the next row is already selected, assume the user
987 // has reversed direction and wants to de-select the last selected row.
988 selectMultiRowsNext() {
989 if (!this.lastSelectedIndex) { return; }
990 const pos = this.getRowPosition(this.lastSelectedIndex);
991 const selectedIndexes = this.rowSelector.selected();
993 const promise = // load the next page of data if needed
994 (pos === (this.pager.offset + this.pager.limit - 1)) ?
995 this.toNextPage() : Promise.resolve();
999 const row = this.dataSource.data[pos + 1];
1000 const newIndex = this.getRowIndex(row);
1001 if (selectedIndexes.filter(i => i === newIndex).length > 0) {
1002 // Next row is already selected. User is reversing direction.
1003 this.rowSelector.deselect(this.lastSelectedIndex);
1004 this.lastSelectedIndex = newIndex;
1006 this.selectMultipleRows(selectedIndexes.concat(newIndex));
1013 getFirstRowInPage(): any {
1014 return this.dataSource.data[this.pager.offset];
1017 getLastRowInPage(): any {
1018 return this.dataSource.data[this.pager.offset + this.pager.limit - 1];
1022 this.selectOneRow(this.getRowIndex(this.getFirstRowInPage()));
1026 this.selectOneRow(this.getRowIndex(this.getLastRowInPage()));
1029 selectRowsInPage() {
1030 const rows = this.dataSource.getPageOfRows(this.pager);
1031 const indexes = rows.map(r => this.getRowIndex(r));
1032 this.rowSelector.select(indexes);
1033 this.selectRowsInPageEmitter.emit();
1036 toPrevPage(): Promise<any> {
1037 if (this.pager.isFirstPage()) {
1038 return Promise.reject('on first');
1040 // temp ignore pager events since we're calling requestPage manually.
1042 this.pager.decrement();
1043 this.listenToPager();
1044 return this.dataSource.requestPage(this.pager);
1047 toNextPage(): Promise<any> {
1048 if (this.pager.isLastPage()) {
1049 return Promise.reject('on last');
1051 // temp ignore pager events since we're calling requestPage manually.
1053 this.pager.increment();
1054 this.listenToPager();
1055 return this.dataSource.requestPage(this.pager);
1058 getAllRows(): Promise<any> {
1059 const pager = new Pager();
1061 pager.limit = MAX_ALL_ROW_COUNT;
1062 return this.dataSource.requestPage(pager);
1065 // Returns a key/value pair object of visible column data as text.
1066 getRowAsFlatText(row: any): any {
1068 this.columnSet.displayColumns().forEach(col => {
1070 this.getColumnTextContent(row, col);
1075 getAllRowsAsText(): Observable<any> {
1076 return Observable.create(observer => {
1077 this.getAllRows().then(ok => {
1078 this.dataSource.data.forEach(row => {
1079 observer.next(this.getRowAsFlatText(row));
1081 observer.complete();
1086 removeFilters(): void {
1087 this.dataSource.filters = {};
1088 this.columnSet.displayColumns().forEach(col => { col.removeFilter(); });
1089 this.filterControls.forEach(ctl => ctl.reset());
1092 filtersSet(): boolean {
1093 return Object.keys(this.dataSource.filters).length > 0;
1096 gridToCsv(): Promise<string> {
1099 const columns = this.columnSet.displayColumns();
1102 columns.forEach(col => {
1103 csvStr += this.valueToCsv(col.label),
1107 csvStr = csvStr.replace(/,$/, '\n');
1109 return new Promise(resolve => {
1110 this.getAllRowsAsText().subscribe(
1112 columns.forEach(col => {
1113 csvStr += this.valueToCsv(row[col.name]);
1116 csvStr = csvStr.replace(/,$/, '\n');
1119 () => resolve(csvStr)
1125 // prepares a string for inclusion within a CSV document
1126 // by escaping commas and quotes and removing newlines.
1127 valueToCsv(str: string): string {
1129 if (!str) { return ''; }
1130 str = str.replace(/\n/g, '');
1131 if (str.match(/\,/) || str.match(/"/)) {
1132 str = str.replace(/"/g, '""');
1133 str = '"' + str + '"';
1139 if (!this.columnSet.idlClass) { return; }
1141 const pkeyField = this.idl.classes[this.columnSet.idlClass].pkey;
1142 const specifiedColumnOrder = this.autoGeneratedColumnOrder ?
1143 this.autoGeneratedColumnOrder.split(/,/) : [];
1145 // generate columns for all non-virtual fields on the IDL class
1146 const fields = this.idl.classes[this.columnSet.idlClass].fields
1147 .filter(field => !field.virtual);
1149 const sortedFields = this.autoGeneratedColumnOrder ?
1150 this.idl.sortIdlFields(fields, this.autoGeneratedColumnOrder.split(/,/)) :
1153 sortedFields.forEach(field => {
1154 if (!this.ignoredFields.filter(ignored => ignored === field.name).length) {
1155 const col = new GridColumn();
1156 col.name = field.name;
1157 col.label = field.label || field.name;
1158 col.idlFieldDef = field;
1159 col.idlClass = this.columnSet.idlClass;
1160 col.datatype = field.datatype;
1161 col.isIndex = (field.name === pkeyField);
1164 if (this.showDeclaredFieldsOnly) {
1168 this.columnSet.add(col);
1173 saveGridConfig(): Promise<any> {
1174 if (!this.persistKey) {
1175 throw new Error('Grid persistKey required to save columns');
1177 const conf = new GridPersistConf();
1179 conf.limit = this.pager.limit;
1180 conf.columns = this.columnSet.compileSaveObject();
1182 // Avoid persisting group visibility since that may change
1183 // with the addition of new columns. Always calculate that
1185 conf.hideToolbarActions = this.toolbarActions
1186 .filter(action => !action.isGroup && action.hidden)
1187 .map(action => action.label);
1189 return this.store.setItem('eg.grid.' + this.persistKey, conf);
1192 // TODO: saveGridConfigAsOrgSetting(...)
1194 getGridConfig(persistKey: string): Promise<GridPersistConf> {
1195 if (!persistKey) { return Promise.resolve(null); }
1196 return this.store.getItem('eg.grid.' + persistKey);
1199 columnHasTextGenerator(col: GridColumn): boolean {
1200 return this.cellTextGenerator && col.name in this.cellTextGenerator;
1205 // Actions apply to specific rows
1206 export class GridToolbarAction {
1208 onClick: EventEmitter<any []>;
1209 action: (rows: any[]) => any; // DEPRECATED
1212 isGroup: boolean; // used for group placeholder entries
1213 isSeparator: boolean;
1214 disableOnRows: (rows: any[]) => boolean;
1218 // Buttons are global actions
1219 export class GridToolbarButton {
1221 onClick: EventEmitter<any []>;
1222 action: () => any; // DEPRECATED
1226 export class GridToolbarCheckbox {
1229 onChange: EventEmitter<boolean>;
1232 export class GridDataSource {
1237 allRowsRetrieved: boolean;
1238 requestingData: boolean;
1239 retrievalError: boolean;
1240 getRows: (pager: Pager, sort: any[]) => Observable<any>;
1250 this.allRowsRetrieved = false;
1253 // called from the template -- no data fetching
1254 getPageOfRows(pager: Pager): any[] {
1256 return this.data.slice(
1257 pager.offset, pager.limit + pager.offset
1258 ).filter(row => row !== undefined);
1263 // called on initial component load and user action (e.g. paging, sorting).
1264 requestPage(pager: Pager): Promise<any> {
1267 this.getPageOfRows(pager).length === pager.limit
1268 // already have all data
1269 || this.allRowsRetrieved
1270 // have no way to get more data.
1273 return Promise.resolve();
1276 // If we have to call out for data, set inFetch
1277 this.requestingData = true;
1278 this.retrievalError = false;
1280 return new Promise((resolve, reject) => {
1281 let idx = pager.offset;
1282 return this.getRows(pager, this.sort).subscribe(
1284 this.data[idx++] = row;
1285 // not updating this.requestingData, as having
1286 // retrieved one row doesn't mean we're done
1287 this.retrievalError = false;
1290 console.error(`grid getRows() error ${err}`);
1291 this.requestingData = false;
1292 this.retrievalError = true;
1296 this.checkAllRetrieved(pager, idx);
1297 this.requestingData = false;
1298 this.retrievalError = false;
1305 // See if the last getRows() call resulted in the final set of data.
1306 checkAllRetrieved(pager: Pager, idx: number) {
1307 if (this.allRowsRetrieved) { return; }
1309 if (idx === 0 || idx < (pager.limit + pager.offset)) {
1310 // last query returned nothing or less than one page.
1311 // confirm we have all of the preceding pages.
1312 if (!this.data.includes(undefined)) {
1313 this.allRowsRetrieved = true;
1314 pager.resultCount = this.data.length;