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 {
25 // IDL class of the object which contains this field.
26 // Not to be confused with the class of a linked object.
30 datePlusTime: boolean;
32 timezoneContextOrg: number;
33 cellTemplate: TemplateRef<any>;
34 dateOnlyIntervalField: string;
38 isDragTarget: boolean;
40 isFilterable: boolean;
42 isMultiSortable: boolean;
43 disableTooltip: boolean;
44 asyncSupportsEmptyTermClick: boolean;
45 comparator: (valueA: any, valueB: any) => number;
48 // True if the column was automatically generated.
53 filterOperator: string;
54 filterInputDisabled: boolean;
55 filterIncludeOrgAncestors: boolean;
56 filterIncludeOrgDescendants: boolean;
58 flesher: (obj: any, col: GridColumn, item: any) => any;
60 getCellContext(row: any) {
64 userContext: this.cellContext
73 this.isFiltered = false;
74 this.filterValue = undefined;
75 this.filterOperator = '=';
76 this.filterInputDisabled = false;
77 this.filterIncludeOrgAncestors = false;
78 this.filterIncludeOrgDescendants = false;
82 const col = new GridColumn();
86 col.label = this.label;
88 col.required = this.required;
89 col.hidden = this.hidden;
90 col.asyncSupportsEmptyTermClick = this.asyncSupportsEmptyTermClick;
91 col.isIndex = this.isIndex;
92 col.cellTemplate = this.cellTemplate;
93 col.cellContext = this.cellContext;
94 col.disableTooltip = this.disableTooltip;
95 col.isSortable = this.isSortable;
96 col.isFilterable = this.isFilterable;
97 col.isMultiSortable = this.isMultiSortable;
98 col.datatype = this.datatype;
99 col.datePlusTime = this.datePlusTime;
100 col.ternaryBool = this.ternaryBool;
101 col.timezoneContextOrg = this.timezoneContextOrg;
102 col.idlClass = this.idlClass;
103 col.isAuto = this.isAuto;
110 export class GridColumnSet {
111 columns: GridColumn[];
113 indexColumn: GridColumn;
115 isFilterable: boolean;
116 isMultiSortable: boolean;
117 stockVisible: string[];
119 defaultHiddenFields: string[];
120 defaultVisibleFields: string[];
122 constructor(idl: IdlService, idlClass?: string) {
125 this.stockVisible = [];
126 this.idlClass = idlClass;
129 add(col: GridColumn) {
131 if (col.path && col.path.match(/\*$/)) {
132 return this.generateWildcardColumns(col);
135 this.applyColumnDefaults(col);
137 if (!this.insertColumn(col)) {
138 // Column was rejected as a duplicate.
142 if (col.isIndex) { this.indexColumn = col; }
144 // track which fields are visible on page load.
146 this.stockVisible.push(col.name);
149 this.applyColumnSortability(col);
150 this.applyColumnFilterability(col);
153 generateWildcardColumns(col: GridColumn) {
155 const dotpath = col.path.replace(/\.?\*$/, '');
156 let classObj, idlField;
159 classObj = this.idl.classes[col.idlClass];
161 classObj = this.idl.classes[this.idlClass];
164 if (!classObj) { return; }
166 const pathParts = dotpath.split(/\./);
169 // find the IDL class definition for the last element in the
170 // path before the .*
171 // An empty pathParts means expand the root class
172 pathParts.forEach((part, pathIdx) => {
174 idlField = classObj.field_map[part];
176 // unless we're at the end of the list, this field should
177 // link to another class.
178 if (idlField && idlField['class'] && (
179 idlField.datatype === 'link' || idlField.datatype === 'org_unit')) {
180 classObj = this.idl.classes[idlField['class']];
183 if (pathIdx < (pathParts.length - 1)) {
184 // we ran out of classes to hop through before
185 // we ran out of path components
186 console.warn('Grid: invalid IDL path: ' + dotpath);
193 'Grid: wildcard path does not resolve to an object:' + dotpath);
197 classObj.fields.forEach(field => {
199 // Only show wildcard fields where we have data to show
200 // Virtual and un-fleshed links will not have any data.
202 field.datatype === 'link' || field.datatype === 'org_unit') {
206 const newCol = col.clone();
207 newCol.isAuto = true;
208 newCol.path = dotpath ? dotpath + '.' + field.name : field.name;
209 newCol.label = dotpath ? classObj.label + ': ' + field.label : field.label;
210 newCol.datatype = field.datatype;
212 // Avoid including the class label prefix in the main grid
213 // header display so it doesn't take up so much horizontal space.
214 newCol.headerLabel = field.label;
220 // Returns true if the new column was inserted, false otherwise.
221 // Declared columns take precedence over auto-generated columns
222 // when collisions occur.
223 // Declared columns are inserted in front of auto columns.
224 insertColumn(col: GridColumn): boolean {
227 if (this.getColByName(col.name) || this.getColByPath(col.path)) {
228 // New auto-generated column conflicts with existing
232 // No collisions. Add to the end of the list
233 this.columns.push(col);
238 // Adding a declared column.
241 for (let idx = 0; idx < this.columns.length; idx++) {
242 const testCol = this.columns[idx];
243 if (testCol.name === col.name) { // match found
244 if (testCol.isAuto) {
245 // new column takes precedence, remove the existing column.
246 this.columns.splice(idx, 1);
249 // New column does not take precedence. Avoid
256 // Delcared columns are inserted just before the first auto-column
257 for (let idx = 0; idx < this.columns.length; idx++) {
258 const testCol = this.columns[idx];
259 if (testCol.isAuto) {
261 this.columns.unshift(col);
263 this.columns.splice(idx, 0, col);
269 // No insertion point found. Toss the new column on the end.
270 this.columns.push(col);
274 getColByName(name: string): GridColumn {
275 return this.columns.filter(c => c.name === name)[0];
278 getColByPath(path: string): GridColumn {
280 return this.columns.filter(c => c.path === path)[0];
284 idlInfoFromDotpath(dotpath: string): any {
285 if (!dotpath || !this.idlClass) { return null; }
290 let nextIdlClass = this.idl.classes[this.idlClass];
292 const pathParts = dotpath.split(/\./);
294 for (let i = 0; i < pathParts.length; i++) {
296 const part = pathParts[i];
297 idlParent = idlField;
298 idlClass = nextIdlClass;
299 idlField = idlClass.field_map[part];
301 if (!idlField) { return null; } // invalid IDL path
303 if (i === pathParts.length - 1) {
304 // No more links to process.
308 if (idlField['class'] && (
309 idlField.datatype === 'link' ||
310 idlField.datatype === 'org_unit')) {
311 // The link class on the current field refers to the
312 // class of the link destination, not the current field.
313 // Mark it for processing during the next iteration.
314 nextIdlClass = this.idl.classes[idlField['class']];
319 idlParent: idlParent,
327 this.columns.forEach(col => {
331 col.visible = this.stockVisible.includes(col.name);
335 applyColumnDefaults(col: GridColumn) {
337 if (!col.idlFieldDef) {
338 const idlInfo = this.idlInfoFromDotpath(col.path || col.name);
340 col.idlFieldDef = idlInfo.idlField;
341 col.idlClass = idlInfo.idlClass.name;
343 col.datatype = col.idlFieldDef.datatype;
346 col.label = col.idlFieldDef.label || col.idlFieldDef.name;
351 if (!col.name) { col.name = col.path; }
352 if (!col.flex) { col.flex = 2; }
353 if (!col.align) { col.align = 'left'; }
354 if (!col.label) { col.label = col.name; }
355 if (!col.datatype) { col.datatype = 'text'; }
356 if (!col.isAuto) { col.headerLabel = col.label; }
358 col.visible = !col.hidden;
361 applyColumnSortability(col: GridColumn) {
362 // column sortability defaults to the sortability of the column set.
363 if (col.isSortable === undefined && this.isSortable) {
364 col.isSortable = true;
367 if (col.isMultiSortable === undefined && this.isMultiSortable) {
368 col.isMultiSortable = true;
371 if (col.isMultiSortable) {
372 col.isSortable = true;
375 applyColumnFilterability(col: GridColumn) {
376 // column filterability defaults to the afilterability of the column set.
377 if (col.isFilterable === undefined && this.isFilterable) {
378 col.isFilterable = true;
382 displayColumns(): GridColumn[] {
383 return this.columns.filter(c => c.visible);
386 // Sorted visible columns followed by sorted non-visible columns.
387 // Note we don't sort this.columns directly as it would impact
388 // grid column display ordering.
389 sortForColPicker(): GridColumn[] {
390 const visible = this.columns.filter(c => c.visible);
391 const invisible = this.columns.filter(c => !c.visible);
393 visible.sort((a, b) => a.label < b.label ? -1 : 1);
394 invisible.sort((a, b) => a.label < b.label ? -1 : 1);
396 return visible.concat(invisible);
399 requiredColumns(): GridColumn[] {
400 const visible = this.displayColumns();
401 return visible.concat(
402 this.columns.filter(c => c.required && !c.visible));
405 insertBefore(source: GridColumn, target: GridColumn) {
408 this.columns.forEach((col, idx) => {
409 if (col.name === target.name) { targetIdx = idx; }});
411 this.columns.forEach((col, idx) => {
412 if (col.name === source.name) { sourceIdx = idx; }});
414 if (sourceIdx >= 0) {
415 this.columns.splice(sourceIdx, 1);
418 this.columns.splice(targetIdx, 0, source);
421 // Move visible columns to the front of the list.
422 moveVisibleToFront() {
423 const newCols = this.displayColumns();
424 this.columns.forEach(col => {
425 if (!col.visible) { newCols.push(col); }});
426 this.columns = newCols;
429 moveColumn(col: GridColumn, diff: number) {
430 let srcIdx, targetIdx;
432 this.columns.forEach((c, i) => {
433 if (c.name === col.name) { srcIdx = i; }
436 targetIdx = srcIdx + diff;
439 } else if (targetIdx >= this.columns.length) {
440 // Target index follows the last visible column.
442 this.columns.forEach((c, idx) => {
443 if (c.visible) { lastVisible = idx; }
446 // When moving a column (down) causes one or more
447 // visible columns to shuffle forward, our column
448 // moves into the slot of the last visible column.
449 // Otherwise, put it into the slot directly following
450 // the last visible column.
451 targetIdx = srcIdx <= lastVisible ? lastVisible : lastVisible + 1;
454 // Splice column out of old position, insert at new position.
455 this.columns.splice(srcIdx, 1);
456 this.columns.splice(targetIdx, 0, col);
459 compileSaveObject(): GridColumnPersistConf[] {
460 // only store information about visible columns.
461 // scrunch the data down to just the needed info.
462 return this.displayColumns().map(col => {
463 const c: GridColumnPersistConf = {name : col.name};
464 if (col.align !== 'left') { c.align = col.align; }
465 if (col.flex !== 2) { c.flex = Number(col.flex); }
466 if (Number(col.sort)) { c.sort = Number(col.sort); }
471 applyColumnSettings(conf: GridColumnPersistConf[]) {
473 if (!conf || conf.length === 0) {
474 // No configuration is available, but we have a list of
475 // fields to show or hide by default
477 if (this.defaultVisibleFields) {
478 this.columns.forEach(col => {
479 if (this.defaultVisibleFields.includes(col.name)) {
486 } else if (this.defaultHiddenFields) {
487 this.defaultHiddenFields.forEach(name => {
488 const col = this.getColByName(name);
500 conf.forEach(colConf => {
501 const col = this.getColByName(colConf.name);
502 if (!col) { return; } // no such column in this grid.
505 if (colConf.align) { col.align = colConf.align; }
506 if (colConf.flex) { col.flex = Number(colConf.flex); }
507 if (colConf.sort) { col.sort = Number(colConf.sort); }
509 // Add to new columns array, avoid dupes.
510 if (newCols.filter(c => c.name === col.name).length === 0) {
515 // columns which are not expressed within the saved
516 // configuration are marked as non-visible and
517 // appended to the end of the new list of columns.
518 this.columns.forEach(c => {
519 if (conf.filter(cf => cf.name === c.name).length === 0) {
525 this.columns = newCols;
529 // Maps colunm names to functions which return plain text values for
530 // each mapped column on a given row. This is primarily useful for
531 // generating print-friendly content for grid cells rendered via
534 // USAGE NOTE: Since a cellTemplate can be passed arbitrary context
535 // but a GridCellTextGenerator only gets the row object,
536 // if it's important to include content that's not available
537 // by default in the row object, you may want to stick
538 // it in the row object as an additional attribute.
540 export interface GridCellTextGenerator {
541 [columnName: string]: (row: any) => string;
544 export class GridRowSelector {
545 indexes: {[string: string]: boolean};
547 // Track these so we can emit the selectionChange event
548 // only when the selection actually changes.
549 previousSelection: string[] = [];
551 // Emits the selected indexes on selection change
552 selectionChange: EventEmitter<string[]> = new EventEmitter<string[]>();
558 // Returns true if all of the requested indexes exist in the selector.
559 contains(index: string | string[]): boolean {
560 const indexes = [].concat(index);
561 for (let i = 0; i < indexes.length; i++) { // early exit
562 if (!this.indexes[indexes[i]]) {
570 const keys = this.selected();
572 if (keys.length === this.previousSelection.length &&
573 this.contains(this.previousSelection)) {
574 return; // No change has occurred
577 this.previousSelection = keys;
578 this.selectionChange.emit(keys);
581 select(index: string | string[]) {
582 const indexes = [].concat(index);
583 indexes.forEach(i => this.indexes[i] = true);
587 deselect(index: string | string[]) {
588 const indexes = [].concat(index);
589 indexes.forEach(i => delete this.indexes[i]);
593 toggle(index: string) {
594 if (this.indexes[index]) {
595 this.deselect(index);
601 selected(): string[] {
602 return Object.keys(this.indexes);
606 return this.selected().length === 0;
615 export interface GridRowFlairEntry {
616 icon: string; // name of material icon
617 title?: string; // tooltip string
620 export class GridColumnPersistConf {
627 export class GridPersistConf {
630 columns: GridColumnPersistConf[];
631 hideToolbarActions: string[];
634 export class GridContext {
639 isFilterable: boolean;
640 stickyGridHeader: boolean;
641 isMultiSortable: boolean;
642 useLocalSort: boolean;
644 disableMultiSelect: boolean;
645 disableSelect: boolean;
646 dataSource: GridDataSource;
647 columnSet: GridColumnSet;
648 autoGeneratedColumnOrder: string;
649 rowSelector: GridRowSelector;
650 toolbarLabel: string;
651 toolbarButtons: GridToolbarButton[];
652 toolbarCheckboxes: GridToolbarCheckbox[];
653 toolbarActions: GridToolbarAction[];
654 lastSelectedIndex: any;
655 pageChanges: Subscription;
656 rowFlairIsEnabled: boolean;
657 rowFlairCallback: (row: any) => GridRowFlairEntry;
658 rowClassCallback: (row: any) => string;
659 cellClassCallback: (row: any, col: GridColumn) => string;
660 defaultVisibleFields: string[];
661 defaultHiddenFields: string[];
662 ignoredFields: string[];
663 overflowCells: boolean;
664 disablePaging: boolean;
665 showDeclaredFieldsOnly: boolean;
666 cellTextGenerator: GridCellTextGenerator;
667 reloadOnColumnChange: boolean;
669 // Allow calling code to know when the select-all-rows-in-page
670 // action has occurred.
671 selectRowsInPageEmitter: EventEmitter<void>;
673 filterControls: QueryList<GridFilterControlComponent>;
675 // Services injected by our grid component
678 store: ServerStoreService;
679 format: FormatService;
684 store: ServerStoreService,
685 format: FormatService) {
690 this.format = format;
691 this.pager = new Pager();
692 this.rowSelector = new GridRowSelector();
693 this.toolbarButtons = [];
694 this.toolbarCheckboxes = [];
695 this.toolbarActions = [];
699 this.selectRowsInPageEmitter = new EventEmitter<void>();
700 this.columnSet = new GridColumnSet(this.idl, this.idlClass);
701 this.columnSet.isSortable = this.isSortable === true;
702 this.columnSet.isFilterable = this.isFilterable === true;
703 this.columnSet.isMultiSortable = this.isMultiSortable === true;
704 this.columnSet.defaultHiddenFields = this.defaultHiddenFields;
705 this.columnSet.defaultVisibleFields = this.defaultVisibleFields;
706 if (!this.pager.limit) {
707 this.pager.limit = this.disablePaging ? MAX_ALL_ROW_COUNT : 10;
709 this.generateColumns();
712 // Load initial settings and data.
714 this.applyGridConfig()
715 .then(ok => this.dataSource.requestPage(this.pager))
716 .then(ok => this.listenToPager());
723 applyGridConfig(): Promise<void> {
724 return this.getGridConfig(this.persistKey)
728 columns = conf.columns;
729 if (conf.limit && !this.disablePaging) {
730 this.pager.limit = conf.limit;
732 this.applyToolbarActionVisibility(conf.hideToolbarActions);
735 // This is called regardless of the presence of saved
736 // settings so defaults can be applied.
737 this.columnSet.applyColumnSettings(columns);
741 applyToolbarActionVisibility(hidden: string[]) {
742 if (!hidden || hidden.length === 0) { return; }
745 this.toolbarActions.forEach(action => {
746 if (action.isGroup) {
748 } else if (!action.isSeparator) {
749 action.hidden = hidden.includes(action.label);
753 // If all actions in a group are hidden, hide the group as well.
754 // Note the group may be marked as hidden in the configuration,
755 // but the addition of new entries within a group should cause
756 // it to be visible again.
757 groups.forEach(group => {
758 const visible = this.toolbarActions
759 .filter(action => action.group === group.label && !action.hidden);
760 group.hidden = visible.length === 0;
765 // Give the UI time to settle before reloading grid data.
766 // This can help when data retrieval depends on a value
767 // getting modified by an angular digest cycle.
770 this.dataSource.reset();
771 this.dataSource.requestPage(this.pager);
775 reloadWithoutPagerReset() {
777 this.dataSource.reset();
778 this.dataSource.requestPage(this.pager);
782 // Sort the existing data source instead of requesting sorted
783 // data from the client. Reset pager to page 1. As with reload(),
784 // give the client a chance to setting before redisplaying.
788 this.sortLocalData();
789 this.dataSource.requestPage(this.pager);
793 // Subscribe or unsubscribe to page-change events from the pager.
795 if (this.pageChanges) { return; }
796 this.pageChanges = this.pager.onChange$.subscribe(
797 val => this.dataSource.requestPage(this.pager));
801 if (!this.pageChanges) { return; }
802 this.pageChanges.unsubscribe();
803 this.pageChanges = null;
806 // Sort data in the data source array
809 const sortDefs = this.dataSource.sort.map(sort => {
810 const column = this.columnSet.getColByName(sort.name);
818 if (!def.col.comparator) {
819 switch (def.col.datatype) {
823 def.col.comparator = (a, b) => {
826 if (a < b) { return -1; }
827 if (a > b) { return 1; }
832 def.col.comparator = (a, b) => {
833 if (a < b) { return -1; }
834 if (a > b) { return 1; }
843 this.dataSource.data.sort((rowA, rowB) => {
845 for (let idx = 0; idx < sortDefs.length; idx++) {
846 const sortDef = sortDefs[idx];
848 const valueA = this.getRowColumnValue(rowA, sortDef.col);
849 const valueB = this.getRowColumnValue(rowB, sortDef.col);
851 if (valueA === '' && valueB === '') { continue; }
852 if (valueA === '' && valueB !== '') { return 1; }
853 if (valueA !== '' && valueB === '') { return -1; }
855 const diff = sortDef.col.comparator(valueA, valueB);
856 if (diff === 0) { continue; }
858 return sortDef.dir === 'DESC' ? -diff : diff;
861 return 0; // No differences found.
865 getRowIndex(row: any): any {
866 const col = this.columnSet.indexColumn;
868 throw new Error('grid index column required');
870 return this.getRowColumnValue(row, col);
873 // Returns position in the data source array of the row with
874 // the provided index.
875 getRowPosition(index: any): number {
876 // for-loop for early exit
877 for (let idx = 0; idx < this.dataSource.data.length; idx++) {
878 const row = this.dataSource.data[idx];
879 if (row !== undefined && index === this.getRowIndex(row)) {
885 // Return the row with the provided index.
886 getRowByIndex(index: any): any {
887 for (let idx = 0; idx < this.dataSource.data.length; idx++) {
888 const row = this.dataSource.data[idx];
889 if (row !== undefined && index === this.getRowIndex(row)) {
895 // Returns all selected rows, regardless of whether they are
896 // currently visible in the grid display.
897 // De-selects previously selected rows which are no longer
898 // present in the grid.
899 getSelectedRows(): any[] {
903 this.rowSelector.selected().forEach(index => {
904 const row = this.getRowByIndex(index);
912 this.rowSelector.deselect(deleted);
916 rowIsSelected(row: any): boolean {
917 const index = this.getRowIndex(row);
918 return this.rowSelector.selected().filter(
923 getRowColumnBareValue(row: any, col: GridColumn): any {
924 if (col.name in row) {
925 return this.getObjectFieldValue(row, col.name);
926 } else if (col.path) {
927 return this.nestedItemFieldValue(row, col);
931 getRowColumnValue(row: any, col: GridColumn): any {
932 const val = this.getRowColumnBareValue(row, col);
934 if (col.datatype === 'bool') {
935 // Avoid string-ifying bools so we can use an <eg-bool/>
936 // in the grid template.
941 const intField = col.dateOnlyIntervalField;
944 this.columnSet.columns.filter(c => c.path === intField)[0];
946 interval = this.getRowColumnBareValue(row, intCol);
950 return this.format.transform({
952 idlClass: col.idlClass,
953 idlField: col.idlFieldDef ? col.idlFieldDef.name : col.name,
954 datatype: col.datatype,
955 datePlusTime: Boolean(col.datePlusTime),
956 timezoneContextOrg: Number(col.timezoneContextOrg),
957 dateOnlyInterval: interval
961 getObjectFieldValue(obj: any, name: string): any {
962 if (typeof obj[name] === 'function') {
969 nestedItemFieldValue(obj: any, col: GridColumn): string {
973 const original = obj;
974 const steps = col.path.split('.');
976 for (let i = 0; i < steps.length; i++) {
977 const step = steps[i];
979 if (obj === null || obj === undefined || typeof obj !== 'object') {
980 // We have run out of data to step through before
981 // reaching the end of the path. Conclude fleshing via
982 // callback if provided then exit.
983 if (col.flesher && obj !== undefined) {
984 return col.flesher(obj, col, original);
989 const class_ = obj.classname;
990 if (class_ && (idlClassDef = this.idl.classes[class_])) {
991 idlField = idlClassDef.field_map[step];
994 obj = this.getObjectFieldValue(obj, step);
997 // We found a nested IDL object which may or may not have
998 // been configured as a top-level column. Flesh the column
999 // metadata with our newly found IDL info.
1001 if (!col.datatype) {
1002 col.datatype = idlField.datatype;
1004 if (!col.idlFieldDef) {
1005 idlField = col.idlFieldDef;
1007 if (!col.idlClass) {
1008 col.idlClass = idlClassDef.name;
1011 col.label = idlField.label || idlField.name;
1019 getColumnTextContent(row: any, col: GridColumn): string {
1020 if (this.columnHasTextGenerator(col)) {
1021 const str = this.cellTextGenerator[col.name](row);
1022 return (str === null || str === undefined) ? '' : str;
1024 if (col.cellTemplate) {
1025 return ''; // avoid 'undefined' values
1027 return this.getRowColumnValue(row, col);
1032 selectOneRow(index: any) {
1033 this.rowSelector.clear();
1034 this.rowSelector.select(index);
1035 this.lastSelectedIndex = index;
1038 selectMultipleRows(indexes: any[]) {
1039 this.rowSelector.clear();
1040 this.rowSelector.select(indexes);
1041 this.lastSelectedIndex = indexes[indexes.length - 1];
1044 // selects or deselects an item, without affecting the others.
1045 // returns true if the item is selected; false if de-selected.
1046 toggleSelectOneRow(index: any) {
1047 if (this.rowSelector.contains(index)) {
1048 this.rowSelector.deselect(index);
1052 this.rowSelector.select(index);
1053 this.lastSelectedIndex = index;
1057 selectRowByPos(pos: number) {
1058 const row = this.dataSource.data[pos];
1060 this.selectOneRow(this.getRowIndex(row));
1064 selectPreviousRow() {
1065 if (!this.lastSelectedIndex) { return; }
1066 const pos = this.getRowPosition(this.lastSelectedIndex);
1067 if (pos === this.pager.offset) {
1068 this.toPrevPage().then(ok => this.selectLastRow(), err => {});
1070 this.selectRowByPos(pos - 1);
1075 if (!this.lastSelectedIndex) { return; }
1076 const pos = this.getRowPosition(this.lastSelectedIndex);
1077 if (pos === (this.pager.offset + this.pager.limit - 1)) {
1078 this.toNextPage().then(ok => this.selectFirstRow(), err => {});
1080 this.selectRowByPos(pos + 1);
1085 // Select the previous row in addition to any currently selected row.
1086 // However, if the previous row is already selected, assume the user
1087 // has reversed direction and now wants to de-select the last selected row.
1088 selectMultiRowsPrevious() {
1089 if (!this.lastSelectedIndex) { return; }
1090 const pos = this.getRowPosition(this.lastSelectedIndex);
1091 const selectedIndexes = this.rowSelector.selected();
1093 const promise = // load the previous page of data if needed
1094 (pos === this.pager.offset) ? this.toPrevPage() : Promise.resolve();
1098 const row = this.dataSource.data[pos - 1];
1099 const newIndex = this.getRowIndex(row);
1100 if (selectedIndexes.filter(i => i === newIndex).length > 0) {
1101 // Prev row is already selected. User is reversing direction.
1102 this.rowSelector.deselect(this.lastSelectedIndex);
1103 this.lastSelectedIndex = newIndex;
1105 this.selectMultipleRows(selectedIndexes.concat(newIndex));
1112 // Select all rows between the previously selected row and
1113 // the provided row, including the provided row.
1114 // This is additive only -- rows are never de-selected.
1115 selectRowRange(index: any) {
1117 if (!this.lastSelectedIndex) {
1118 this.selectOneRow(index);
1122 const next = this.getRowPosition(index);
1123 const prev = this.getRowPosition(this.lastSelectedIndex);
1124 const start = Math.min(prev, next);
1125 const end = Math.max(prev, next);
1127 for (let idx = start; idx <= end; idx++) {
1128 const row = this.dataSource.data[idx];
1130 this.rowSelector.select(this.getRowIndex(row));
1134 this.lastSelectedIndex = index;
1138 // Select the next row in addition to any currently selected row.
1139 // However, if the next row is already selected, assume the user
1140 // has reversed direction and wants to de-select the last selected row.
1141 selectMultiRowsNext() {
1142 if (!this.lastSelectedIndex) { return; }
1143 const pos = this.getRowPosition(this.lastSelectedIndex);
1144 const selectedIndexes = this.rowSelector.selected();
1146 const promise = // load the next page of data if needed
1147 (pos === (this.pager.offset + this.pager.limit - 1)) ?
1148 this.toNextPage() : Promise.resolve();
1152 const row = this.dataSource.data[pos + 1];
1153 const newIndex = this.getRowIndex(row);
1154 if (selectedIndexes.filter(i => i === newIndex).length > 0) {
1155 // Next row is already selected. User is reversing direction.
1156 this.rowSelector.deselect(this.lastSelectedIndex);
1157 this.lastSelectedIndex = newIndex;
1159 this.selectMultipleRows(selectedIndexes.concat(newIndex));
1166 getFirstRowInPage(): any {
1167 return this.dataSource.data[this.pager.offset];
1170 getLastRowInPage(): any {
1171 return this.dataSource.data[this.pager.offset + this.pager.limit - 1];
1175 this.selectOneRow(this.getRowIndex(this.getFirstRowInPage()));
1179 this.selectOneRow(this.getRowIndex(this.getLastRowInPage()));
1182 selectRowsInPage() {
1183 const rows = this.dataSource.getPageOfRows(this.pager);
1184 const indexes = rows.map(r => this.getRowIndex(r));
1185 this.rowSelector.select(indexes);
1186 this.selectRowsInPageEmitter.emit();
1189 toPrevPage(): Promise<any> {
1190 if (this.pager.isFirstPage()) {
1191 return Promise.reject('on first');
1193 // temp ignore pager events since we're calling requestPage manually.
1195 this.pager.decrement();
1196 this.listenToPager();
1197 return this.dataSource.requestPage(this.pager);
1200 toNextPage(): Promise<any> {
1201 if (this.pager.isLastPage()) {
1202 return Promise.reject('on last');
1204 // temp ignore pager events since we're calling requestPage manually.
1206 this.pager.increment();
1207 this.listenToPager();
1208 return this.dataSource.requestPage(this.pager);
1211 getAllRows(): Promise<any> {
1212 const pager = new Pager();
1214 pager.limit = MAX_ALL_ROW_COUNT;
1215 return this.dataSource.requestPage(pager);
1218 // Returns a key/value pair object of visible column data as text.
1219 getRowAsFlatText(row: any): any {
1221 this.columnSet.displayColumns().forEach(col => {
1223 this.getColumnTextContent(row, col);
1228 getAllRowsAsText(): Observable<any> {
1229 return Observable.create(observer => {
1230 this.getAllRows().then(ok => {
1231 this.dataSource.data.forEach(row => {
1232 observer.next(this.getRowAsFlatText(row));
1234 observer.complete();
1239 removeFilters(): void {
1240 this.dataSource.filters = {};
1241 this.columnSet.displayColumns().forEach(col => { col.removeFilter(); });
1242 this.filterControls.forEach(ctl => ctl.reset());
1245 filtersSet(): boolean {
1246 return Object.keys(this.dataSource.filters).length > 0;
1249 gridToCsv(): Promise<string> {
1252 const columns = this.columnSet.displayColumns();
1255 columns.forEach(col => {
1256 csvStr += this.valueToCsv(col.label),
1260 csvStr = csvStr.replace(/,$/, '\n');
1262 return new Promise(resolve => {
1263 this.getAllRowsAsText().subscribe(
1265 columns.forEach(col => {
1266 csvStr += this.valueToCsv(row[col.name]);
1269 csvStr = csvStr.replace(/,$/, '\n');
1272 () => resolve(csvStr)
1278 // prepares a string for inclusion within a CSV document
1279 // by escaping commas and quotes and removing newlines.
1280 valueToCsv(str: string): string {
1282 if (!str) { return ''; }
1283 str = str.replace(/\n/g, '');
1284 if (str.match(/\,/) || str.match(/"/)) {
1285 str = str.replace(/"/g, '""');
1286 str = '"' + str + '"';
1292 if (!this.columnSet.idlClass) { return; }
1294 const pkeyField = this.idl.classes[this.columnSet.idlClass].pkey;
1295 const specifiedColumnOrder = this.autoGeneratedColumnOrder ?
1296 this.autoGeneratedColumnOrder.split(/,/) : [];
1298 // generate columns for all non-virtual fields on the IDL class
1299 const fields = this.idl.classes[this.columnSet.idlClass].fields
1300 .filter(field => !field.virtual);
1302 const sortedFields = this.autoGeneratedColumnOrder ?
1303 this.idl.sortIdlFields(fields, this.autoGeneratedColumnOrder.split(/,/)) :
1306 sortedFields.forEach(field => {
1307 if (!this.ignoredFields.filter(ignored => ignored === field.name).length) {
1308 const col = new GridColumn();
1309 col.name = field.name;
1310 col.label = field.label || field.name;
1311 col.idlFieldDef = field;
1312 col.idlClass = this.columnSet.idlClass;
1313 col.datatype = field.datatype;
1314 col.isIndex = (field.name === pkeyField);
1316 col.headerLabel = col.label;
1318 if (this.showDeclaredFieldsOnly) {
1322 this.columnSet.add(col);
1327 saveGridConfig(): Promise<any> {
1328 if (!this.persistKey) {
1329 throw new Error('Grid persistKey required to save columns');
1331 const conf = new GridPersistConf();
1333 conf.limit = this.pager.limit;
1334 conf.columns = this.columnSet.compileSaveObject();
1336 // Avoid persisting group visibility since that may change
1337 // with the addition of new columns. Always calculate that
1339 conf.hideToolbarActions = this.toolbarActions
1340 .filter(action => !action.isGroup && action.hidden)
1341 .map(action => action.label);
1343 return this.store.setItem('eg.grid.' + this.persistKey, conf);
1346 // TODO: saveGridConfigAsOrgSetting(...)
1348 getGridConfig(persistKey: string): Promise<GridPersistConf> {
1349 if (!persistKey) { return Promise.resolve(null); }
1350 return this.store.getItem('eg.grid.' + persistKey);
1353 columnHasTextGenerator(col: GridColumn): boolean {
1354 return this.cellTextGenerator && col.name in this.cellTextGenerator;
1359 // Actions apply to specific rows
1360 export class GridToolbarAction {
1362 onClick: EventEmitter<any []>;
1363 action: (rows: any[]) => any; // DEPRECATED
1366 isGroup: boolean; // used for group placeholder entries
1367 isSeparator: boolean;
1368 disableOnRows: (rows: any[]) => boolean;
1372 // Buttons are global actions
1373 export class GridToolbarButton {
1375 onClick: EventEmitter<any []>;
1376 action: () => any; // DEPRECATED
1381 export class GridToolbarCheckbox {
1384 onChange: EventEmitter<boolean>;
1387 export interface GridColumnSort {
1392 export class GridDataSource {
1395 sort: GridColumnSort[];
1397 allRowsRetrieved: boolean;
1398 requestingData: boolean;
1399 retrievalError: boolean;
1400 getRows: (pager: Pager, sort: GridColumnSort[]) => Observable<any>;
1410 this.allRowsRetrieved = false;
1413 // called from the template -- no data fetching
1414 getPageOfRows(pager: Pager): any[] {
1416 return this.data.slice(
1417 pager.offset, pager.limit + pager.offset
1418 ).filter(row => row !== undefined);
1423 // called on initial component load and user action (e.g. paging, sorting).
1424 requestPage(pager: Pager): Promise<any> {
1427 this.getPageOfRows(pager).length === pager.limit
1428 // already have all data
1429 || this.allRowsRetrieved
1430 // have no way to get more data.
1433 return Promise.resolve();
1436 // If we have to call out for data, set inFetch
1437 this.requestingData = true;
1438 this.retrievalError = false;
1440 return new Promise((resolve, reject) => {
1441 let idx = pager.offset;
1442 return this.getRows(pager, this.sort).subscribe(
1444 this.data[idx++] = row;
1445 // not updating this.requestingData, as having
1446 // retrieved one row doesn't mean we're done
1447 this.retrievalError = false;
1450 console.error(`grid getRows() error ${err}`);
1451 this.requestingData = false;
1452 this.retrievalError = true;
1456 this.checkAllRetrieved(pager, idx);
1457 this.requestingData = false;
1458 this.retrievalError = false;
1465 // See if the last getRows() call resulted in the final set of data.
1466 checkAllRetrieved(pager: Pager, idx: number) {
1467 if (this.allRowsRetrieved) { return; }
1469 if (idx === 0 || idx < (pager.limit + pager.offset)) {
1470 // last query returned nothing or less than one page.
1471 // confirm we have all of the preceding pages.
1472 if (!this.data.includes(undefined)) {
1473 this.allRowsRetrieved = true;
1474 pager.resultCount = this.data.length;