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);
120 // Returns true if the new column was inserted, false otherwise.
121 // Declared columns take precedence over auto-generated columns
122 // when collisions occur.
123 // Declared columns are inserted in front of auto columns.
124 insertColumn(col: GridColumn): boolean {
127 if (this.getColByName(col.name)) {
128 // New auto-generated column conflicts with existing
132 // No collisions. Add to the end of the list
133 this.columns.push(col);
138 // Adding a declared column.
141 for (let idx = 0; idx < this.columns.length; idx++) {
142 const testCol = this.columns[idx];
143 if (testCol.name === col.name) { // match found
144 if (testCol.isAuto) {
145 // new column takes precedence, remove the existing column.
146 this.columns.splice(idx, 1);
149 // New column does not take precedence. Avoid
156 // Delcared columns are inserted just before the first auto-column
157 for (let idx = 0; idx < this.columns.length; idx++) {
158 const testCol = this.columns[idx];
159 if (testCol.isAuto) {
161 this.columns.unshift(col);
163 this.columns.splice(idx, 0, col);
169 // No insertion point found. Toss the new column on the end.
170 this.columns.push(col);
174 getColByName(name: string): GridColumn {
175 return this.columns.filter(c => c.name === name)[0];
178 idlInfoFromDotpath(dotpath: string): any {
179 if (!dotpath || !this.idlClass) { return null; }
184 let nextIdlClass = this.idl.classes[this.idlClass];
186 const pathParts = dotpath.split(/\./);
188 for (let i = 0; i < pathParts.length; i++) {
190 const part = pathParts[i];
191 idlParent = idlField;
192 idlClass = nextIdlClass;
193 idlField = idlClass.field_map[part];
195 if (!idlField) { return null; } // invalid IDL path
197 if (i === pathParts.length - 1) {
198 // No more links to process.
202 if (idlField['class'] && (
203 idlField.datatype === 'link' ||
204 idlField.datatype === 'org_unit')) {
205 // The link class on the current field refers to the
206 // class of the link destination, not the current field.
207 // Mark it for processing during the next iteration.
208 nextIdlClass = this.idl.classes[idlField['class']];
213 idlParent: idlParent,
221 this.columns.forEach(col => {
225 col.visible = this.stockVisible.includes(col.name);
229 applyColumnDefaults(col: GridColumn) {
231 if (!col.idlFieldDef) {
232 const idlInfo = this.idlInfoFromDotpath(col.path || col.name);
234 col.idlFieldDef = idlInfo.idlField;
235 col.idlClass = idlInfo.idlClass.name;
237 col.datatype = col.idlFieldDef.datatype;
240 col.label = col.idlFieldDef.label || col.idlFieldDef.name;
245 if (!col.name) { col.name = col.path; }
246 if (!col.flex) { col.flex = 2; }
247 if (!col.align) { col.align = 'left'; }
248 if (!col.label) { col.label = col.name; }
249 if (!col.datatype) { col.datatype = 'text'; }
251 col.visible = !col.hidden;
254 applyColumnSortability(col: GridColumn) {
255 // column sortability defaults to the sortability of the column set.
256 if (col.isSortable === undefined && this.isSortable) {
257 col.isSortable = true;
260 if (col.isMultiSortable === undefined && this.isMultiSortable) {
261 col.isMultiSortable = true;
264 if (col.isMultiSortable) {
265 col.isSortable = true;
268 applyColumnFilterability(col: GridColumn) {
269 // column filterability defaults to the afilterability of the column set.
270 if (col.isFilterable === undefined && this.isFilterable) {
271 col.isFilterable = true;
275 displayColumns(): GridColumn[] {
276 return this.columns.filter(c => c.visible);
279 // Sorted visible columns followed by sorted non-visible columns.
280 // Note we don't sort this.columns directly as it would impact
281 // grid column display ordering.
282 sortForColPicker(): GridColumn[] {
283 const visible = this.columns.filter(c => c.visible);
284 const invisible = this.columns.filter(c => !c.visible);
286 visible.sort((a, b) => a.label < b.label ? -1 : 1);
287 invisible.sort((a, b) => a.label < b.label ? -1 : 1);
289 return visible.concat(invisible);
292 requiredColumns(): GridColumn[] {
293 const visible = this.displayColumns();
294 return visible.concat(
295 this.columns.filter(c => c.required && !c.visible));
298 insertBefore(source: GridColumn, target: GridColumn) {
301 this.columns.forEach((col, idx) => {
302 if (col.name === target.name) { targetIdx = idx; }});
304 this.columns.forEach((col, idx) => {
305 if (col.name === source.name) { sourceIdx = idx; }});
307 if (sourceIdx >= 0) {
308 this.columns.splice(sourceIdx, 1);
311 this.columns.splice(targetIdx, 0, source);
314 // Move visible columns to the front of the list.
315 moveVisibleToFront() {
316 const newCols = this.displayColumns();
317 this.columns.forEach(col => {
318 if (!col.visible) { newCols.push(col); }});
319 this.columns = newCols;
322 moveColumn(col: GridColumn, diff: number) {
323 let srcIdx, targetIdx;
325 this.columns.forEach((c, i) => {
326 if (c.name === col.name) { srcIdx = i; }
329 targetIdx = srcIdx + diff;
332 } else if (targetIdx >= this.columns.length) {
333 // Target index follows the last visible column.
335 this.columns.forEach((c, idx) => {
336 if (c.visible) { lastVisible = idx; }
339 // When moving a column (down) causes one or more
340 // visible columns to shuffle forward, our column
341 // moves into the slot of the last visible column.
342 // Otherwise, put it into the slot directly following
343 // the last visible column.
344 targetIdx = srcIdx <= lastVisible ? lastVisible : lastVisible + 1;
347 // Splice column out of old position, insert at new position.
348 this.columns.splice(srcIdx, 1);
349 this.columns.splice(targetIdx, 0, col);
352 compileSaveObject(): GridColumnPersistConf[] {
353 // only store information about visible columns.
354 // scrunch the data down to just the needed info.
355 return this.displayColumns().map(col => {
356 const c: GridColumnPersistConf = {name : col.name};
357 if (col.align !== 'left') { c.align = col.align; }
358 if (col.flex !== 2) { c.flex = Number(col.flex); }
359 if (Number(col.sort)) { c.sort = Number(col.sort); }
364 applyColumnSettings(conf: GridColumnPersistConf[]) {
366 if (!conf || conf.length === 0) {
367 // No configuration is available, but we have a list of
368 // fields to show or hide by default
370 if (this.defaultVisibleFields) {
371 this.columns.forEach(col => {
372 if (this.defaultVisibleFields.includes(col.name)) {
379 } else if (this.defaultHiddenFields) {
380 this.defaultHiddenFields.forEach(name => {
381 const col = this.getColByName(name);
393 conf.forEach(colConf => {
394 const col = this.getColByName(colConf.name);
395 if (!col) { return; } // no such column in this grid.
398 if (colConf.align) { col.align = colConf.align; }
399 if (colConf.flex) { col.flex = Number(colConf.flex); }
400 if (colConf.sort) { col.sort = Number(colConf.sort); }
402 // Add to new columns array, avoid dupes.
403 if (newCols.filter(c => c.name === col.name).length === 0) {
408 // columns which are not expressed within the saved
409 // configuration are marked as non-visible and
410 // appended to the end of the new list of columns.
411 this.columns.forEach(c => {
412 if (conf.filter(cf => cf.name === c.name).length === 0) {
418 this.columns = newCols;
422 // Maps colunm names to functions which return plain text values for
423 // each mapped column on a given row. This is primarily useful for
424 // generating print-friendly content for grid cells rendered via
427 // USAGE NOTE: Since a cellTemplate can be passed arbitrary context
428 // but a GridCellTextGenerator only gets the row object,
429 // if it's important to include content that's not available
430 // by default in the row object, you may want to stick
431 // it in the row object as an additional attribute.
433 export interface GridCellTextGenerator {
434 [columnName: string]: (row: any) => string;
437 export class GridRowSelector {
438 indexes: {[string: string]: boolean};
440 // Track these so we can emit the selectionChange event
441 // only when the selection actually changes.
442 previousSelection: string[] = [];
444 // Emits the selected indexes on selection change
445 selectionChange: EventEmitter<string[]> = new EventEmitter<string[]>();
451 // Returns true if all of the requested indexes exist in the selector.
452 contains(index: string | string[]): boolean {
453 const indexes = [].concat(index);
454 for (let i = 0; i < indexes.length; i++) { // early exit
455 if (!this.indexes[indexes[i]]) {
463 const keys = this.selected();
465 if (keys.length === this.previousSelection.length &&
466 this.contains(this.previousSelection)) {
467 return; // No change has occurred
470 this.previousSelection = keys;
471 this.selectionChange.emit(keys);
474 select(index: string | string[]) {
475 const indexes = [].concat(index);
476 indexes.forEach(i => this.indexes[i] = true);
480 deselect(index: string | string[]) {
481 const indexes = [].concat(index);
482 indexes.forEach(i => delete this.indexes[i]);
486 toggle(index: string) {
487 if (this.indexes[index]) {
488 this.deselect(index);
494 selected(): string[] {
495 return Object.keys(this.indexes);
499 return this.selected().length === 0;
508 export interface GridRowFlairEntry {
509 icon: string; // name of material icon
510 title?: string; // tooltip string
513 export class GridColumnPersistConf {
520 export class GridPersistConf {
523 columns: GridColumnPersistConf[];
524 hideToolbarActions: string[];
527 export class GridContext {
532 isFilterable: boolean;
533 stickyGridHeader: boolean;
534 isMultiSortable: boolean;
535 useLocalSort: boolean;
537 disableMultiSelect: boolean;
538 disableSelect: boolean;
539 dataSource: GridDataSource;
540 columnSet: GridColumnSet;
541 autoGeneratedColumnOrder: string;
542 rowSelector: GridRowSelector;
543 toolbarLabel: string;
544 toolbarButtons: GridToolbarButton[];
545 toolbarCheckboxes: GridToolbarCheckbox[];
546 toolbarActions: GridToolbarAction[];
547 lastSelectedIndex: any;
548 pageChanges: Subscription;
549 rowFlairIsEnabled: boolean;
550 rowFlairCallback: (row: any) => GridRowFlairEntry;
551 rowClassCallback: (row: any) => string;
552 cellClassCallback: (row: any, col: GridColumn) => string;
553 defaultVisibleFields: string[];
554 defaultHiddenFields: string[];
555 ignoredFields: string[];
556 overflowCells: boolean;
557 disablePaging: boolean;
558 showDeclaredFieldsOnly: boolean;
559 cellTextGenerator: GridCellTextGenerator;
560 reloadOnColumnChange: boolean;
562 // Allow calling code to know when the select-all-rows-in-page
563 // action has occurred.
564 selectRowsInPageEmitter: EventEmitter<void>;
566 filterControls: QueryList<GridFilterControlComponent>;
568 // Services injected by our grid component
571 store: ServerStoreService;
572 format: FormatService;
577 store: ServerStoreService,
578 format: FormatService) {
583 this.format = format;
584 this.pager = new Pager();
585 this.rowSelector = new GridRowSelector();
586 this.toolbarButtons = [];
587 this.toolbarCheckboxes = [];
588 this.toolbarActions = [];
592 this.selectRowsInPageEmitter = new EventEmitter<void>();
593 this.columnSet = new GridColumnSet(this.idl, this.idlClass);
594 this.columnSet.isSortable = this.isSortable === true;
595 this.columnSet.isFilterable = this.isFilterable === true;
596 this.columnSet.isMultiSortable = this.isMultiSortable === true;
597 this.columnSet.defaultHiddenFields = this.defaultHiddenFields;
598 this.columnSet.defaultVisibleFields = this.defaultVisibleFields;
599 if (!this.pager.limit) {
600 this.pager.limit = this.disablePaging ? MAX_ALL_ROW_COUNT : 10;
602 this.generateColumns();
605 // Load initial settings and data.
607 this.applyGridConfig()
608 .then(ok => this.dataSource.requestPage(this.pager))
609 .then(ok => this.listenToPager());
616 applyGridConfig(): Promise<void> {
617 return this.getGridConfig(this.persistKey)
621 columns = conf.columns;
622 if (conf.limit && !this.disablePaging) {
623 this.pager.limit = conf.limit;
625 this.applyToolbarActionVisibility(conf.hideToolbarActions);
628 // This is called regardless of the presence of saved
629 // settings so defaults can be applied.
630 this.columnSet.applyColumnSettings(columns);
634 applyToolbarActionVisibility(hidden: string[]) {
635 if (!hidden || hidden.length === 0) { return; }
638 this.toolbarActions.forEach(action => {
639 if (action.isGroup) {
641 } else if (!action.isSeparator) {
642 action.hidden = hidden.includes(action.label);
646 // If all actions in a group are hidden, hide the group as well.
647 // Note the group may be marked as hidden in the configuration,
648 // but the addition of new entries within a group should cause
649 // it to be visible again.
650 groups.forEach(group => {
651 const visible = this.toolbarActions
652 .filter(action => action.group === group.label && !action.hidden);
653 group.hidden = visible.length === 0;
658 // Give the UI time to settle before reloading grid data.
659 // This can help when data retrieval depends on a value
660 // getting modified by an angular digest cycle.
663 this.dataSource.reset();
664 this.dataSource.requestPage(this.pager);
668 reloadWithoutPagerReset() {
670 this.dataSource.reset();
671 this.dataSource.requestPage(this.pager);
675 // Sort the existing data source instead of requesting sorted
676 // data from the client. Reset pager to page 1. As with reload(),
677 // give the client a chance to setting before redisplaying.
681 this.sortLocalData();
682 this.dataSource.requestPage(this.pager);
686 // Subscribe or unsubscribe to page-change events from the pager.
688 if (this.pageChanges) { return; }
689 this.pageChanges = this.pager.onChange$.subscribe(
690 val => this.dataSource.requestPage(this.pager));
694 if (!this.pageChanges) { return; }
695 this.pageChanges.unsubscribe();
696 this.pageChanges = null;
699 // Sort data in the data source array
702 const sortDefs = this.dataSource.sort.map(sort => {
703 const column = this.columnSet.getColByName(sort.name);
711 if (!def.col.comparator) {
712 switch (def.col.datatype) {
716 def.col.comparator = (a, b) => {
719 if (a < b) { return -1; }
720 if (a > b) { return 1; }
725 def.col.comparator = (a, b) => {
726 if (a < b) { return -1; }
727 if (a > b) { return 1; }
736 this.dataSource.data.sort((rowA, rowB) => {
738 for (let idx = 0; idx < sortDefs.length; idx++) {
739 const sortDef = sortDefs[idx];
741 const valueA = this.getRowColumnValue(rowA, sortDef.col);
742 const valueB = this.getRowColumnValue(rowB, sortDef.col);
744 if (valueA === '' && valueB === '') { continue; }
745 if (valueA === '' && valueB !== '') { return 1; }
746 if (valueA !== '' && valueB === '') { return -1; }
748 const diff = sortDef.col.comparator(valueA, valueB);
749 if (diff === 0) { continue; }
751 return sortDef.dir === 'DESC' ? -diff : diff;
754 return 0; // No differences found.
758 getRowIndex(row: any): any {
759 const col = this.columnSet.indexColumn;
761 throw new Error('grid index column required');
763 return this.getRowColumnValue(row, col);
766 // Returns position in the data source array of the row with
767 // the provided index.
768 getRowPosition(index: any): number {
769 // for-loop for early exit
770 for (let idx = 0; idx < this.dataSource.data.length; idx++) {
771 const row = this.dataSource.data[idx];
772 if (row !== undefined && index === this.getRowIndex(row)) {
778 // Return the row with the provided index.
779 getRowByIndex(index: any): any {
780 for (let idx = 0; idx < this.dataSource.data.length; idx++) {
781 const row = this.dataSource.data[idx];
782 if (row !== undefined && index === this.getRowIndex(row)) {
788 // Returns all selected rows, regardless of whether they are
789 // currently visible in the grid display.
790 // De-selects previously selected rows which are no longer
791 // present in the grid.
792 getSelectedRows(): any[] {
796 this.rowSelector.selected().forEach(index => {
797 const row = this.getRowByIndex(index);
805 this.rowSelector.deselect(deleted);
809 rowIsSelected(row: any): boolean {
810 const index = this.getRowIndex(row);
811 return this.rowSelector.selected().filter(
816 getRowColumnBareValue(row: any, col: GridColumn): any {
817 if (col.name in row) {
818 return this.getObjectFieldValue(row, col.name);
819 } else if (col.path) {
820 return this.nestedItemFieldValue(row, col);
824 getRowColumnValue(row: any, col: GridColumn): any {
825 const val = this.getRowColumnBareValue(row, col);
827 if (col.datatype === 'bool') {
828 // Avoid string-ifying bools so we can use an <eg-bool/>
829 // in the grid template.
834 const intField = col.dateOnlyIntervalField;
837 this.columnSet.columns.filter(c => c.path === intField)[0];
839 interval = this.getRowColumnBareValue(row, intCol);
843 return this.format.transform({
845 idlClass: col.idlClass,
846 idlField: col.idlFieldDef ? col.idlFieldDef.name : col.name,
847 datatype: col.datatype,
848 datePlusTime: Boolean(col.datePlusTime),
849 timezoneContextOrg: Number(col.timezoneContextOrg),
850 dateOnlyInterval: interval
854 getObjectFieldValue(obj: any, name: string): any {
855 if (typeof obj[name] === 'function') {
862 nestedItemFieldValue(obj: any, col: GridColumn): string {
866 const original = obj;
867 const steps = col.path.split('.');
869 for (let i = 0; i < steps.length; i++) {
870 const step = steps[i];
872 if (obj === null || obj === undefined || typeof obj !== 'object') {
873 // We have run out of data to step through before
874 // reaching the end of the path. Conclude fleshing via
875 // callback if provided then exit.
876 if (col.flesher && obj !== undefined) {
877 return col.flesher(obj, col, original);
882 const class_ = obj.classname;
883 if (class_ && (idlClassDef = this.idl.classes[class_])) {
884 idlField = idlClassDef.field_map[step];
887 obj = this.getObjectFieldValue(obj, step);
890 // We found a nested IDL object which may or may not have
891 // been configured as a top-level column. Flesh the column
892 // metadata with our newly found IDL info.
895 col.datatype = idlField.datatype;
897 if (!col.idlFieldDef) {
898 idlField = col.idlFieldDef;
901 col.idlClass = idlClassDef.name;
904 col.label = idlField.label || idlField.name;
912 getColumnTextContent(row: any, col: GridColumn): string {
913 if (this.columnHasTextGenerator(col)) {
914 const str = this.cellTextGenerator[col.name](row);
915 return (str === null || str === undefined) ? '' : str;
917 if (col.cellTemplate) {
918 return ''; // avoid 'undefined' values
920 return this.getRowColumnValue(row, col);
925 selectOneRow(index: any) {
926 this.rowSelector.clear();
927 this.rowSelector.select(index);
928 this.lastSelectedIndex = index;
931 selectMultipleRows(indexes: any[]) {
932 this.rowSelector.clear();
933 this.rowSelector.select(indexes);
934 this.lastSelectedIndex = indexes[indexes.length - 1];
937 // selects or deselects an item, without affecting the others.
938 // returns true if the item is selected; false if de-selected.
939 toggleSelectOneRow(index: any) {
940 if (this.rowSelector.contains(index)) {
941 this.rowSelector.deselect(index);
945 this.rowSelector.select(index);
946 this.lastSelectedIndex = index;
950 selectRowByPos(pos: number) {
951 const row = this.dataSource.data[pos];
953 this.selectOneRow(this.getRowIndex(row));
957 selectPreviousRow() {
958 if (!this.lastSelectedIndex) { return; }
959 const pos = this.getRowPosition(this.lastSelectedIndex);
960 if (pos === this.pager.offset) {
961 this.toPrevPage().then(ok => this.selectLastRow(), err => {});
963 this.selectRowByPos(pos - 1);
968 if (!this.lastSelectedIndex) { return; }
969 const pos = this.getRowPosition(this.lastSelectedIndex);
970 if (pos === (this.pager.offset + this.pager.limit - 1)) {
971 this.toNextPage().then(ok => this.selectFirstRow(), err => {});
973 this.selectRowByPos(pos + 1);
978 // Select the previous row in addition to any currently selected row.
979 // However, if the previous row is already selected, assume the user
980 // has reversed direction and now wants to de-select the last selected row.
981 selectMultiRowsPrevious() {
982 if (!this.lastSelectedIndex) { return; }
983 const pos = this.getRowPosition(this.lastSelectedIndex);
984 const selectedIndexes = this.rowSelector.selected();
986 const promise = // load the previous page of data if needed
987 (pos === this.pager.offset) ? this.toPrevPage() : Promise.resolve();
991 const row = this.dataSource.data[pos - 1];
992 const newIndex = this.getRowIndex(row);
993 if (selectedIndexes.filter(i => i === newIndex).length > 0) {
994 // Prev row is already selected. User is reversing direction.
995 this.rowSelector.deselect(this.lastSelectedIndex);
996 this.lastSelectedIndex = newIndex;
998 this.selectMultipleRows(selectedIndexes.concat(newIndex));
1005 // Select all rows between the previously selected row and
1006 // the provided row, including the provided row.
1007 // This is additive only -- rows are never de-selected.
1008 selectRowRange(index: any) {
1010 if (!this.lastSelectedIndex) {
1011 this.selectOneRow(index);
1015 const next = this.getRowPosition(index);
1016 const prev = this.getRowPosition(this.lastSelectedIndex);
1017 const start = Math.min(prev, next);
1018 const end = Math.max(prev, next);
1020 for (let idx = start; idx <= end; idx++) {
1021 const row = this.dataSource.data[idx];
1023 this.rowSelector.select(this.getRowIndex(row));
1027 this.lastSelectedIndex = index;
1031 // Select the next row in addition to any currently selected row.
1032 // However, if the next row is already selected, assume the user
1033 // has reversed direction and wants to de-select the last selected row.
1034 selectMultiRowsNext() {
1035 if (!this.lastSelectedIndex) { return; }
1036 const pos = this.getRowPosition(this.lastSelectedIndex);
1037 const selectedIndexes = this.rowSelector.selected();
1039 const promise = // load the next page of data if needed
1040 (pos === (this.pager.offset + this.pager.limit - 1)) ?
1041 this.toNextPage() : Promise.resolve();
1045 const row = this.dataSource.data[pos + 1];
1046 const newIndex = this.getRowIndex(row);
1047 if (selectedIndexes.filter(i => i === newIndex).length > 0) {
1048 // Next row is already selected. User is reversing direction.
1049 this.rowSelector.deselect(this.lastSelectedIndex);
1050 this.lastSelectedIndex = newIndex;
1052 this.selectMultipleRows(selectedIndexes.concat(newIndex));
1059 getFirstRowInPage(): any {
1060 return this.dataSource.data[this.pager.offset];
1063 getLastRowInPage(): any {
1064 return this.dataSource.data[this.pager.offset + this.pager.limit - 1];
1068 this.selectOneRow(this.getRowIndex(this.getFirstRowInPage()));
1072 this.selectOneRow(this.getRowIndex(this.getLastRowInPage()));
1075 selectRowsInPage() {
1076 const rows = this.dataSource.getPageOfRows(this.pager);
1077 const indexes = rows.map(r => this.getRowIndex(r));
1078 this.rowSelector.select(indexes);
1079 this.selectRowsInPageEmitter.emit();
1082 toPrevPage(): Promise<any> {
1083 if (this.pager.isFirstPage()) {
1084 return Promise.reject('on first');
1086 // temp ignore pager events since we're calling requestPage manually.
1088 this.pager.decrement();
1089 this.listenToPager();
1090 return this.dataSource.requestPage(this.pager);
1093 toNextPage(): Promise<any> {
1094 if (this.pager.isLastPage()) {
1095 return Promise.reject('on last');
1097 // temp ignore pager events since we're calling requestPage manually.
1099 this.pager.increment();
1100 this.listenToPager();
1101 return this.dataSource.requestPage(this.pager);
1104 getAllRows(): Promise<any> {
1105 const pager = new Pager();
1107 pager.limit = MAX_ALL_ROW_COUNT;
1108 return this.dataSource.requestPage(pager);
1111 // Returns a key/value pair object of visible column data as text.
1112 getRowAsFlatText(row: any): any {
1114 this.columnSet.displayColumns().forEach(col => {
1116 this.getColumnTextContent(row, col);
1121 getAllRowsAsText(): Observable<any> {
1122 return Observable.create(observer => {
1123 this.getAllRows().then(ok => {
1124 this.dataSource.data.forEach(row => {
1125 observer.next(this.getRowAsFlatText(row));
1127 observer.complete();
1132 removeFilters(): void {
1133 this.dataSource.filters = {};
1134 this.columnSet.displayColumns().forEach(col => { col.removeFilter(); });
1135 this.filterControls.forEach(ctl => ctl.reset());
1138 filtersSet(): boolean {
1139 return Object.keys(this.dataSource.filters).length > 0;
1142 gridToCsv(): Promise<string> {
1145 const columns = this.columnSet.displayColumns();
1148 columns.forEach(col => {
1149 csvStr += this.valueToCsv(col.label),
1153 csvStr = csvStr.replace(/,$/, '\n');
1155 return new Promise(resolve => {
1156 this.getAllRowsAsText().subscribe(
1158 columns.forEach(col => {
1159 csvStr += this.valueToCsv(row[col.name]);
1162 csvStr = csvStr.replace(/,$/, '\n');
1165 () => resolve(csvStr)
1171 // prepares a string for inclusion within a CSV document
1172 // by escaping commas and quotes and removing newlines.
1173 valueToCsv(str: string): string {
1175 if (!str) { return ''; }
1176 str = str.replace(/\n/g, '');
1177 if (str.match(/\,/) || str.match(/"/)) {
1178 str = str.replace(/"/g, '""');
1179 str = '"' + str + '"';
1185 if (!this.columnSet.idlClass) { return; }
1187 const pkeyField = this.idl.classes[this.columnSet.idlClass].pkey;
1188 const specifiedColumnOrder = this.autoGeneratedColumnOrder ?
1189 this.autoGeneratedColumnOrder.split(/,/) : [];
1191 // generate columns for all non-virtual fields on the IDL class
1192 const fields = this.idl.classes[this.columnSet.idlClass].fields
1193 .filter(field => !field.virtual);
1195 const sortedFields = this.autoGeneratedColumnOrder ?
1196 this.idl.sortIdlFields(fields, this.autoGeneratedColumnOrder.split(/,/)) :
1199 sortedFields.forEach(field => {
1200 if (!this.ignoredFields.filter(ignored => ignored === field.name).length) {
1201 const col = new GridColumn();
1202 col.name = field.name;
1203 col.label = field.label || field.name;
1204 col.idlFieldDef = field;
1205 col.idlClass = this.columnSet.idlClass;
1206 col.datatype = field.datatype;
1207 col.isIndex = (field.name === pkeyField);
1210 if (this.showDeclaredFieldsOnly) {
1214 this.columnSet.add(col);
1219 saveGridConfig(): Promise<any> {
1220 if (!this.persistKey) {
1221 throw new Error('Grid persistKey required to save columns');
1223 const conf = new GridPersistConf();
1225 conf.limit = this.pager.limit;
1226 conf.columns = this.columnSet.compileSaveObject();
1228 // Avoid persisting group visibility since that may change
1229 // with the addition of new columns. Always calculate that
1231 conf.hideToolbarActions = this.toolbarActions
1232 .filter(action => !action.isGroup && action.hidden)
1233 .map(action => action.label);
1235 return this.store.setItem('eg.grid.' + this.persistKey, conf);
1238 // TODO: saveGridConfigAsOrgSetting(...)
1240 getGridConfig(persistKey: string): Promise<GridPersistConf> {
1241 if (!persistKey) { return Promise.resolve(null); }
1242 return this.store.getItem('eg.grid.' + persistKey);
1245 columnHasTextGenerator(col: GridColumn): boolean {
1246 return this.cellTextGenerator && col.name in this.cellTextGenerator;
1251 // Actions apply to specific rows
1252 export class GridToolbarAction {
1254 onClick: EventEmitter<any []>;
1255 action: (rows: any[]) => any; // DEPRECATED
1258 isGroup: boolean; // used for group placeholder entries
1259 isSeparator: boolean;
1260 disableOnRows: (rows: any[]) => boolean;
1264 // Buttons are global actions
1265 export class GridToolbarButton {
1267 onClick: EventEmitter<any []>;
1268 action: () => any; // DEPRECATED
1273 export class GridToolbarCheckbox {
1276 onChange: EventEmitter<boolean>;
1279 export interface GridColumnSort {
1284 export class GridDataSource {
1287 sort: GridColumnSort[];
1289 allRowsRetrieved: boolean;
1290 requestingData: boolean;
1291 retrievalError: boolean;
1292 getRows: (pager: Pager, sort: GridColumnSort[]) => Observable<any>;
1302 this.allRowsRetrieved = false;
1305 // called from the template -- no data fetching
1306 getPageOfRows(pager: Pager): any[] {
1308 return this.data.slice(
1309 pager.offset, pager.limit + pager.offset
1310 ).filter(row => row !== undefined);
1315 // called on initial component load and user action (e.g. paging, sorting).
1316 requestPage(pager: Pager): Promise<any> {
1319 this.getPageOfRows(pager).length === pager.limit
1320 // already have all data
1321 || this.allRowsRetrieved
1322 // have no way to get more data.
1325 return Promise.resolve();
1328 // If we have to call out for data, set inFetch
1329 this.requestingData = true;
1330 this.retrievalError = false;
1332 return new Promise((resolve, reject) => {
1333 let idx = pager.offset;
1334 return this.getRows(pager, this.sort).subscribe(
1336 this.data[idx++] = row;
1337 // not updating this.requestingData, as having
1338 // retrieved one row doesn't mean we're done
1339 this.retrievalError = false;
1342 console.error(`grid getRows() error ${err}`);
1343 this.requestingData = false;
1344 this.retrievalError = true;
1348 this.checkAllRetrieved(pager, idx);
1349 this.requestingData = false;
1350 this.retrievalError = false;
1357 // See if the last getRows() call resulted in the final set of data.
1358 checkAllRetrieved(pager: Pager, idx: number) {
1359 if (this.allRowsRetrieved) { return; }
1361 if (idx === 0 || idx < (pager.limit + pager.offset)) {
1362 // last query returned nothing or less than one page.
1363 // confirm we have all of the preceding pages.
1364 if (!this.data.includes(undefined)) {
1365 this.allRowsRetrieved = true;
1366 pager.resultCount = this.data.length;