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 const col = new GridColumn();
85 col.label = this.label;
87 col.required = this.required;
88 col.hidden = this.hidden;
89 col.asyncSupportsEmptyTermClick = this.asyncSupportsEmptyTermClick;
90 col.isIndex = this.isIndex;
91 col.cellTemplate = this.cellTemplate;
92 col.cellContext = this.cellContext;
93 col.disableTooltip = this.disableTooltip;
94 col.isSortable = this.isSortable;
95 col.isFilterable = this.isFilterable;
96 col.isMultiSortable = this.isMultiSortable;
97 col.datatype = this.datatype;
98 col.datePlusTime = this.datePlusTime;
99 col.ternaryBool = this.ternaryBool;
100 col.timezoneContextOrg = this.timezoneContextOrg;
101 col.idlClass = this.idlClass;
102 col.isAuto = this.isAuto;
109 export class GridColumnSet {
110 columns: GridColumn[];
112 indexColumn: GridColumn;
114 isFilterable: boolean;
115 isMultiSortable: boolean;
116 stockVisible: string[];
118 defaultHiddenFields: string[];
119 defaultVisibleFields: string[];
121 constructor(idl: IdlService, idlClass?: string) {
124 this.stockVisible = [];
125 this.idlClass = idlClass;
128 add(col: GridColumn) {
130 if (col.path && col.path.match(/\*$/)) {
131 return this.generateWildcardColumns(col);
134 this.applyColumnDefaults(col);
136 if (!this.insertColumn(col)) {
137 // Column was rejected as a duplicate.
141 if (col.isIndex) { this.indexColumn = col; }
143 // track which fields are visible on page load.
145 this.stockVisible.push(col.name);
148 this.applyColumnSortability(col);
149 this.applyColumnFilterability(col);
152 generateWildcardColumns(col: GridColumn) {
154 const dotpath = col.path.replace(/\.?\*$/, '');
155 let classObj, idlField;
158 classObj = this.idl.classes[col.idlClass];
160 classObj = this.idl.classes[this.idlClass];
163 if (!classObj) { return; }
165 const pathParts = dotpath.split(/\./);
167 let oldFieldLabel = '';
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')) {
181 if (oldFieldLabel) { oldFieldLabel += ' : '; }
183 oldFieldLabel += idlField.label;
184 classObj = this.idl.classes[idlField['class']];
187 if (pathIdx < (pathParts.length - 1)) {
188 // we ran out of classes to hop through before
189 // we ran out of path components
190 console.warn('Grid: invalid IDL path: ' + dotpath);
197 'Grid: wildcard path does not resolve to an object:' + dotpath);
201 classObj.fields.forEach(field => {
203 // Only show wildcard fields where we have data to show
204 // Virtual and un-fleshed links will not have any data.
206 field.datatype === 'link' || field.datatype === 'org_unit') {
210 const newCol = col.clone();
211 newCol.isAuto = true;
212 newCol.path = dotpath ? dotpath + '.' + field.name : field.name;
213 newCol.label = dotpath ? classObj.label + ': ' + field.label : field.label;
219 // Returns true if the new column was inserted, false otherwise.
220 // Declared columns take precedence over auto-generated columns
221 // when collisions occur.
222 // Declared columns are inserted in front of auto columns.
223 insertColumn(col: GridColumn): boolean {
226 if (this.getColByName(col.name) || this.getColByPath(col.path)) {
227 // New auto-generated column conflicts with existing
231 // No collisions. Add to the end of the list
232 this.columns.push(col);
237 // Adding a declared column.
240 for (let idx = 0; idx < this.columns.length; idx++) {
241 const testCol = this.columns[idx];
242 if (testCol.name === col.name) { // match found
243 if (testCol.isAuto) {
244 // new column takes precedence, remove the existing column.
245 this.columns.splice(idx, 1);
248 // New column does not take precedence. Avoid
255 // Delcared columns are inserted just before the first auto-column
256 for (let idx = 0; idx < this.columns.length; idx++) {
257 const testCol = this.columns[idx];
258 if (testCol.isAuto) {
260 this.columns.unshift(col);
262 this.columns.splice(idx, 0, col);
268 // No insertion point found. Toss the new column on the end.
269 this.columns.push(col);
273 getColByName(name: string): GridColumn {
274 return this.columns.filter(c => c.name === name)[0];
277 getColByPath(path: string): GridColumn {
279 return this.columns.filter(c => c.path === path)[0];
283 idlInfoFromDotpath(dotpath: string): any {
284 if (!dotpath || !this.idlClass) { return null; }
289 let nextIdlClass = this.idl.classes[this.idlClass];
291 const pathParts = dotpath.split(/\./);
293 for (let i = 0; i < pathParts.length; i++) {
295 const part = pathParts[i];
296 idlParent = idlField;
297 idlClass = nextIdlClass;
298 idlField = idlClass.field_map[part];
300 if (!idlField) { return null; } // invalid IDL path
302 if (i === pathParts.length - 1) {
303 // No more links to process.
307 if (idlField['class'] && (
308 idlField.datatype === 'link' ||
309 idlField.datatype === 'org_unit')) {
310 // The link class on the current field refers to the
311 // class of the link destination, not the current field.
312 // Mark it for processing during the next iteration.
313 nextIdlClass = this.idl.classes[idlField['class']];
318 idlParent: idlParent,
326 this.columns.forEach(col => {
330 col.visible = this.stockVisible.includes(col.name);
334 applyColumnDefaults(col: GridColumn) {
336 if (!col.idlFieldDef) {
337 const idlInfo = this.idlInfoFromDotpath(col.path || col.name);
339 col.idlFieldDef = idlInfo.idlField;
340 col.idlClass = idlInfo.idlClass.name;
342 col.datatype = col.idlFieldDef.datatype;
345 col.label = col.idlFieldDef.label || col.idlFieldDef.name;
350 if (!col.name) { col.name = col.path; }
351 if (!col.flex) { col.flex = 2; }
352 if (!col.align) { col.align = 'left'; }
353 if (!col.label) { col.label = col.name; }
354 if (!col.datatype) { col.datatype = 'text'; }
356 col.visible = !col.hidden;
359 applyColumnSortability(col: GridColumn) {
360 // column sortability defaults to the sortability of the column set.
361 if (col.isSortable === undefined && this.isSortable) {
362 col.isSortable = true;
365 if (col.isMultiSortable === undefined && this.isMultiSortable) {
366 col.isMultiSortable = true;
369 if (col.isMultiSortable) {
370 col.isSortable = true;
373 applyColumnFilterability(col: GridColumn) {
374 // column filterability defaults to the afilterability of the column set.
375 if (col.isFilterable === undefined && this.isFilterable) {
376 col.isFilterable = true;
380 displayColumns(): GridColumn[] {
381 return this.columns.filter(c => c.visible);
384 // Sorted visible columns followed by sorted non-visible columns.
385 // Note we don't sort this.columns directly as it would impact
386 // grid column display ordering.
387 sortForColPicker(): GridColumn[] {
388 const visible = this.columns.filter(c => c.visible);
389 const invisible = this.columns.filter(c => !c.visible);
391 visible.sort((a, b) => a.label < b.label ? -1 : 1);
392 invisible.sort((a, b) => a.label < b.label ? -1 : 1);
394 return visible.concat(invisible);
397 requiredColumns(): GridColumn[] {
398 const visible = this.displayColumns();
399 return visible.concat(
400 this.columns.filter(c => c.required && !c.visible));
403 // Sorted visible columns followed by sorted non-visible columns.
404 // Note we don't sort this.columns directly as it would impact
405 // grid column display ordering.
406 sortForColPicker(): GridColumn[] {
407 const visible = this.columns.filter(c => c.visible);
408 const invisible = this.columns.filter(c => !c.visible);
410 visible.sort((a, b) => a.label < b.label ? -1 : 1);
411 invisible.sort((a, b) => a.label < b.label ? -1 : 1);
413 return visible.concat(invisible);
416 insertBefore(source: GridColumn, target: GridColumn) {
419 this.columns.forEach((col, idx) => {
420 if (col.name === target.name) { targetIdx = idx; }});
422 this.columns.forEach((col, idx) => {
423 if (col.name === source.name) { sourceIdx = idx; }});
425 if (sourceIdx >= 0) {
426 this.columns.splice(sourceIdx, 1);
429 this.columns.splice(targetIdx, 0, source);
432 // Move visible columns to the front of the list.
433 moveVisibleToFront() {
434 const newCols = this.displayColumns();
435 this.columns.forEach(col => {
436 if (!col.visible) { newCols.push(col); }});
437 this.columns = newCols;
440 moveColumn(col: GridColumn, diff: number) {
441 let srcIdx, targetIdx;
443 this.columns.forEach((c, i) => {
444 if (c.name === col.name) { srcIdx = i; }
447 targetIdx = srcIdx + diff;
450 } else if (targetIdx >= this.columns.length) {
451 // Target index follows the last visible column.
453 this.columns.forEach((c, idx) => {
454 if (c.visible) { lastVisible = idx; }
457 // When moving a column (down) causes one or more
458 // visible columns to shuffle forward, our column
459 // moves into the slot of the last visible column.
460 // Otherwise, put it into the slot directly following
461 // the last visible column.
462 targetIdx = srcIdx <= lastVisible ? lastVisible : lastVisible + 1;
465 // Splice column out of old position, insert at new position.
466 this.columns.splice(srcIdx, 1);
467 this.columns.splice(targetIdx, 0, col);
470 compileSaveObject(): GridColumnPersistConf[] {
471 // only store information about visible columns.
472 // scrunch the data down to just the needed info.
473 return this.displayColumns().map(col => {
474 const c: GridColumnPersistConf = {name : col.name};
475 if (col.align !== 'left') { c.align = col.align; }
476 if (col.flex !== 2) { c.flex = Number(col.flex); }
477 if (Number(col.sort)) { c.sort = Number(col.sort); }
482 applyColumnSettings(conf: GridColumnPersistConf[]) {
484 if (!conf || conf.length === 0) {
485 // No configuration is available, but we have a list of
486 // fields to show or hide by default
488 if (this.defaultVisibleFields) {
489 this.columns.forEach(col => {
490 if (this.defaultVisibleFields.includes(col.name)) {
497 } else if (this.defaultHiddenFields) {
498 this.defaultHiddenFields.forEach(name => {
499 const col = this.getColByName(name);
511 conf.forEach(colConf => {
512 const col = this.getColByName(colConf.name);
513 if (!col) { return; } // no such column in this grid.
516 if (colConf.align) { col.align = colConf.align; }
517 if (colConf.flex) { col.flex = Number(colConf.flex); }
518 if (colConf.sort) { col.sort = Number(colConf.sort); }
520 // Add to new columns array, avoid dupes.
521 if (newCols.filter(c => c.name === col.name).length === 0) {
526 // columns which are not expressed within the saved
527 // configuration are marked as non-visible and
528 // appended to the end of the new list of columns.
529 this.columns.forEach(c => {
530 if (conf.filter(cf => cf.name === c.name).length === 0) {
536 this.columns = newCols;
540 // Maps colunm names to functions which return plain text values for
541 // each mapped column on a given row. This is primarily useful for
542 // generating print-friendly content for grid cells rendered via
545 // USAGE NOTE: Since a cellTemplate can be passed arbitrary context
546 // but a GridCellTextGenerator only gets the row object,
547 // if it's important to include content that's not available
548 // by default in the row object, you may want to stick
549 // it in the row object as an additional attribute.
551 export interface GridCellTextGenerator {
552 [columnName: string]: (row: any) => string;
555 export class GridRowSelector {
556 indexes: {[string: string]: boolean};
558 // Track these so we can emit the selectionChange event
559 // only when the selection actually changes.
560 previousSelection: string[] = [];
562 // Emits the selected indexes on selection change
563 selectionChange: EventEmitter<string[]> = new EventEmitter<string[]>();
569 // Returns true if all of the requested indexes exist in the selector.
570 contains(index: string | string[]): boolean {
571 const indexes = [].concat(index);
572 for (let i = 0; i < indexes.length; i++) { // early exit
573 if (!this.indexes[indexes[i]]) {
581 const keys = this.selected();
583 if (keys.length === this.previousSelection.length &&
584 this.contains(this.previousSelection)) {
585 return; // No change has occurred
588 this.previousSelection = keys;
589 this.selectionChange.emit(keys);
592 select(index: string | string[]) {
593 const indexes = [].concat(index);
594 indexes.forEach(i => this.indexes[i] = true);
598 deselect(index: string | string[]) {
599 const indexes = [].concat(index);
600 indexes.forEach(i => delete this.indexes[i]);
604 toggle(index: string) {
605 if (this.indexes[index]) {
606 this.deselect(index);
612 selected(): string[] {
613 return Object.keys(this.indexes);
617 return this.selected().length === 0;
626 export interface GridRowFlairEntry {
627 icon: string; // name of material icon
628 title?: string; // tooltip string
631 export class GridColumnPersistConf {
638 export class GridPersistConf {
641 columns: GridColumnPersistConf[];
642 hideToolbarActions: string[];
645 export class GridContext {
650 isFilterable: boolean;
651 stickyGridHeader: boolean;
652 isMultiSortable: boolean;
653 useLocalSort: boolean;
655 disableMultiSelect: boolean;
656 disableSelect: boolean;
657 dataSource: GridDataSource;
658 columnSet: GridColumnSet;
659 autoGeneratedColumnOrder: string;
660 rowSelector: GridRowSelector;
661 toolbarLabel: string;
662 toolbarButtons: GridToolbarButton[];
663 toolbarCheckboxes: GridToolbarCheckbox[];
664 toolbarActions: GridToolbarAction[];
665 lastSelectedIndex: any;
666 pageChanges: Subscription;
667 rowFlairIsEnabled: boolean;
668 rowFlairCallback: (row: any) => GridRowFlairEntry;
669 rowClassCallback: (row: any) => string;
670 cellClassCallback: (row: any, col: GridColumn) => string;
671 defaultVisibleFields: string[];
672 defaultHiddenFields: string[];
673 ignoredFields: string[];
674 overflowCells: boolean;
675 disablePaging: boolean;
676 showDeclaredFieldsOnly: boolean;
677 cellTextGenerator: GridCellTextGenerator;
678 reloadOnColumnChange: boolean;
680 // Allow calling code to know when the select-all-rows-in-page
681 // action has occurred.
682 selectRowsInPageEmitter: EventEmitter<void>;
684 filterControls: QueryList<GridFilterControlComponent>;
686 // Services injected by our grid component
689 store: ServerStoreService;
690 format: FormatService;
695 store: ServerStoreService,
696 format: FormatService) {
701 this.format = format;
702 this.pager = new Pager();
703 this.rowSelector = new GridRowSelector();
704 this.toolbarButtons = [];
705 this.toolbarCheckboxes = [];
706 this.toolbarActions = [];
710 this.selectRowsInPageEmitter = new EventEmitter<void>();
711 this.columnSet = new GridColumnSet(this.idl, this.idlClass);
712 this.columnSet.isSortable = this.isSortable === true;
713 this.columnSet.isFilterable = this.isFilterable === true;
714 this.columnSet.isMultiSortable = this.isMultiSortable === true;
715 this.columnSet.defaultHiddenFields = this.defaultHiddenFields;
716 this.columnSet.defaultVisibleFields = this.defaultVisibleFields;
717 if (!this.pager.limit) {
718 this.pager.limit = this.disablePaging ? MAX_ALL_ROW_COUNT : 10;
720 this.generateColumns();
723 // Load initial settings and data.
725 this.applyGridConfig()
726 .then(ok => this.dataSource.requestPage(this.pager))
727 .then(ok => this.listenToPager());
734 applyGridConfig(): Promise<void> {
735 return this.getGridConfig(this.persistKey)
739 columns = conf.columns;
740 if (conf.limit && !this.disablePaging) {
741 this.pager.limit = conf.limit;
743 this.applyToolbarActionVisibility(conf.hideToolbarActions);
746 // This is called regardless of the presence of saved
747 // settings so defaults can be applied.
748 this.columnSet.applyColumnSettings(columns);
752 applyToolbarActionVisibility(hidden: string[]) {
753 if (!hidden || hidden.length === 0) { return; }
756 this.toolbarActions.forEach(action => {
757 if (action.isGroup) {
759 } else if (!action.isSeparator) {
760 action.hidden = hidden.includes(action.label);
764 // If all actions in a group are hidden, hide the group as well.
765 // Note the group may be marked as hidden in the configuration,
766 // but the addition of new entries within a group should cause
767 // it to be visible again.
768 groups.forEach(group => {
769 const visible = this.toolbarActions
770 .filter(action => action.group === group.label && !action.hidden);
771 group.hidden = visible.length === 0;
776 // Give the UI time to settle before reloading grid data.
777 // This can help when data retrieval depends on a value
778 // getting modified by an angular digest cycle.
781 this.dataSource.reset();
782 this.dataSource.requestPage(this.pager);
786 reloadWithoutPagerReset() {
788 this.dataSource.reset();
789 this.dataSource.requestPage(this.pager);
793 // Sort the existing data source instead of requesting sorted
794 // data from the client. Reset pager to page 1. As with reload(),
795 // give the client a chance to setting before redisplaying.
799 this.sortLocalData();
800 this.dataSource.requestPage(this.pager);
804 // Subscribe or unsubscribe to page-change events from the pager.
806 if (this.pageChanges) { return; }
807 this.pageChanges = this.pager.onChange$.subscribe(
808 val => this.dataSource.requestPage(this.pager));
812 if (!this.pageChanges) { return; }
813 this.pageChanges.unsubscribe();
814 this.pageChanges = null;
817 // Sort data in the data source array
820 const sortDefs = this.dataSource.sort.map(sort => {
821 const column = this.columnSet.getColByName(sort.name);
829 if (!def.col.comparator) {
830 switch (def.col.datatype) {
834 def.col.comparator = (a, b) => {
837 if (a < b) { return -1; }
838 if (a > b) { return 1; }
843 def.col.comparator = (a, b) => {
844 if (a < b) { return -1; }
845 if (a > b) { return 1; }
854 this.dataSource.data.sort((rowA, rowB) => {
856 for (let idx = 0; idx < sortDefs.length; idx++) {
857 const sortDef = sortDefs[idx];
859 const valueA = this.getRowColumnValue(rowA, sortDef.col);
860 const valueB = this.getRowColumnValue(rowB, sortDef.col);
862 if (valueA === '' && valueB === '') { continue; }
863 if (valueA === '' && valueB !== '') { return 1; }
864 if (valueA !== '' && valueB === '') { return -1; }
866 const diff = sortDef.col.comparator(valueA, valueB);
867 if (diff === 0) { continue; }
869 return sortDef.dir === 'DESC' ? -diff : diff;
872 return 0; // No differences found.
876 getRowIndex(row: any): any {
877 const col = this.columnSet.indexColumn;
879 throw new Error('grid index column required');
881 return this.getRowColumnValue(row, col);
884 // Returns position in the data source array of the row with
885 // the provided index.
886 getRowPosition(index: any): number {
887 // for-loop for early exit
888 for (let idx = 0; idx < this.dataSource.data.length; idx++) {
889 const row = this.dataSource.data[idx];
890 if (row !== undefined && index === this.getRowIndex(row)) {
896 // Return the row with the provided index.
897 getRowByIndex(index: any): any {
898 for (let idx = 0; idx < this.dataSource.data.length; idx++) {
899 const row = this.dataSource.data[idx];
900 if (row !== undefined && index === this.getRowIndex(row)) {
906 // Returns all selected rows, regardless of whether they are
907 // currently visible in the grid display.
908 // De-selects previously selected rows which are no longer
909 // present in the grid.
910 getSelectedRows(): any[] {
914 this.rowSelector.selected().forEach(index => {
915 const row = this.getRowByIndex(index);
923 this.rowSelector.deselect(deleted);
927 rowIsSelected(row: any): boolean {
928 const index = this.getRowIndex(row);
929 return this.rowSelector.selected().filter(
934 getRowColumnBareValue(row: any, col: GridColumn): any {
935 if (col.name in row) {
936 return this.getObjectFieldValue(row, col.name);
937 } else if (col.path) {
938 return this.nestedItemFieldValue(row, col);
942 getRowColumnValue(row: any, col: GridColumn): any {
943 const val = this.getRowColumnBareValue(row, col);
945 if (col.datatype === 'bool') {
946 // Avoid string-ifying bools so we can use an <eg-bool/>
947 // in the grid template.
952 const intField = col.dateOnlyIntervalField;
955 this.columnSet.columns.filter(c => c.path === intField)[0];
957 interval = this.getRowColumnBareValue(row, intCol);
961 return this.format.transform({
963 idlClass: col.idlClass,
964 idlField: col.idlFieldDef ? col.idlFieldDef.name : col.name,
965 datatype: col.datatype,
966 datePlusTime: Boolean(col.datePlusTime),
967 timezoneContextOrg: Number(col.timezoneContextOrg),
968 dateOnlyInterval: interval
972 getObjectFieldValue(obj: any, name: string): any {
973 if (typeof obj[name] === 'function') {
980 nestedItemFieldValue(obj: any, col: GridColumn): string {
984 const original = obj;
985 const steps = col.path.split('.');
987 for (let i = 0; i < steps.length; i++) {
988 const step = steps[i];
990 if (obj === null || obj === undefined || typeof obj !== 'object') {
991 // We have run out of data to step through before
992 // reaching the end of the path. Conclude fleshing via
993 // callback if provided then exit.
994 if (col.flesher && obj !== undefined) {
995 return col.flesher(obj, col, original);
1000 const class_ = obj.classname;
1001 if (class_ && (idlClassDef = this.idl.classes[class_])) {
1002 idlField = idlClassDef.field_map[step];
1005 obj = this.getObjectFieldValue(obj, step);
1008 // We found a nested IDL object which may or may not have
1009 // been configured as a top-level column. Flesh the column
1010 // metadata with our newly found IDL info.
1012 if (!col.datatype) {
1013 col.datatype = idlField.datatype;
1015 if (!col.idlFieldDef) {
1016 idlField = col.idlFieldDef;
1018 if (!col.idlClass) {
1019 col.idlClass = idlClassDef.name;
1022 col.label = idlField.label || idlField.name;
1030 getColumnTextContent(row: any, col: GridColumn): string {
1031 if (this.columnHasTextGenerator(col)) {
1032 const str = this.cellTextGenerator[col.name](row);
1033 return (str === null || str === undefined) ? '' : str;
1035 if (col.cellTemplate) {
1036 return ''; // avoid 'undefined' values
1038 return this.getRowColumnValue(row, col);
1043 selectOneRow(index: any) {
1044 this.rowSelector.clear();
1045 this.rowSelector.select(index);
1046 this.lastSelectedIndex = index;
1049 selectMultipleRows(indexes: any[]) {
1050 this.rowSelector.clear();
1051 this.rowSelector.select(indexes);
1052 this.lastSelectedIndex = indexes[indexes.length - 1];
1055 // selects or deselects an item, without affecting the others.
1056 // returns true if the item is selected; false if de-selected.
1057 toggleSelectOneRow(index: any) {
1058 if (this.rowSelector.contains(index)) {
1059 this.rowSelector.deselect(index);
1063 this.rowSelector.select(index);
1064 this.lastSelectedIndex = index;
1068 selectRowByPos(pos: number) {
1069 const row = this.dataSource.data[pos];
1071 this.selectOneRow(this.getRowIndex(row));
1075 selectPreviousRow() {
1076 if (!this.lastSelectedIndex) { return; }
1077 const pos = this.getRowPosition(this.lastSelectedIndex);
1078 if (pos === this.pager.offset) {
1079 this.toPrevPage().then(ok => this.selectLastRow(), err => {});
1081 this.selectRowByPos(pos - 1);
1086 if (!this.lastSelectedIndex) { return; }
1087 const pos = this.getRowPosition(this.lastSelectedIndex);
1088 if (pos === (this.pager.offset + this.pager.limit - 1)) {
1089 this.toNextPage().then(ok => this.selectFirstRow(), err => {});
1091 this.selectRowByPos(pos + 1);
1096 // Select the previous row in addition to any currently selected row.
1097 // However, if the previous row is already selected, assume the user
1098 // has reversed direction and now wants to de-select the last selected row.
1099 selectMultiRowsPrevious() {
1100 if (!this.lastSelectedIndex) { return; }
1101 const pos = this.getRowPosition(this.lastSelectedIndex);
1102 const selectedIndexes = this.rowSelector.selected();
1104 const promise = // load the previous page of data if needed
1105 (pos === this.pager.offset) ? this.toPrevPage() : Promise.resolve();
1109 const row = this.dataSource.data[pos - 1];
1110 const newIndex = this.getRowIndex(row);
1111 if (selectedIndexes.filter(i => i === newIndex).length > 0) {
1112 // Prev row is already selected. User is reversing direction.
1113 this.rowSelector.deselect(this.lastSelectedIndex);
1114 this.lastSelectedIndex = newIndex;
1116 this.selectMultipleRows(selectedIndexes.concat(newIndex));
1123 // Select all rows between the previously selected row and
1124 // the provided row, including the provided row.
1125 // This is additive only -- rows are never de-selected.
1126 selectRowRange(index: any) {
1128 if (!this.lastSelectedIndex) {
1129 this.selectOneRow(index);
1133 const next = this.getRowPosition(index);
1134 const prev = this.getRowPosition(this.lastSelectedIndex);
1135 const start = Math.min(prev, next);
1136 const end = Math.max(prev, next);
1138 for (let idx = start; idx <= end; idx++) {
1139 const row = this.dataSource.data[idx];
1141 this.rowSelector.select(this.getRowIndex(row));
1145 this.lastSelectedIndex = index;
1149 // Select the next row in addition to any currently selected row.
1150 // However, if the next row is already selected, assume the user
1151 // has reversed direction and wants to de-select the last selected row.
1152 selectMultiRowsNext() {
1153 if (!this.lastSelectedIndex) { return; }
1154 const pos = this.getRowPosition(this.lastSelectedIndex);
1155 const selectedIndexes = this.rowSelector.selected();
1157 const promise = // load the next page of data if needed
1158 (pos === (this.pager.offset + this.pager.limit - 1)) ?
1159 this.toNextPage() : Promise.resolve();
1163 const row = this.dataSource.data[pos + 1];
1164 const newIndex = this.getRowIndex(row);
1165 if (selectedIndexes.filter(i => i === newIndex).length > 0) {
1166 // Next row is already selected. User is reversing direction.
1167 this.rowSelector.deselect(this.lastSelectedIndex);
1168 this.lastSelectedIndex = newIndex;
1170 this.selectMultipleRows(selectedIndexes.concat(newIndex));
1177 getFirstRowInPage(): any {
1178 return this.dataSource.data[this.pager.offset];
1181 getLastRowInPage(): any {
1182 return this.dataSource.data[this.pager.offset + this.pager.limit - 1];
1186 this.selectOneRow(this.getRowIndex(this.getFirstRowInPage()));
1190 this.selectOneRow(this.getRowIndex(this.getLastRowInPage()));
1193 selectRowsInPage() {
1194 const rows = this.dataSource.getPageOfRows(this.pager);
1195 const indexes = rows.map(r => this.getRowIndex(r));
1196 this.rowSelector.select(indexes);
1197 this.selectRowsInPageEmitter.emit();
1200 toPrevPage(): Promise<any> {
1201 if (this.pager.isFirstPage()) {
1202 return Promise.reject('on first');
1204 // temp ignore pager events since we're calling requestPage manually.
1206 this.pager.decrement();
1207 this.listenToPager();
1208 return this.dataSource.requestPage(this.pager);
1211 toNextPage(): Promise<any> {
1212 if (this.pager.isLastPage()) {
1213 return Promise.reject('on last');
1215 // temp ignore pager events since we're calling requestPage manually.
1217 this.pager.increment();
1218 this.listenToPager();
1219 return this.dataSource.requestPage(this.pager);
1222 getAllRows(): Promise<any> {
1223 const pager = new Pager();
1225 pager.limit = MAX_ALL_ROW_COUNT;
1226 return this.dataSource.requestPage(pager);
1229 // Returns a key/value pair object of visible column data as text.
1230 getRowAsFlatText(row: any): any {
1232 this.columnSet.displayColumns().forEach(col => {
1234 this.getColumnTextContent(row, col);
1239 getAllRowsAsText(): Observable<any> {
1240 return Observable.create(observer => {
1241 this.getAllRows().then(ok => {
1242 this.dataSource.data.forEach(row => {
1243 observer.next(this.getRowAsFlatText(row));
1245 observer.complete();
1250 removeFilters(): void {
1251 this.dataSource.filters = {};
1252 this.columnSet.displayColumns().forEach(col => { col.removeFilter(); });
1253 this.filterControls.forEach(ctl => ctl.reset());
1256 filtersSet(): boolean {
1257 return Object.keys(this.dataSource.filters).length > 0;
1260 gridToCsv(): Promise<string> {
1263 const columns = this.columnSet.displayColumns();
1266 columns.forEach(col => {
1267 csvStr += this.valueToCsv(col.label),
1271 csvStr = csvStr.replace(/,$/, '\n');
1273 return new Promise(resolve => {
1274 this.getAllRowsAsText().subscribe(
1276 columns.forEach(col => {
1277 csvStr += this.valueToCsv(row[col.name]);
1280 csvStr = csvStr.replace(/,$/, '\n');
1283 () => resolve(csvStr)
1289 // prepares a string for inclusion within a CSV document
1290 // by escaping commas and quotes and removing newlines.
1291 valueToCsv(str: string): string {
1293 if (!str) { return ''; }
1294 str = str.replace(/\n/g, '');
1295 if (str.match(/\,/) || str.match(/"/)) {
1296 str = str.replace(/"/g, '""');
1297 str = '"' + str + '"';
1303 if (!this.columnSet.idlClass) { return; }
1305 const pkeyField = this.idl.classes[this.columnSet.idlClass].pkey;
1306 const specifiedColumnOrder = this.autoGeneratedColumnOrder ?
1307 this.autoGeneratedColumnOrder.split(/,/) : [];
1309 // generate columns for all non-virtual fields on the IDL class
1310 const fields = this.idl.classes[this.columnSet.idlClass].fields
1311 .filter(field => !field.virtual);
1313 const sortedFields = this.autoGeneratedColumnOrder ?
1314 this.idl.sortIdlFields(fields, this.autoGeneratedColumnOrder.split(/,/)) :
1317 sortedFields.forEach(field => {
1318 if (!this.ignoredFields.filter(ignored => ignored === field.name).length) {
1319 const col = new GridColumn();
1320 col.name = field.name;
1321 col.label = field.label || field.name;
1322 col.idlFieldDef = field;
1323 col.idlClass = this.columnSet.idlClass;
1324 col.datatype = field.datatype;
1325 col.isIndex = (field.name === pkeyField);
1328 if (this.showDeclaredFieldsOnly) {
1332 this.columnSet.add(col);
1337 saveGridConfig(): Promise<any> {
1338 if (!this.persistKey) {
1339 throw new Error('Grid persistKey required to save columns');
1341 const conf = new GridPersistConf();
1343 conf.limit = this.pager.limit;
1344 conf.columns = this.columnSet.compileSaveObject();
1346 // Avoid persisting group visibility since that may change
1347 // with the addition of new columns. Always calculate that
1349 conf.hideToolbarActions = this.toolbarActions
1350 .filter(action => !action.isGroup && action.hidden)
1351 .map(action => action.label);
1353 return this.store.setItem('eg.grid.' + this.persistKey, conf);
1356 // TODO: saveGridConfigAsOrgSetting(...)
1358 getGridConfig(persistKey: string): Promise<GridPersistConf> {
1359 if (!persistKey) { return Promise.resolve(null); }
1360 return this.store.getItem('eg.grid.' + persistKey);
1363 columnHasTextGenerator(col: GridColumn): boolean {
1364 return this.cellTextGenerator && col.name in this.cellTextGenerator;
1369 // Actions apply to specific rows
1370 export class GridToolbarAction {
1372 onClick: EventEmitter<any []>;
1373 action: (rows: any[]) => any; // DEPRECATED
1376 isGroup: boolean; // used for group placeholder entries
1377 isSeparator: boolean;
1378 disableOnRows: (rows: any[]) => boolean;
1382 // Buttons are global actions
1383 export class GridToolbarButton {
1385 onClick: EventEmitter<any []>;
1386 action: () => any; // DEPRECATED
1391 export class GridToolbarCheckbox {
1394 onChange: EventEmitter<boolean>;
1397 export interface GridColumnSort {
1402 export class GridDataSource {
1405 sort: GridColumnSort[];
1407 allRowsRetrieved: boolean;
1408 requestingData: boolean;
1409 retrievalError: boolean;
1410 getRows: (pager: Pager, sort: GridColumnSort[]) => Observable<any>;
1420 this.allRowsRetrieved = false;
1423 // called from the template -- no data fetching
1424 getPageOfRows(pager: Pager): any[] {
1426 return this.data.slice(
1427 pager.offset, pager.limit + pager.offset
1428 ).filter(row => row !== undefined);
1433 // called on initial component load and user action (e.g. paging, sorting).
1434 requestPage(pager: Pager): Promise<any> {
1437 this.getPageOfRows(pager).length === pager.limit
1438 // already have all data
1439 || this.allRowsRetrieved
1440 // have no way to get more data.
1443 return Promise.resolve();
1446 // If we have to call out for data, set inFetch
1447 this.requestingData = true;
1448 this.retrievalError = false;
1450 return new Promise((resolve, reject) => {
1451 let idx = pager.offset;
1452 return this.getRows(pager, this.sort).subscribe(
1454 this.data[idx++] = row;
1455 // not updating this.requestingData, as having
1456 // retrieved one row doesn't mean we're done
1457 this.retrievalError = false;
1460 console.error(`grid getRows() error ${err}`);
1461 this.requestingData = false;
1462 this.retrievalError = true;
1466 this.checkAllRetrieved(pager, idx);
1467 this.requestingData = false;
1468 this.retrievalError = false;
1475 // See if the last getRows() call resulted in the final set of data.
1476 checkAllRetrieved(pager: Pager, idx: number) {
1477 if (this.allRowsRetrieved) { return; }
1479 if (idx === 0 || idx < (pager.limit + pager.offset)) {
1480 // last query returned nothing or less than one page.
1481 // confirm we have all of the preceding pages.
1482 if (!this.data.includes(undefined)) {
1483 this.allRowsRetrieved = true;
1484 pager.resultCount = this.data.length;