2 * Collection of grid related classses and interfaces.
4 import {TemplateRef, EventEmitter, QueryList} from '@angular/core';
5 import {Observable, Subscription, empty} 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>;
33 dateOnlyIntervalField: string;
37 isDragTarget: boolean;
39 isFilterable: boolean;
41 isMultiSortable: boolean;
42 disableTooltip: boolean;
43 asyncSupportsEmptyTermClick: boolean;
44 comparator: (valueA: any, valueB: any) => number;
47 // True if the column was automatically generated.
52 filterOperator: string;
53 filterInputDisabled: boolean;
54 filterIncludeOrgAncestors: boolean;
55 filterIncludeOrgDescendants: boolean;
57 flesher: (obj: any, col: GridColumn, item: any) => any;
59 getCellContext(row: any) {
63 userContext: this.cellContext
72 this.isFiltered = false;
73 this.filterValue = undefined;
74 this.filterOperator = '=';
75 this.filterInputDisabled = false;
76 this.filterIncludeOrgAncestors = false;
77 this.filterIncludeOrgDescendants = false;
81 export class GridColumnSet {
82 columns: GridColumn[];
84 indexColumn: GridColumn;
86 isFilterable: boolean;
87 isMultiSortable: boolean;
88 stockVisible: string[];
90 defaultHiddenFields: string[];
91 defaultVisibleFields: string[];
93 constructor(idl: IdlService, idlClass?: string) {
96 this.stockVisible = [];
97 this.idlClass = idlClass;
100 add(col: GridColumn) {
102 this.applyColumnDefaults(col);
104 if (!this.insertColumn(col)) {
105 // Column was rejected as a duplicate.
109 if (col.isIndex) { this.indexColumn = col; }
111 // track which fields are visible on page load.
113 this.stockVisible.push(col.name);
116 this.applyColumnSortability(col);
117 this.applyColumnFilterability(col);
121 // Returns true if the new column was inserted, false otherwise.
122 // Declared columns take precedence over auto-generated columns
123 // when collisions occur.
124 // Declared columns are inserted in front of auto columns.
125 insertColumn(col: GridColumn): boolean {
128 if (this.getColByName(col.name) || this.getColByPath(col.path)) {
129 // New auto-generated column conflicts with existing
133 // No collisions. Add to the end of the list
134 this.columns.push(col);
139 // Adding a declared column.
142 for (let idx = 0; idx < this.columns.length; idx++) {
143 const testCol = this.columns[idx];
144 if (testCol.name === col.name) { // match found
145 if (testCol.isAuto) {
146 // new column takes precedence, remove the existing column.
147 this.columns.splice(idx, 1);
150 // New column does not take precedence. Avoid
157 // Delcared columns are inserted just before the first auto-column
158 for (let idx = 0; idx < this.columns.length; idx++) {
159 const testCol = this.columns[idx];
160 if (testCol.isAuto) {
162 this.columns.unshift(col);
164 this.columns.splice(idx, 0, col);
170 // No insertion point found. Toss the new column on the end.
171 this.columns.push(col);
175 getColByName(name: string): GridColumn {
176 return this.columns.filter(c => c.name === name)[0];
179 getColByPath(path: string): GridColumn {
181 return this.columns.filter(c => c.path === path)[0];
185 idlInfoFromDotpath(dotpath: string): any {
186 if (!dotpath || !this.idlClass) { return null; }
191 let nextIdlClass = this.idl.classes[this.idlClass];
193 const pathParts = dotpath.split(/\./);
195 for (let i = 0; i < pathParts.length; i++) {
197 const part = pathParts[i];
198 idlParent = idlField;
199 idlClass = nextIdlClass;
200 idlField = idlClass.field_map[part];
202 if (!idlField) { return null; } // invalid IDL path
204 if (i === pathParts.length - 1) {
205 // No more links to process.
209 if (idlField['class'] && (
210 idlField.datatype === 'link' ||
211 idlField.datatype === 'org_unit')) {
212 // The link class on the current field refers to the
213 // class of the link destination, not the current field.
214 // Mark it for processing during the next iteration.
215 nextIdlClass = this.idl.classes[idlField['class']];
220 idlParent: idlParent,
228 this.columns.forEach(col => {
232 col.visible = this.stockVisible.includes(col.name);
236 applyColumnDefaults(col: GridColumn) {
238 if (!col.idlFieldDef) {
239 const idlInfo = this.idlInfoFromDotpath(col.path || col.name);
241 col.idlFieldDef = idlInfo.idlField;
242 col.idlClass = idlInfo.idlClass.name;
244 col.datatype = col.idlFieldDef.datatype;
247 col.label = col.idlFieldDef.label || col.idlFieldDef.name;
252 if (!col.name) { col.name = col.path; }
253 if (!col.flex) { col.flex = 2; }
254 if (!col.align) { col.align = 'left'; }
255 if (!col.label) { col.label = col.name; }
256 if (!col.datatype) { col.datatype = 'text'; }
258 col.visible = !col.hidden;
261 applyColumnSortability(col: GridColumn) {
262 // column sortability defaults to the sortability of the column set.
263 if (col.isSortable === undefined && this.isSortable) {
264 col.isSortable = true;
267 if (col.isMultiSortable === undefined && this.isMultiSortable) {
268 col.isMultiSortable = true;
271 if (col.isMultiSortable) {
272 col.isSortable = true;
275 applyColumnFilterability(col: GridColumn) {
276 // column filterability defaults to the afilterability of the column set.
277 if (col.isFilterable === undefined && this.isFilterable) {
278 col.isFilterable = true;
282 displayColumns(): GridColumn[] {
283 return this.columns.filter(c => c.visible);
286 // Sorted visible columns followed by sorted non-visible columns.
287 // Note we don't sort this.columns directly as it would impact
288 // grid column display ordering.
289 sortForColPicker(): GridColumn[] {
290 const visible = this.columns.filter(c => c.visible);
291 const invisible = this.columns.filter(c => !c.visible);
293 visible.sort((a, b) => a.label < b.label ? -1 : 1);
294 invisible.sort((a, b) => a.label < b.label ? -1 : 1);
296 return visible.concat(invisible);
299 requiredColumns(): GridColumn[] {
300 const visible = this.displayColumns();
301 return visible.concat(
302 this.columns.filter(c => c.required && !c.visible));
305 insertBefore(source: GridColumn, target: GridColumn) {
308 this.columns.forEach((col, idx) => {
309 if (col.name === target.name) { targetIdx = idx; }});
311 this.columns.forEach((col, idx) => {
312 if (col.name === source.name) { sourceIdx = idx; }});
314 if (sourceIdx >= 0) {
315 this.columns.splice(sourceIdx, 1);
318 this.columns.splice(targetIdx, 0, source);
321 // Move visible columns to the front of the list.
322 moveVisibleToFront() {
323 const newCols = this.displayColumns();
324 this.columns.forEach(col => {
325 if (!col.visible) { newCols.push(col); }});
326 this.columns = newCols;
329 moveColumn(col: GridColumn, diff: number) {
330 let srcIdx, targetIdx;
332 this.columns.forEach((c, i) => {
333 if (c.name === col.name) { srcIdx = i; }
336 targetIdx = srcIdx + diff;
339 } else if (targetIdx >= this.columns.length) {
340 // Target index follows the last visible column.
342 this.columns.forEach((c, idx) => {
343 if (c.visible) { lastVisible = idx; }
346 // When moving a column (down) causes one or more
347 // visible columns to shuffle forward, our column
348 // moves into the slot of the last visible column.
349 // Otherwise, put it into the slot directly following
350 // the last visible column.
351 targetIdx = srcIdx <= lastVisible ? lastVisible : lastVisible + 1;
354 // Splice column out of old position, insert at new position.
355 this.columns.splice(srcIdx, 1);
356 this.columns.splice(targetIdx, 0, col);
359 compileSaveObject(): GridColumnPersistConf[] {
360 // only store information about visible columns.
361 // scrunch the data down to just the needed info.
362 return this.displayColumns().map(col => {
363 const c: GridColumnPersistConf = {name : col.name};
364 if (col.align !== 'left') { c.align = col.align; }
365 if (col.flex !== 2) { c.flex = Number(col.flex); }
366 if (Number(col.sort)) { c.sort = Number(col.sort); }
371 applyColumnSettings(conf: GridColumnPersistConf[]) {
373 if (!conf || conf.length === 0) {
374 // No configuration is available, but we have a list of
375 // fields to show or hide by default
377 if (this.defaultVisibleFields) {
378 this.columns.forEach(col => {
379 if (this.defaultVisibleFields.includes(col.name)) {
386 } else if (this.defaultHiddenFields) {
387 this.defaultHiddenFields.forEach(name => {
388 const col = this.getColByName(name);
400 conf.forEach(colConf => {
401 const col = this.getColByName(colConf.name);
402 if (!col) { return; } // no such column in this grid.
405 if (colConf.align) { col.align = colConf.align; }
406 if (colConf.flex) { col.flex = Number(colConf.flex); }
407 if (colConf.sort) { col.sort = Number(colConf.sort); }
409 // Add to new columns array, avoid dupes.
410 if (newCols.filter(c => c.name === col.name).length === 0) {
415 // columns which are not expressed within the saved
416 // configuration are marked as non-visible and
417 // appended to the end of the new list of columns.
418 this.columns.forEach(c => {
419 if (conf.filter(cf => cf.name === c.name).length === 0) {
425 this.columns = newCols;
429 // Maps colunm names to functions which return plain text values for
430 // each mapped column on a given row. This is primarily useful for
431 // generating print-friendly content for grid cells rendered via
434 // USAGE NOTE: Since a cellTemplate can be passed arbitrary context
435 // but a GridCellTextGenerator only gets the row object,
436 // if it's important to include content that's not available
437 // by default in the row object, you may want to stick
438 // it in the row object as an additional attribute.
440 export interface GridCellTextGenerator {
441 [columnName: string]: (row: any) => string;
444 export class GridRowSelector {
445 indexes: {[string: string]: boolean};
447 // Track these so we can emit the selectionChange event
448 // only when the selection actually changes.
449 previousSelection: string[] = [];
451 // Emits the selected indexes on selection change
452 selectionChange: EventEmitter<string[]> = new EventEmitter<string[]>();
458 // Returns true if all of the requested indexes exist in the selector.
459 contains(index: string | string[]): boolean {
460 const indexes = [].concat(index);
461 for (let i = 0; i < indexes.length; i++) { // early exit
462 if (!this.indexes[indexes[i]]) {
470 const keys = this.selected();
472 if (keys.length === this.previousSelection.length &&
473 this.contains(this.previousSelection)) {
474 return; // No change has occurred
477 this.previousSelection = keys;
478 this.selectionChange.emit(keys);
481 select(index: string | string[]) {
482 const indexes = [].concat(index);
483 indexes.forEach(i => this.indexes[i] = true);
487 deselect(index: string | string[]) {
488 const indexes = [].concat(index);
489 indexes.forEach(i => delete this.indexes[i]);
493 toggle(index: string) {
494 if (this.indexes[index]) {
495 this.deselect(index);
501 selected(): string[] {
502 return Object.keys(this.indexes);
506 return this.selected().length === 0;
515 export interface GridRowFlairEntry {
516 icon: string; // name of material icon
517 title?: string; // tooltip string
520 export class GridColumnPersistConf {
527 export class GridPersistConf {
530 columns: GridColumnPersistConf[];
531 hideToolbarActions: string[];
534 export class GridContext {
539 isFilterable: boolean;
540 stickyGridHeader: boolean;
541 isMultiSortable: boolean;
542 useLocalSort: boolean;
544 disableMultiSelect: boolean;
545 disableSelect: boolean;
546 dataSource: GridDataSource;
547 columnSet: GridColumnSet;
548 autoGeneratedColumnOrder: string;
549 rowSelector: GridRowSelector;
550 toolbarLabel: string;
551 toolbarButtons: GridToolbarButton[];
552 toolbarCheckboxes: GridToolbarCheckbox[];
553 toolbarActions: GridToolbarAction[];
554 lastSelectedIndex: any;
555 pageChanges: Subscription;
556 rowFlairIsEnabled: boolean;
557 rowFlairCallback: (row: any) => GridRowFlairEntry;
558 rowClassCallback: (row: any) => string;
559 cellClassCallback: (row: any, col: GridColumn) => string;
560 defaultVisibleFields: string[];
561 defaultHiddenFields: string[];
562 ignoredFields: string[];
563 overflowCells: boolean;
564 disablePaging: boolean;
565 showDeclaredFieldsOnly: boolean;
566 cellTextGenerator: GridCellTextGenerator;
567 reloadOnColumnChange: boolean;
569 // Allow calling code to know when the select-all-rows-in-page
570 // action has occurred.
571 selectRowsInPageEmitter: EventEmitter<void>;
573 filterControls: QueryList<GridFilterControlComponent>;
575 // Services injected by our grid component
578 store: ServerStoreService;
579 format: FormatService;
584 store: ServerStoreService,
585 format: FormatService) {
590 this.format = format;
591 this.pager = new Pager();
592 this.rowSelector = new GridRowSelector();
593 this.toolbarButtons = [];
594 this.toolbarCheckboxes = [];
595 this.toolbarActions = [];
599 this.selectRowsInPageEmitter = new EventEmitter<void>();
600 this.columnSet = new GridColumnSet(this.idl, this.idlClass);
601 this.columnSet.isSortable = this.isSortable === true;
602 this.columnSet.isFilterable = this.isFilterable === true;
603 this.columnSet.isMultiSortable = this.isMultiSortable === true;
604 this.columnSet.defaultHiddenFields = this.defaultHiddenFields;
605 this.columnSet.defaultVisibleFields = this.defaultVisibleFields;
606 if (!this.pager.limit) {
607 this.pager.limit = this.disablePaging ? MAX_ALL_ROW_COUNT : 10;
609 this.generateColumns();
612 // Load initial settings and data.
614 this.applyGridConfig()
615 .then(ok => this.dataSource.requestPage(this.pager))
616 .then(ok => this.listenToPager());
623 applyGridConfig(): Promise<void> {
624 return this.getGridConfig(this.persistKey)
628 columns = conf.columns;
629 if (conf.limit && !this.disablePaging) {
630 this.pager.limit = conf.limit;
632 this.applyToolbarActionVisibility(conf.hideToolbarActions);
635 // This is called regardless of the presence of saved
636 // settings so defaults can be applied.
637 this.columnSet.applyColumnSettings(columns);
641 applyToolbarActionVisibility(hidden: string[]) {
642 if (!hidden || hidden.length === 0) { return; }
645 this.toolbarActions.forEach(action => {
646 if (action.isGroup) {
648 } else if (!action.isSeparator) {
649 action.hidden = hidden.includes(action.label);
653 // If all actions in a group are hidden, hide the group as well.
654 // Note the group may be marked as hidden in the configuration,
655 // but the addition of new entries within a group should cause
656 // it to be visible again.
657 groups.forEach(group => {
658 const visible = this.toolbarActions
659 .filter(action => action.group === group.label && !action.hidden);
660 group.hidden = visible.length === 0;
665 // Give the UI time to settle before reloading grid data.
666 // This can help when data retrieval depends on a value
667 // getting modified by an angular digest cycle.
670 this.dataSource.reset();
671 this.dataSource.requestPage(this.pager);
675 reloadWithoutPagerReset() {
677 this.dataSource.reset();
678 this.dataSource.requestPage(this.pager);
682 // Sort the existing data source instead of requesting sorted
683 // data from the client. Reset pager to page 1. As with reload(),
684 // give the client a chance to setting before redisplaying.
688 this.sortLocalData();
689 this.dataSource.requestPage(this.pager);
693 // Subscribe or unsubscribe to page-change events from the pager.
695 if (this.pageChanges) { return; }
696 this.pageChanges = this.pager.onChange$.subscribe(
697 val => this.dataSource.requestPage(this.pager));
701 if (!this.pageChanges) { return; }
702 this.pageChanges.unsubscribe();
703 this.pageChanges = null;
706 // Sort data in the data source array
709 const sortDefs = this.dataSource.sort.map(sort => {
710 const column = this.columnSet.getColByName(sort.name);
718 if (!def.col.comparator) {
719 switch (def.col.datatype) {
723 def.col.comparator = (a, b) => {
726 if (a < b) { return -1; }
727 if (a > b) { return 1; }
732 def.col.comparator = (a, b) => {
733 if (a < b) { return -1; }
734 if (a > b) { return 1; }
743 this.dataSource.data.sort((rowA, rowB) => {
745 for (let idx = 0; idx < sortDefs.length; idx++) {
746 const sortDef = sortDefs[idx];
748 const valueA = this.getRowColumnValue(rowA, sortDef.col);
749 const valueB = this.getRowColumnValue(rowB, sortDef.col);
751 if (valueA === '' && valueB === '') { continue; }
752 if (valueA === '' && valueB !== '') { return 1; }
753 if (valueA !== '' && valueB === '') { return -1; }
755 const diff = sortDef.col.comparator(valueA, valueB);
756 if (diff === 0) { continue; }
758 return sortDef.dir === 'DESC' ? -diff : diff;
761 return 0; // No differences found.
765 getRowIndex(row: any): any {
766 const col = this.columnSet.indexColumn;
768 throw new Error('grid index column required');
770 return this.getRowColumnValue(row, col);
773 // Returns position in the data source array of the row with
774 // the provided index.
775 getRowPosition(index: any): number {
776 // for-loop for early exit
777 for (let idx = 0; idx < this.dataSource.data.length; idx++) {
778 const row = this.dataSource.data[idx];
779 if (row !== undefined && index === this.getRowIndex(row)) {
785 // Return the row with the provided index.
786 getRowByIndex(index: any): any {
787 for (let idx = 0; idx < this.dataSource.data.length; idx++) {
788 const row = this.dataSource.data[idx];
789 if (row !== undefined && index === this.getRowIndex(row)) {
795 // Returns all selected rows, regardless of whether they are
796 // currently visible in the grid display.
797 // De-selects previously selected rows which are no longer
798 // present in the grid.
799 getSelectedRows(): any[] {
803 this.rowSelector.selected().forEach(index => {
804 const row = this.getRowByIndex(index);
812 this.rowSelector.deselect(deleted);
816 rowIsSelected(row: any): boolean {
817 const index = this.getRowIndex(row);
818 return this.rowSelector.selected().filter(
823 getRowColumnBareValue(row: any, col: GridColumn): any {
824 if (col.name in row) {
825 return this.getObjectFieldValue(row, col.name);
826 } else if (col.path) {
827 return this.nestedItemFieldValue(row, col);
831 getRowColumnValue(row: any, col: GridColumn): any {
832 const val = this.getRowColumnBareValue(row, col);
834 if (col.datatype === 'bool') {
835 // Avoid string-ifying bools so we can use an <eg-bool/>
836 // in the grid template.
841 const intField = col.dateOnlyIntervalField;
844 this.columnSet.columns.filter(c => c.path === intField)[0];
846 interval = this.getRowColumnBareValue(row, intCol);
850 return this.format.transform({
852 idlClass: col.idlClass,
853 idlField: col.idlFieldDef ? col.idlFieldDef.name : col.name,
854 datatype: col.datatype,
855 datePlusTime: Boolean(col.datePlusTime),
856 timezoneContextOrg: Number(col.timezoneContextOrg),
857 dateOnlyInterval: interval
861 getObjectFieldValue(obj: any, name: string): any {
862 if (typeof obj[name] === 'function') {
869 nestedItemFieldValue(obj: any, col: GridColumn): string {
873 const original = obj;
874 const steps = col.path.split('.');
876 for (let i = 0; i < steps.length; i++) {
877 const step = steps[i];
879 if (obj === null || obj === undefined || typeof obj !== 'object') {
880 // We have run out of data to step through before
881 // reaching the end of the path. Conclude fleshing via
882 // callback if provided then exit.
883 if (col.flesher && obj !== undefined) {
884 return col.flesher(obj, col, original);
889 const class_ = obj.classname;
890 if (class_ && (idlClassDef = this.idl.classes[class_])) {
891 idlField = idlClassDef.field_map[step];
894 obj = this.getObjectFieldValue(obj, step);
897 // We found a nested IDL object which may or may not have
898 // been configured as a top-level column. Flesh the column
899 // metadata with our newly found IDL info.
902 col.datatype = idlField.datatype;
904 if (!col.idlFieldDef) {
905 idlField = col.idlFieldDef;
908 col.idlClass = idlClassDef.name;
911 col.label = idlField.label || idlField.name;
919 getColumnTextContent(row: any, col: GridColumn): string {
920 if (this.columnHasTextGenerator(col)) {
921 const str = this.cellTextGenerator[col.name](row);
922 return (str === null || str === undefined) ? '' : str;
924 if (col.cellTemplate) {
925 return ''; // avoid 'undefined' values
927 return this.getRowColumnValue(row, col);
932 selectOneRow(index: any) {
933 this.rowSelector.clear();
934 this.rowSelector.select(index);
935 this.lastSelectedIndex = index;
938 selectMultipleRows(indexes: any[]) {
939 this.rowSelector.clear();
940 this.rowSelector.select(indexes);
941 this.lastSelectedIndex = indexes[indexes.length - 1];
944 // selects or deselects an item, without affecting the others.
945 // returns true if the item is selected; false if de-selected.
946 toggleSelectOneRow(index: any) {
947 if (this.rowSelector.contains(index)) {
948 this.rowSelector.deselect(index);
952 this.rowSelector.select(index);
953 this.lastSelectedIndex = index;
957 selectRowByPos(pos: number) {
958 const row = this.dataSource.data[pos];
960 this.selectOneRow(this.getRowIndex(row));
964 selectPreviousRow() {
965 if (!this.lastSelectedIndex) { return; }
966 const pos = this.getRowPosition(this.lastSelectedIndex);
967 if (pos === this.pager.offset) {
968 this.toPrevPage().then(ok => this.selectLastRow(), err => {});
970 this.selectRowByPos(pos - 1);
975 if (!this.lastSelectedIndex) { return; }
976 const pos = this.getRowPosition(this.lastSelectedIndex);
977 if (pos === (this.pager.offset + this.pager.limit - 1)) {
978 this.toNextPage().then(ok => this.selectFirstRow(), err => {});
980 this.selectRowByPos(pos + 1);
985 // Select the previous row in addition to any currently selected row.
986 // However, if the previous row is already selected, assume the user
987 // has reversed direction and now wants to de-select the last selected row.
988 selectMultiRowsPrevious() {
989 if (!this.lastSelectedIndex) { return; }
990 const pos = this.getRowPosition(this.lastSelectedIndex);
991 const selectedIndexes = this.rowSelector.selected();
993 const promise = // load the previous page of data if needed
994 (pos === this.pager.offset) ? this.toPrevPage() : Promise.resolve();
998 const row = this.dataSource.data[pos - 1];
999 const newIndex = this.getRowIndex(row);
1000 if (selectedIndexes.filter(i => i === newIndex).length > 0) {
1001 // Prev row is already selected. User is reversing direction.
1002 this.rowSelector.deselect(this.lastSelectedIndex);
1003 this.lastSelectedIndex = newIndex;
1005 this.selectMultipleRows(selectedIndexes.concat(newIndex));
1012 // Select all rows between the previously selected row and
1013 // the provided row, including the provided row.
1014 // This is additive only -- rows are never de-selected.
1015 selectRowRange(index: any) {
1017 if (!this.lastSelectedIndex) {
1018 this.selectOneRow(index);
1022 const next = this.getRowPosition(index);
1023 const prev = this.getRowPosition(this.lastSelectedIndex);
1024 const start = Math.min(prev, next);
1025 const end = Math.max(prev, next);
1027 for (let idx = start; idx <= end; idx++) {
1028 const row = this.dataSource.data[idx];
1030 this.rowSelector.select(this.getRowIndex(row));
1034 this.lastSelectedIndex = index;
1038 // Select the next row in addition to any currently selected row.
1039 // However, if the next row is already selected, assume the user
1040 // has reversed direction and wants to de-select the last selected row.
1041 selectMultiRowsNext() {
1042 if (!this.lastSelectedIndex) { return; }
1043 const pos = this.getRowPosition(this.lastSelectedIndex);
1044 const selectedIndexes = this.rowSelector.selected();
1046 const promise = // load the next page of data if needed
1047 (pos === (this.pager.offset + this.pager.limit - 1)) ?
1048 this.toNextPage() : Promise.resolve();
1052 const row = this.dataSource.data[pos + 1];
1053 const newIndex = this.getRowIndex(row);
1054 if (selectedIndexes.filter(i => i === newIndex).length > 0) {
1055 // Next row is already selected. User is reversing direction.
1056 this.rowSelector.deselect(this.lastSelectedIndex);
1057 this.lastSelectedIndex = newIndex;
1059 this.selectMultipleRows(selectedIndexes.concat(newIndex));
1066 getFirstRowInPage(): any {
1067 return this.dataSource.data[this.pager.offset];
1070 getLastRowInPage(): any {
1071 return this.dataSource.data[this.pager.offset + this.pager.limit - 1];
1075 this.selectOneRow(this.getRowIndex(this.getFirstRowInPage()));
1079 this.selectOneRow(this.getRowIndex(this.getLastRowInPage()));
1082 selectRowsInPage() {
1083 const rows = this.dataSource.getPageOfRows(this.pager);
1084 const indexes = rows.map(r => this.getRowIndex(r));
1085 this.rowSelector.select(indexes);
1086 this.selectRowsInPageEmitter.emit();
1089 toPrevPage(): Promise<any> {
1090 if (this.pager.isFirstPage()) {
1091 return Promise.reject('on first');
1093 // temp ignore pager events since we're calling requestPage manually.
1095 this.pager.decrement();
1096 this.listenToPager();
1097 return this.dataSource.requestPage(this.pager);
1100 toNextPage(): Promise<any> {
1101 if (this.pager.isLastPage()) {
1102 return Promise.reject('on last');
1104 // temp ignore pager events since we're calling requestPage manually.
1106 this.pager.increment();
1107 this.listenToPager();
1108 return this.dataSource.requestPage(this.pager);
1111 getAllRows(): Promise<any> {
1112 const pager = new Pager();
1114 pager.limit = MAX_ALL_ROW_COUNT;
1115 return this.dataSource.requestPage(pager);
1118 // Returns a key/value pair object of visible column data as text.
1119 getRowAsFlatText(row: any): any {
1121 this.columnSet.displayColumns().forEach(col => {
1123 this.getColumnTextContent(row, col);
1128 getAllRowsAsText(): Observable<any> {
1129 return Observable.create(observer => {
1130 this.getAllRows().then(ok => {
1131 this.dataSource.data.forEach(row => {
1132 observer.next(this.getRowAsFlatText(row));
1134 observer.complete();
1139 removeFilters(): void {
1140 this.dataSource.filters = {};
1141 this.columnSet.displayColumns().forEach(col => { col.removeFilter(); });
1142 this.filterControls.forEach(ctl => ctl.reset());
1145 filtersSet(): boolean {
1146 return Object.keys(this.dataSource.filters).length > 0;
1149 gridToCsv(): Promise<string> {
1152 const columns = this.columnSet.displayColumns();
1155 columns.forEach(col => {
1156 csvStr += this.valueToCsv(col.label),
1160 csvStr = csvStr.replace(/,$/, '\n');
1162 return new Promise(resolve => {
1163 this.getAllRowsAsText().subscribe(
1165 columns.forEach(col => {
1166 csvStr += this.valueToCsv(row[col.name]);
1169 csvStr = csvStr.replace(/,$/, '\n');
1172 () => resolve(csvStr)
1178 // prepares a string for inclusion within a CSV document
1179 // by escaping commas and quotes and removing newlines.
1180 valueToCsv(str: string): string {
1182 if (!str) { return ''; }
1183 str = str.replace(/\n/g, '');
1184 if (str.match(/\,/) || str.match(/"/)) {
1185 str = str.replace(/"/g, '""');
1186 str = '"' + str + '"';
1192 if (!this.columnSet.idlClass) { return; }
1194 const pkeyField = this.idl.classes[this.columnSet.idlClass].pkey;
1195 const specifiedColumnOrder = this.autoGeneratedColumnOrder ?
1196 this.autoGeneratedColumnOrder.split(/,/) : [];
1198 // generate columns for all non-virtual fields on the IDL class
1199 const fields = this.idl.classes[this.columnSet.idlClass].fields
1200 .filter(field => !field.virtual);
1202 const sortedFields = this.autoGeneratedColumnOrder ?
1203 this.idl.sortIdlFields(fields, this.autoGeneratedColumnOrder.split(/,/)) :
1206 sortedFields.forEach(field => {
1207 if (!this.ignoredFields.filter(ignored => ignored === field.name).length) {
1208 const col = new GridColumn();
1209 col.name = field.name;
1210 col.label = field.label || field.name;
1211 col.idlFieldDef = field;
1212 col.idlClass = this.columnSet.idlClass;
1213 col.datatype = field.datatype;
1214 col.isIndex = (field.name === pkeyField);
1217 if (this.showDeclaredFieldsOnly) {
1221 this.columnSet.add(col);
1226 saveGridConfig(): Promise<any> {
1227 if (!this.persistKey) {
1228 throw new Error('Grid persistKey required to save columns');
1230 const conf = new GridPersistConf();
1232 conf.limit = this.pager.limit;
1233 conf.columns = this.columnSet.compileSaveObject();
1235 // Avoid persisting group visibility since that may change
1236 // with the addition of new columns. Always calculate that
1238 conf.hideToolbarActions = this.toolbarActions
1239 .filter(action => !action.isGroup && action.hidden)
1240 .map(action => action.label);
1242 return this.store.setItem('eg.grid.' + this.persistKey, conf);
1245 // TODO: saveGridConfigAsOrgSetting(...)
1247 getGridConfig(persistKey: string): Promise<GridPersistConf> {
1248 if (!persistKey) { return Promise.resolve(null); }
1249 return this.store.getItem('eg.grid.' + persistKey);
1252 columnHasTextGenerator(col: GridColumn): boolean {
1253 return this.cellTextGenerator && col.name in this.cellTextGenerator;
1258 // Actions apply to specific rows
1259 export class GridToolbarAction {
1261 onClick: EventEmitter<any []>;
1262 action: (rows: any[]) => any; // DEPRECATED
1265 isGroup: boolean; // used for group placeholder entries
1266 isSeparator: boolean;
1267 disableOnRows: (rows: any[]) => boolean;
1271 // Buttons are global actions
1272 export class GridToolbarButton {
1274 onClick: EventEmitter<any []>;
1275 action: () => any; // DEPRECATED
1280 export class GridToolbarCheckbox {
1283 onChange: EventEmitter<boolean>;
1286 export interface GridColumnSort {
1291 export class GridDataSource {
1294 sort: GridColumnSort[];
1296 allRowsRetrieved: boolean;
1297 requestingData: boolean;
1298 retrievalError: boolean;
1299 getRows: (pager: Pager, sort: GridColumnSort[]) => Observable<any>;
1309 this.allRowsRetrieved = false;
1312 // called from the template -- no data fetching
1313 getPageOfRows(pager: Pager): any[] {
1315 return this.data.slice(
1316 pager.offset, pager.limit + pager.offset
1317 ).filter(row => row !== undefined);
1322 // called on initial component load and user action (e.g. paging, sorting).
1323 requestPage(pager: Pager): Promise<any> {
1326 this.getPageOfRows(pager).length === pager.limit
1327 // already have all data
1328 || this.allRowsRetrieved
1329 // have no way to get more data.
1332 return Promise.resolve();
1335 // If we have to call out for data, set inFetch
1336 this.requestingData = true;
1337 this.retrievalError = false;
1339 return new Promise((resolve, reject) => {
1340 let idx = pager.offset;
1341 return this.getRows(pager, this.sort).subscribe(
1343 this.data[idx++] = row;
1344 // not updating this.requestingData, as having
1345 // retrieved one row doesn't mean we're done
1346 this.retrievalError = false;
1349 console.error(`grid getRows() error ${err}`);
1350 this.requestingData = false;
1351 this.retrievalError = true;
1355 this.checkAllRetrieved(pager, idx);
1356 this.requestingData = false;
1357 this.retrievalError = false;
1364 // See if the last getRows() call resulted in the final set of data.
1365 checkAllRetrieved(pager: Pager, idx: number) {
1366 if (this.allRowsRetrieved) { return; }
1368 if (idx === 0 || idx < (pager.limit + pager.offset)) {
1369 // last query returned nothing or less than one page.
1370 // confirm we have all of the preceding pages.
1371 if (!this.data.includes(undefined)) {
1372 this.allRowsRetrieved = true;
1373 pager.resultCount = this.data.length;