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)) {
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 idlInfoFromDotpath(dotpath: string): any {
180 if (!dotpath || !this.idlClass) { return null; }
185 let nextIdlClass = this.idl.classes[this.idlClass];
187 const pathParts = dotpath.split(/\./);
189 for (let i = 0; i < pathParts.length; i++) {
191 const part = pathParts[i];
192 idlParent = idlField;
193 idlClass = nextIdlClass;
194 idlField = idlClass.field_map[part];
196 if (!idlField) { return null; } // invalid IDL path
198 if (i === pathParts.length - 1) {
199 // No more links to process.
203 if (idlField['class'] && (
204 idlField.datatype === 'link' ||
205 idlField.datatype === 'org_unit')) {
206 // The link class on the current field refers to the
207 // class of the link destination, not the current field.
208 // Mark it for processing during the next iteration.
209 nextIdlClass = this.idl.classes[idlField['class']];
214 idlParent: idlParent,
222 this.columns.forEach(col => {
226 col.visible = this.stockVisible.includes(col.name);
230 applyColumnDefaults(col: GridColumn) {
232 if (!col.idlFieldDef) {
233 const idlInfo = this.idlInfoFromDotpath(col.path || col.name);
235 col.idlFieldDef = idlInfo.idlField;
236 col.idlClass = idlInfo.idlClass.name;
238 col.datatype = col.idlFieldDef.datatype;
241 col.label = col.idlFieldDef.label || col.idlFieldDef.name;
246 if (!col.name) { col.name = col.path; }
247 if (!col.flex) { col.flex = 2; }
248 if (!col.align) { col.align = 'left'; }
249 if (!col.label) { col.label = col.name; }
250 if (!col.datatype) { col.datatype = 'text'; }
252 col.visible = !col.hidden;
255 applyColumnSortability(col: GridColumn) {
256 // column sortability defaults to the sortability of the column set.
257 if (col.isSortable === undefined && this.isSortable) {
258 col.isSortable = true;
261 if (col.isMultiSortable === undefined && this.isMultiSortable) {
262 col.isMultiSortable = true;
265 if (col.isMultiSortable) {
266 col.isSortable = true;
269 applyColumnFilterability(col: GridColumn) {
270 // column filterability defaults to the afilterability of the column set.
271 if (col.isFilterable === undefined && this.isFilterable) {
272 col.isFilterable = true;
276 displayColumns(): GridColumn[] {
277 return this.columns.filter(c => c.visible);
280 // Sorted visible columns followed by sorted non-visible columns.
281 // Note we don't sort this.columns directly as it would impact
282 // grid column display ordering.
283 sortForColPicker(): GridColumn[] {
284 const visible = this.columns.filter(c => c.visible);
285 const invisible = this.columns.filter(c => !c.visible);
287 visible.sort((a, b) => a.label < b.label ? -1 : 1);
288 invisible.sort((a, b) => a.label < b.label ? -1 : 1);
290 return visible.concat(invisible);
293 requiredColumns(): GridColumn[] {
294 const visible = this.displayColumns();
295 return visible.concat(
296 this.columns.filter(c => c.required && !c.visible));
299 insertBefore(source: GridColumn, target: GridColumn) {
302 this.columns.forEach((col, idx) => {
303 if (col.name === target.name) { targetIdx = idx; }});
305 this.columns.forEach((col, idx) => {
306 if (col.name === source.name) { sourceIdx = idx; }});
308 if (sourceIdx >= 0) {
309 this.columns.splice(sourceIdx, 1);
312 this.columns.splice(targetIdx, 0, source);
315 // Move visible columns to the front of the list.
316 moveVisibleToFront() {
317 const newCols = this.displayColumns();
318 this.columns.forEach(col => {
319 if (!col.visible) { newCols.push(col); }});
320 this.columns = newCols;
323 moveColumn(col: GridColumn, diff: number) {
324 let srcIdx, targetIdx;
326 this.columns.forEach((c, i) => {
327 if (c.name === col.name) { srcIdx = i; }
330 targetIdx = srcIdx + diff;
333 } else if (targetIdx >= this.columns.length) {
334 // Target index follows the last visible column.
336 this.columns.forEach((c, idx) => {
337 if (c.visible) { lastVisible = idx; }
340 // When moving a column (down) causes one or more
341 // visible columns to shuffle forward, our column
342 // moves into the slot of the last visible column.
343 // Otherwise, put it into the slot directly following
344 // the last visible column.
345 targetIdx = srcIdx <= lastVisible ? lastVisible : lastVisible + 1;
348 // Splice column out of old position, insert at new position.
349 this.columns.splice(srcIdx, 1);
350 this.columns.splice(targetIdx, 0, col);
353 compileSaveObject(): GridColumnPersistConf[] {
354 // only store information about visible columns.
355 // scrunch the data down to just the needed info.
356 return this.displayColumns().map(col => {
357 const c: GridColumnPersistConf = {name : col.name};
358 if (col.align !== 'left') { c.align = col.align; }
359 if (col.flex !== 2) { c.flex = Number(col.flex); }
360 if (Number(col.sort)) { c.sort = Number(col.sort); }
365 applyColumnSettings(conf: GridColumnPersistConf[]) {
367 if (!conf || conf.length === 0) {
368 // No configuration is available, but we have a list of
369 // fields to show or hide by default
371 if (this.defaultVisibleFields) {
372 this.columns.forEach(col => {
373 if (this.defaultVisibleFields.includes(col.name)) {
380 } else if (this.defaultHiddenFields) {
381 this.defaultHiddenFields.forEach(name => {
382 const col = this.getColByName(name);
394 conf.forEach(colConf => {
395 const col = this.getColByName(colConf.name);
396 if (!col) { return; } // no such column in this grid.
399 if (colConf.align) { col.align = colConf.align; }
400 if (colConf.flex) { col.flex = Number(colConf.flex); }
401 if (colConf.sort) { col.sort = Number(colConf.sort); }
403 // Add to new columns array, avoid dupes.
404 if (newCols.filter(c => c.name === col.name).length === 0) {
409 // columns which are not expressed within the saved
410 // configuration are marked as non-visible and
411 // appended to the end of the new list of columns.
412 this.columns.forEach(c => {
413 if (conf.filter(cf => cf.name === c.name).length === 0) {
419 this.columns = newCols;
423 // Maps colunm names to functions which return plain text values for
424 // each mapped column on a given row. This is primarily useful for
425 // generating print-friendly content for grid cells rendered via
428 // USAGE NOTE: Since a cellTemplate can be passed arbitrary context
429 // but a GridCellTextGenerator only gets the row object,
430 // if it's important to include content that's not available
431 // by default in the row object, you may want to stick
432 // it in the row object as an additional attribute.
434 export interface GridCellTextGenerator {
435 [columnName: string]: (row: any) => string;
438 export class GridRowSelector {
439 indexes: {[string: string]: boolean};
441 // Track these so we can emit the selectionChange event
442 // only when the selection actually changes.
443 previousSelection: string[] = [];
445 // Emits the selected indexes on selection change
446 selectionChange: EventEmitter<string[]> = new EventEmitter<string[]>();
452 // Returns true if all of the requested indexes exist in the selector.
453 contains(index: string | string[]): boolean {
454 const indexes = [].concat(index);
455 for (let i = 0; i < indexes.length; i++) { // early exit
456 if (!this.indexes[indexes[i]]) {
464 const keys = this.selected();
466 if (keys.length === this.previousSelection.length &&
467 this.contains(this.previousSelection)) {
468 return; // No change has occurred
471 this.previousSelection = keys;
472 this.selectionChange.emit(keys);
475 select(index: string | string[]) {
476 const indexes = [].concat(index);
477 indexes.forEach(i => this.indexes[i] = true);
481 deselect(index: string | string[]) {
482 const indexes = [].concat(index);
483 indexes.forEach(i => delete this.indexes[i]);
487 toggle(index: string) {
488 if (this.indexes[index]) {
489 this.deselect(index);
495 selected(): string[] {
496 return Object.keys(this.indexes);
500 return this.selected().length === 0;
509 export interface GridRowFlairEntry {
510 icon: string; // name of material icon
511 title?: string; // tooltip string
514 export class GridColumnPersistConf {
521 export class GridPersistConf {
524 columns: GridColumnPersistConf[];
525 hideToolbarActions: string[];
528 export class GridContext {
533 isFilterable: boolean;
534 stickyGridHeader: boolean;
535 isMultiSortable: boolean;
536 useLocalSort: boolean;
538 disableMultiSelect: boolean;
539 disableSelect: boolean;
540 dataSource: GridDataSource;
541 columnSet: GridColumnSet;
542 autoGeneratedColumnOrder: string;
543 rowSelector: GridRowSelector;
544 toolbarLabel: string;
545 toolbarButtons: GridToolbarButton[];
546 toolbarCheckboxes: GridToolbarCheckbox[];
547 toolbarActions: GridToolbarAction[];
548 lastSelectedIndex: any;
549 pageChanges: Subscription;
550 rowFlairIsEnabled: boolean;
551 rowFlairCallback: (row: any) => GridRowFlairEntry;
552 rowClassCallback: (row: any) => string;
553 cellClassCallback: (row: any, col: GridColumn) => string;
554 defaultVisibleFields: string[];
555 defaultHiddenFields: string[];
556 ignoredFields: string[];
557 overflowCells: boolean;
558 disablePaging: boolean;
559 showDeclaredFieldsOnly: boolean;
560 cellTextGenerator: GridCellTextGenerator;
561 reloadOnColumnChange: boolean;
563 // Allow calling code to know when the select-all-rows-in-page
564 // action has occurred.
565 selectRowsInPageEmitter: EventEmitter<void>;
567 filterControls: QueryList<GridFilterControlComponent>;
569 // Services injected by our grid component
572 store: ServerStoreService;
573 format: FormatService;
578 store: ServerStoreService,
579 format: FormatService) {
584 this.format = format;
585 this.pager = new Pager();
586 this.rowSelector = new GridRowSelector();
587 this.toolbarButtons = [];
588 this.toolbarCheckboxes = [];
589 this.toolbarActions = [];
593 this.selectRowsInPageEmitter = new EventEmitter<void>();
594 this.columnSet = new GridColumnSet(this.idl, this.idlClass);
595 this.columnSet.isSortable = this.isSortable === true;
596 this.columnSet.isFilterable = this.isFilterable === true;
597 this.columnSet.isMultiSortable = this.isMultiSortable === true;
598 this.columnSet.defaultHiddenFields = this.defaultHiddenFields;
599 this.columnSet.defaultVisibleFields = this.defaultVisibleFields;
600 if (!this.pager.limit) {
601 this.pager.limit = this.disablePaging ? MAX_ALL_ROW_COUNT : 10;
603 this.generateColumns();
606 // Load initial settings and data.
608 this.applyGridConfig()
609 .then(ok => this.dataSource.requestPage(this.pager))
610 .then(ok => this.listenToPager());
617 applyGridConfig(): Promise<void> {
618 return this.getGridConfig(this.persistKey)
622 columns = conf.columns;
623 if (conf.limit && !this.disablePaging) {
624 this.pager.limit = conf.limit;
626 this.applyToolbarActionVisibility(conf.hideToolbarActions);
629 // This is called regardless of the presence of saved
630 // settings so defaults can be applied.
631 this.columnSet.applyColumnSettings(columns);
635 applyToolbarActionVisibility(hidden: string[]) {
636 if (!hidden || hidden.length === 0) { return; }
639 this.toolbarActions.forEach(action => {
640 if (action.isGroup) {
642 } else if (!action.isSeparator) {
643 action.hidden = hidden.includes(action.label);
647 // If all actions in a group are hidden, hide the group as well.
648 // Note the group may be marked as hidden in the configuration,
649 // but the addition of new entries within a group should cause
650 // it to be visible again.
651 groups.forEach(group => {
652 const visible = this.toolbarActions
653 .filter(action => action.group === group.label && !action.hidden);
654 group.hidden = visible.length === 0;
659 // Give the UI time to settle before reloading grid data.
660 // This can help when data retrieval depends on a value
661 // getting modified by an angular digest cycle.
664 this.dataSource.reset();
665 this.dataSource.requestPage(this.pager);
669 reloadWithoutPagerReset() {
671 this.dataSource.reset();
672 this.dataSource.requestPage(this.pager);
676 // Sort the existing data source instead of requesting sorted
677 // data from the client. Reset pager to page 1. As with reload(),
678 // give the client a chance to setting before redisplaying.
682 this.sortLocalData();
683 this.dataSource.requestPage(this.pager);
687 // Subscribe or unsubscribe to page-change events from the pager.
689 if (this.pageChanges) { return; }
690 this.pageChanges = this.pager.onChange$.subscribe(
691 val => this.dataSource.requestPage(this.pager));
695 if (!this.pageChanges) { return; }
696 this.pageChanges.unsubscribe();
697 this.pageChanges = null;
700 // Sort data in the data source array
703 const sortDefs = this.dataSource.sort.map(sort => {
704 const column = this.columnSet.getColByName(sort.name);
712 if (!def.col.comparator) {
713 switch (def.col.datatype) {
717 def.col.comparator = (a, b) => {
720 if (a < b) { return -1; }
721 if (a > b) { return 1; }
726 def.col.comparator = (a, b) => {
727 if (a < b) { return -1; }
728 if (a > b) { return 1; }
737 this.dataSource.data.sort((rowA, rowB) => {
739 for (let idx = 0; idx < sortDefs.length; idx++) {
740 const sortDef = sortDefs[idx];
742 const valueA = this.getRowColumnValue(rowA, sortDef.col);
743 const valueB = this.getRowColumnValue(rowB, sortDef.col);
745 if (valueA === '' && valueB === '') { continue; }
746 if (valueA === '' && valueB !== '') { return 1; }
747 if (valueA !== '' && valueB === '') { return -1; }
749 const diff = sortDef.col.comparator(valueA, valueB);
750 if (diff === 0) { continue; }
752 return sortDef.dir === 'DESC' ? -diff : diff;
755 return 0; // No differences found.
759 getRowIndex(row: any): any {
760 const col = this.columnSet.indexColumn;
762 throw new Error('grid index column required');
764 return this.getRowColumnValue(row, col);
767 // Returns position in the data source array of the row with
768 // the provided index.
769 getRowPosition(index: any): number {
770 // for-loop for early exit
771 for (let idx = 0; idx < this.dataSource.data.length; idx++) {
772 const row = this.dataSource.data[idx];
773 if (row !== undefined && index === this.getRowIndex(row)) {
779 // Return the row with the provided index.
780 getRowByIndex(index: any): any {
781 for (let idx = 0; idx < this.dataSource.data.length; idx++) {
782 const row = this.dataSource.data[idx];
783 if (row !== undefined && index === this.getRowIndex(row)) {
789 // Returns all selected rows, regardless of whether they are
790 // currently visible in the grid display.
791 // De-selects previously selected rows which are no longer
792 // present in the grid.
793 getSelectedRows(): any[] {
797 this.rowSelector.selected().forEach(index => {
798 const row = this.getRowByIndex(index);
806 this.rowSelector.deselect(deleted);
810 rowIsSelected(row: any): boolean {
811 const index = this.getRowIndex(row);
812 return this.rowSelector.selected().filter(
817 getRowColumnBareValue(row: any, col: GridColumn): any {
818 if (col.name in row) {
819 return this.getObjectFieldValue(row, col.name);
820 } else if (col.path) {
821 return this.nestedItemFieldValue(row, col);
825 getRowColumnValue(row: any, col: GridColumn): any {
826 const val = this.getRowColumnBareValue(row, col);
828 if (col.datatype === 'bool') {
829 // Avoid string-ifying bools so we can use an <eg-bool/>
830 // in the grid template.
835 const intField = col.dateOnlyIntervalField;
838 this.columnSet.columns.filter(c => c.path === intField)[0];
840 interval = this.getRowColumnBareValue(row, intCol);
844 return this.format.transform({
846 idlClass: col.idlClass,
847 idlField: col.idlFieldDef ? col.idlFieldDef.name : col.name,
848 datatype: col.datatype,
849 datePlusTime: Boolean(col.datePlusTime),
850 timezoneContextOrg: Number(col.timezoneContextOrg),
851 dateOnlyInterval: interval
855 getObjectFieldValue(obj: any, name: string): any {
856 if (typeof obj[name] === 'function') {
863 nestedItemFieldValue(obj: any, col: GridColumn): string {
867 const original = obj;
868 const steps = col.path.split('.');
870 for (let i = 0; i < steps.length; i++) {
871 const step = steps[i];
873 if (obj === null || obj === undefined || typeof obj !== 'object') {
874 // We have run out of data to step through before
875 // reaching the end of the path. Conclude fleshing via
876 // callback if provided then exit.
877 if (col.flesher && obj !== undefined) {
878 return col.flesher(obj, col, original);
883 const class_ = obj.classname;
884 if (class_ && (idlClassDef = this.idl.classes[class_])) {
885 idlField = idlClassDef.field_map[step];
888 obj = this.getObjectFieldValue(obj, step);
891 // We found a nested IDL object which may or may not have
892 // been configured as a top-level column. Flesh the column
893 // metadata with our newly found IDL info.
896 col.datatype = idlField.datatype;
898 if (!col.idlFieldDef) {
899 idlField = col.idlFieldDef;
902 col.idlClass = idlClassDef.name;
905 col.label = idlField.label || idlField.name;
913 getColumnTextContent(row: any, col: GridColumn): string {
914 if (this.columnHasTextGenerator(col)) {
915 const str = this.cellTextGenerator[col.name](row);
916 return (str === null || str === undefined) ? '' : str;
918 if (col.cellTemplate) {
919 return ''; // avoid 'undefined' values
921 return this.getRowColumnValue(row, col);
926 selectOneRow(index: any) {
927 this.rowSelector.clear();
928 this.rowSelector.select(index);
929 this.lastSelectedIndex = index;
932 selectMultipleRows(indexes: any[]) {
933 this.rowSelector.clear();
934 this.rowSelector.select(indexes);
935 this.lastSelectedIndex = indexes[indexes.length - 1];
938 // selects or deselects an item, without affecting the others.
939 // returns true if the item is selected; false if de-selected.
940 toggleSelectOneRow(index: any) {
941 if (this.rowSelector.contains(index)) {
942 this.rowSelector.deselect(index);
946 this.rowSelector.select(index);
947 this.lastSelectedIndex = index;
951 selectRowByPos(pos: number) {
952 const row = this.dataSource.data[pos];
954 this.selectOneRow(this.getRowIndex(row));
958 selectPreviousRow() {
959 if (!this.lastSelectedIndex) { return; }
960 const pos = this.getRowPosition(this.lastSelectedIndex);
961 if (pos === this.pager.offset) {
962 this.toPrevPage().then(ok => this.selectLastRow(), err => {});
964 this.selectRowByPos(pos - 1);
969 if (!this.lastSelectedIndex) { return; }
970 const pos = this.getRowPosition(this.lastSelectedIndex);
971 if (pos === (this.pager.offset + this.pager.limit - 1)) {
972 this.toNextPage().then(ok => this.selectFirstRow(), err => {});
974 this.selectRowByPos(pos + 1);
979 // Select the previous row in addition to any currently selected row.
980 // However, if the previous row is already selected, assume the user
981 // has reversed direction and now wants to de-select the last selected row.
982 selectMultiRowsPrevious() {
983 if (!this.lastSelectedIndex) { return; }
984 const pos = this.getRowPosition(this.lastSelectedIndex);
985 const selectedIndexes = this.rowSelector.selected();
987 const promise = // load the previous page of data if needed
988 (pos === this.pager.offset) ? this.toPrevPage() : Promise.resolve();
992 const row = this.dataSource.data[pos - 1];
993 const newIndex = this.getRowIndex(row);
994 if (selectedIndexes.filter(i => i === newIndex).length > 0) {
995 // Prev row is already selected. User is reversing direction.
996 this.rowSelector.deselect(this.lastSelectedIndex);
997 this.lastSelectedIndex = newIndex;
999 this.selectMultipleRows(selectedIndexes.concat(newIndex));
1006 // Select all rows between the previously selected row and
1007 // the provided row, including the provided row.
1008 // This is additive only -- rows are never de-selected.
1009 selectRowRange(index: any) {
1011 if (!this.lastSelectedIndex) {
1012 this.selectOneRow(index);
1016 const next = this.getRowPosition(index);
1017 const prev = this.getRowPosition(this.lastSelectedIndex);
1018 const start = Math.min(prev, next);
1019 const end = Math.max(prev, next);
1021 for (let idx = start; idx <= end; idx++) {
1022 const row = this.dataSource.data[idx];
1024 this.rowSelector.select(this.getRowIndex(row));
1028 this.lastSelectedIndex = index;
1032 // Select the next row in addition to any currently selected row.
1033 // However, if the next row is already selected, assume the user
1034 // has reversed direction and wants to de-select the last selected row.
1035 selectMultiRowsNext() {
1036 if (!this.lastSelectedIndex) { return; }
1037 const pos = this.getRowPosition(this.lastSelectedIndex);
1038 const selectedIndexes = this.rowSelector.selected();
1040 const promise = // load the next page of data if needed
1041 (pos === (this.pager.offset + this.pager.limit - 1)) ?
1042 this.toNextPage() : Promise.resolve();
1046 const row = this.dataSource.data[pos + 1];
1047 const newIndex = this.getRowIndex(row);
1048 if (selectedIndexes.filter(i => i === newIndex).length > 0) {
1049 // Next row is already selected. User is reversing direction.
1050 this.rowSelector.deselect(this.lastSelectedIndex);
1051 this.lastSelectedIndex = newIndex;
1053 this.selectMultipleRows(selectedIndexes.concat(newIndex));
1060 getFirstRowInPage(): any {
1061 return this.dataSource.data[this.pager.offset];
1064 getLastRowInPage(): any {
1065 return this.dataSource.data[this.pager.offset + this.pager.limit - 1];
1069 this.selectOneRow(this.getRowIndex(this.getFirstRowInPage()));
1073 this.selectOneRow(this.getRowIndex(this.getLastRowInPage()));
1076 selectRowsInPage() {
1077 const rows = this.dataSource.getPageOfRows(this.pager);
1078 const indexes = rows.map(r => this.getRowIndex(r));
1079 this.rowSelector.select(indexes);
1080 this.selectRowsInPageEmitter.emit();
1083 toPrevPage(): Promise<any> {
1084 if (this.pager.isFirstPage()) {
1085 return Promise.reject('on first');
1087 // temp ignore pager events since we're calling requestPage manually.
1089 this.pager.decrement();
1090 this.listenToPager();
1091 return this.dataSource.requestPage(this.pager);
1094 toNextPage(): Promise<any> {
1095 if (this.pager.isLastPage()) {
1096 return Promise.reject('on last');
1098 // temp ignore pager events since we're calling requestPage manually.
1100 this.pager.increment();
1101 this.listenToPager();
1102 return this.dataSource.requestPage(this.pager);
1105 getAllRows(): Promise<any> {
1106 const pager = new Pager();
1108 pager.limit = MAX_ALL_ROW_COUNT;
1109 return this.dataSource.requestPage(pager);
1112 // Returns a key/value pair object of visible column data as text.
1113 getRowAsFlatText(row: any): any {
1115 this.columnSet.displayColumns().forEach(col => {
1117 this.getColumnTextContent(row, col);
1122 getAllRowsAsText(): Observable<any> {
1123 return Observable.create(observer => {
1124 this.getAllRows().then(ok => {
1125 this.dataSource.data.forEach(row => {
1126 observer.next(this.getRowAsFlatText(row));
1128 observer.complete();
1133 removeFilters(): void {
1134 this.dataSource.filters = {};
1135 this.columnSet.displayColumns().forEach(col => { col.removeFilter(); });
1136 this.filterControls.forEach(ctl => ctl.reset());
1139 filtersSet(): boolean {
1140 return Object.keys(this.dataSource.filters).length > 0;
1143 gridToCsv(): Promise<string> {
1146 const columns = this.columnSet.displayColumns();
1149 columns.forEach(col => {
1150 csvStr += this.valueToCsv(col.label),
1154 csvStr = csvStr.replace(/,$/, '\n');
1156 return new Promise(resolve => {
1157 this.getAllRowsAsText().subscribe(
1159 columns.forEach(col => {
1160 csvStr += this.valueToCsv(row[col.name]);
1163 csvStr = csvStr.replace(/,$/, '\n');
1166 () => resolve(csvStr)
1172 // prepares a string for inclusion within a CSV document
1173 // by escaping commas and quotes and removing newlines.
1174 valueToCsv(str: string): string {
1176 if (!str) { return ''; }
1177 str = str.replace(/\n/g, '');
1178 if (str.match(/\,/) || str.match(/"/)) {
1179 str = str.replace(/"/g, '""');
1180 str = '"' + str + '"';
1186 if (!this.columnSet.idlClass) { return; }
1188 const pkeyField = this.idl.classes[this.columnSet.idlClass].pkey;
1189 const specifiedColumnOrder = this.autoGeneratedColumnOrder ?
1190 this.autoGeneratedColumnOrder.split(/,/) : [];
1192 // generate columns for all non-virtual fields on the IDL class
1193 const fields = this.idl.classes[this.columnSet.idlClass].fields
1194 .filter(field => !field.virtual);
1196 const sortedFields = this.autoGeneratedColumnOrder ?
1197 this.idl.sortIdlFields(fields, this.autoGeneratedColumnOrder.split(/,/)) :
1200 sortedFields.forEach(field => {
1201 if (!this.ignoredFields.filter(ignored => ignored === field.name).length) {
1202 const col = new GridColumn();
1203 col.name = field.name;
1204 col.label = field.label || field.name;
1205 col.idlFieldDef = field;
1206 col.idlClass = this.columnSet.idlClass;
1207 col.datatype = field.datatype;
1208 col.isIndex = (field.name === pkeyField);
1211 if (this.showDeclaredFieldsOnly) {
1215 this.columnSet.add(col);
1220 saveGridConfig(): Promise<any> {
1221 if (!this.persistKey) {
1222 throw new Error('Grid persistKey required to save columns');
1224 const conf = new GridPersistConf();
1226 conf.limit = this.pager.limit;
1227 conf.columns = this.columnSet.compileSaveObject();
1229 // Avoid persisting group visibility since that may change
1230 // with the addition of new columns. Always calculate that
1232 conf.hideToolbarActions = this.toolbarActions
1233 .filter(action => !action.isGroup && action.hidden)
1234 .map(action => action.label);
1236 return this.store.setItem('eg.grid.' + this.persistKey, conf);
1239 // TODO: saveGridConfigAsOrgSetting(...)
1241 getGridConfig(persistKey: string): Promise<GridPersistConf> {
1242 if (!persistKey) { return Promise.resolve(null); }
1243 return this.store.getItem('eg.grid.' + persistKey);
1246 columnHasTextGenerator(col: GridColumn): boolean {
1247 return this.cellTextGenerator && col.name in this.cellTextGenerator;
1252 // Actions apply to specific rows
1253 export class GridToolbarAction {
1255 onClick: EventEmitter<any []>;
1256 action: (rows: any[]) => any; // DEPRECATED
1259 isGroup: boolean; // used for group placeholder entries
1260 isSeparator: boolean;
1261 disableOnRows: (rows: any[]) => boolean;
1265 // Buttons are global actions
1266 export class GridToolbarButton {
1268 onClick: EventEmitter<any []>;
1269 action: () => any; // DEPRECATED
1274 export class GridToolbarCheckbox {
1277 onChange: EventEmitter<boolean>;
1280 export interface GridColumnSort {
1285 export class GridDataSource {
1288 sort: GridColumnSort[];
1290 allRowsRetrieved: boolean;
1291 requestingData: boolean;
1292 retrievalError: boolean;
1293 getRows: (pager: Pager, sort: GridColumnSort[]) => Observable<any>;
1303 this.allRowsRetrieved = false;
1306 // called from the template -- no data fetching
1307 getPageOfRows(pager: Pager): any[] {
1309 return this.data.slice(
1310 pager.offset, pager.limit + pager.offset
1311 ).filter(row => row !== undefined);
1316 // called on initial component load and user action (e.g. paging, sorting).
1317 requestPage(pager: Pager): Promise<any> {
1320 this.getPageOfRows(pager).length === pager.limit
1321 // already have all data
1322 || this.allRowsRetrieved
1323 // have no way to get more data.
1326 return Promise.resolve();
1329 // If we have to call out for data, set inFetch
1330 this.requestingData = true;
1331 this.retrievalError = false;
1333 return new Promise((resolve, reject) => {
1334 let idx = pager.offset;
1335 return this.getRows(pager, this.sort).subscribe(
1337 this.data[idx++] = row;
1338 // not updating this.requestingData, as having
1339 // retrieved one row doesn't mean we're done
1340 this.retrievalError = false;
1343 console.error(`grid getRows() error ${err}`);
1344 this.requestingData = false;
1345 this.retrievalError = true;
1349 this.checkAllRetrieved(pager, idx);
1350 this.requestingData = false;
1351 this.retrievalError = false;
1358 // See if the last getRows() call resulted in the final set of data.
1359 checkAllRetrieved(pager: Pager, idx: number) {
1360 if (this.allRowsRetrieved) { return; }
1362 if (idx === 0 || idx < (pager.limit + pager.offset)) {
1363 // last query returned nothing or less than one page.
1364 // confirm we have all of the preceding pages.
1365 if (!this.data.includes(undefined)) {
1366 this.allRowsRetrieved = true;
1367 pager.resultCount = this.data.length;