2 * Collection of grid related classses and interfaces.
4 import {TemplateRef} from '@angular/core';
5 import {Observable} from 'rxjs/Observable';
6 import {Subscription} from 'rxjs/Subscription';
7 import {IdlService, IdlObject} from '@eg/core/idl.service';
8 import {OrgService} from '@eg/core/org.service';
9 import {ServerStoreService} from '@eg/core/server-store.service';
10 import {FormatService} from '@eg/core/format.service';
11 import {Pager} from '@eg/share/util/pager';
13 const MAX_ALL_ROW_COUNT = 10000;
15 export class GridColumn {
27 datePlusTime: boolean;
28 cellTemplate: TemplateRef<any>;
31 isDragTarget: boolean;
33 isMultiSortable: boolean;
34 comparator: (valueA: any, valueB: any) => number;
36 // True if the column was automatically generated.
39 flesher: (obj: any, col: GridColumn, item: any) => any;
41 getCellContext(row: any) {
45 userContext: this.cellContext
50 export class GridColumnSet {
51 columns: GridColumn[];
53 indexColumn: GridColumn;
55 isMultiSortable: boolean;
56 stockVisible: string[];
58 defaultHiddenFields: string[];
59 defaultVisibleFields: string[];
61 constructor(idl: IdlService, idlClass?: string) {
64 this.stockVisible = [];
65 this.idlClass = idlClass;
68 add(col: GridColumn) {
70 this.applyColumnDefaults(col);
72 if (!this.insertColumn(col)) {
73 // Column was rejected as a duplicate.
77 if (col.isIndex) { this.indexColumn = col; }
79 // track which fields are visible on page load.
81 this.stockVisible.push(col.name);
84 this.applyColumnSortability(col);
87 // Returns true if the new column was inserted, false otherwise.
88 // Declared columns take precedence over auto-generated columns
89 // when collisions occur.
90 // Declared columns are inserted in front of auto columns.
91 insertColumn(col: GridColumn): boolean {
94 if (this.getColByName(col.name)) {
95 // New auto-generated column conflicts with existing
99 // No collisions. Add to the end of the list
100 this.columns.push(col);
105 // Adding a declared column.
108 for (let idx = 0; idx < this.columns.length; idx++) {
109 const testCol = this.columns[idx];
110 if (testCol.name === col.name) { // match found
111 if (testCol.isAuto) {
112 // new column takes precedence, remove the existing column.
113 this.columns.splice(idx, 1);
116 // New column does not take precedence. Avoid
123 // Delcared columns are inserted just before the first auto-column
124 for (let idx = 0; idx < this.columns.length; idx++) {
125 const testCol = this.columns[idx];
126 if (testCol.isAuto) {
128 this.columns.unshift(col);
130 this.columns.splice(idx - 1, 0, col);
136 // No insertion point found. Toss the new column on the end.
137 this.columns.push(col);
141 getColByName(name: string): GridColumn {
142 return this.columns.filter(c => c.name === name)[0];
145 idlInfoFromDotpath(dotpath: string): any {
146 if (!dotpath || !this.idlClass) { return null; }
150 let idlClass = this.idl.classes[this.idlClass];
152 const pathParts = dotpath.split(/\./);
154 for (let i = 0; i < pathParts.length; i++) {
155 const part = pathParts[i];
156 idlParent = idlField;
157 idlField = idlClass.field_map[part];
160 if (idlField['class'] && (
161 idlField.datatype === 'link' ||
162 idlField.datatype === 'org_unit')) {
163 idlClass = this.idl.classes[idlField['class']];
171 idlParent: idlParent,
179 this.columns.forEach(col => {
183 col.visible = this.stockVisible.includes(col.name);
187 applyColumnDefaults(col: GridColumn) {
189 if (!col.idlFieldDef && col.path) {
190 const idlInfo = this.idlInfoFromDotpath(col.path);
192 col.idlFieldDef = idlInfo.idlField;
194 col.label = col.idlFieldDef.label || col.idlFieldDef.name;
195 col.datatype = col.idlFieldDef.datatype;
200 if (!col.name) { col.name = col.path; }
201 if (!col.flex) { col.flex = 2; }
202 if (!col.align) { col.align = 'left'; }
203 if (!col.label) { col.label = col.name; }
204 if (!col.datatype) { col.datatype = 'text'; }
206 col.visible = !col.hidden;
209 applyColumnSortability(col: GridColumn) {
210 // column sortability defaults to the sortability of the column set.
211 if (col.isSortable === undefined && this.isSortable) {
212 col.isSortable = true;
215 if (col.isMultiSortable === undefined && this.isMultiSortable) {
216 col.isMultiSortable = true;
219 if (col.isMultiSortable) {
220 col.isSortable = true;
224 displayColumns(): GridColumn[] {
225 return this.columns.filter(c => c.visible);
228 insertBefore(source: GridColumn, target: GridColumn) {
231 this.columns.forEach((col, idx) => {
232 if (col.name === target.name) { targetIdx = idx; }});
234 this.columns.forEach((col, idx) => {
235 if (col.name === source.name) { sourceIdx = idx; }});
237 if (sourceIdx >= 0) {
238 this.columns.splice(sourceIdx, 1);
241 this.columns.splice(targetIdx, 0, source);
244 // Move visible columns to the front of the list.
245 moveVisibleToFront() {
246 const newCols = this.displayColumns();
247 this.columns.forEach(col => {
248 if (!col.visible) { newCols.push(col); }});
249 this.columns = newCols;
252 moveColumn(col: GridColumn, diff: number) {
253 let srcIdx, targetIdx;
255 this.columns.forEach((c, i) => {
256 if (c.name === col.name) { srcIdx = i; }
259 targetIdx = srcIdx + diff;
262 } else if (targetIdx >= this.columns.length) {
263 // Target index follows the last visible column.
265 this.columns.forEach((c, idx) => {
266 if (c.visible) { lastVisible = idx; }
269 // When moving a column (down) causes one or more
270 // visible columns to shuffle forward, our column
271 // moves into the slot of the last visible column.
272 // Otherwise, put it into the slot directly following
273 // the last visible column.
274 targetIdx = srcIdx <= lastVisible ? lastVisible : lastVisible + 1;
277 // Splice column out of old position, insert at new position.
278 this.columns.splice(srcIdx, 1);
279 this.columns.splice(targetIdx, 0, col);
282 compileSaveObject(): GridColumnPersistConf[] {
283 // only store information about visible columns.
284 // scrunch the data down to just the needed info.
285 return this.displayColumns().map(col => {
286 const c: GridColumnPersistConf = {name : col.name};
287 if (col.align !== 'left') { c.align = col.align; }
288 if (col.flex !== 2) { c.flex = Number(col.flex); }
289 if (Number(col.sort)) { c.sort = Number(c.sort); }
294 applyColumnSettings(conf: GridColumnPersistConf[]) {
296 if (!conf || conf.length === 0) {
297 // No configuration is available, but we have a list of
298 // fields to show or hide by default
300 if (this.defaultVisibleFields) {
301 this.columns.forEach(col => {
302 if (this.defaultVisibleFields.includes(col.name)) {
309 } else if (this.defaultHiddenFields) {
310 this.defaultHiddenFields.forEach(name => {
311 const col = this.getColByName(name);
323 conf.forEach(colConf => {
324 const col = this.getColByName(colConf.name);
325 if (!col) { return; } // no such column in this grid.
328 if (colConf.align) { col.align = colConf.align; }
329 if (colConf.flex) { col.flex = Number(colConf.flex); }
330 if (colConf.sort) { col.sort = Number(colConf.sort); }
332 // Add to new columns array, avoid dupes.
333 if (newCols.filter(c => c.name === col.name).length === 0) {
338 // columns which are not expressed within the saved
339 // configuration are marked as non-visible and
340 // appended to the end of the new list of columns.
341 this.columns.forEach(c => {
342 if (conf.filter(cf => cf.name === c.name).length === 0) {
348 this.columns = newCols;
353 export class GridRowSelector {
354 indexes: {[string: string]: boolean};
360 // Returns true if all of the requested indexes exist in the selector.
361 contains(index: string | string[]): boolean {
362 const indexes = [].concat(index);
363 for (let i = 0; i < indexes.length; i++) { // early exit
364 if (!this.indexes[indexes[i]]) {
371 select(index: string | string[]) {
372 const indexes = [].concat(index);
373 indexes.forEach(i => this.indexes[i] = true);
376 deselect(index: string | string[]) {
377 const indexes = [].concat(index);
378 indexes.forEach(i => delete this.indexes[i]);
381 // Returns the list of selected index values.
382 // in some contexts (template checkboxes) the value for an index is
383 // set to false to deselect instead of having it removed (via deselect()).
385 return Object.keys(this.indexes).filter(
386 ind => Boolean(this.indexes[ind]));
390 return this.selected().length === 0;
398 export interface GridRowFlairEntry {
399 icon: string; // name of material icon
400 title: string; // tooltip string
403 export class GridColumnPersistConf {
410 export class GridPersistConf {
413 columns: GridColumnPersistConf[];
416 export class GridContext {
421 isMultiSortable: boolean;
422 useLocalSort: boolean;
424 disableMultiSelect: boolean;
425 dataSource: GridDataSource;
426 columnSet: GridColumnSet;
427 rowSelector: GridRowSelector;
428 toolbarButtons: GridToolbarButton[];
429 toolbarCheckboxes: GridToolbarCheckbox[];
430 toolbarActions: GridToolbarAction[];
431 lastSelectedIndex: any;
432 pageChanges: Subscription;
433 rowFlairIsEnabled: boolean;
434 rowFlairCallback: (row: any) => GridRowFlairEntry;
435 rowClassCallback: (row: any) => string;
436 cellClassCallback: (row: any, col: GridColumn) => string;
437 defaultVisibleFields: string[];
438 defaultHiddenFields: string[];
439 overflowCells: boolean;
441 // Services injected by our grid component
444 store: ServerStoreService;
445 format: FormatService;
450 store: ServerStoreService,
451 format: FormatService) {
456 this.format = format;
457 this.pager = new Pager();
458 this.pager.limit = 10;
459 this.rowSelector = new GridRowSelector();
460 this.toolbarButtons = [];
461 this.toolbarCheckboxes = [];
462 this.toolbarActions = [];
466 this.columnSet = new GridColumnSet(this.idl, this.idlClass);
467 this.columnSet.isSortable = this.isSortable === true;
468 this.columnSet.isMultiSortable = this.isMultiSortable === true;
469 this.columnSet.defaultHiddenFields = this.defaultHiddenFields;
470 this.columnSet.defaultVisibleFields = this.defaultVisibleFields;
471 this.generateColumns();
474 // Load initial settings and data.
476 this.applyGridConfig()
477 .then(ok => this.dataSource.requestPage(this.pager))
478 .then(ok => this.listenToPager());
485 applyGridConfig(): Promise<void> {
486 return this.getGridConfig(this.persistKey)
490 columns = conf.columns;
492 this.pager.limit = conf.limit;
496 // This is called regardless of the presence of saved
497 // settings so defaults can be applied.
498 this.columnSet.applyColumnSettings(columns);
503 // Give the UI time to settle before reloading grid data.
504 // This can help when data retrieval depends on a value
505 // getting modified by an angular digest cycle.
508 this.dataSource.reset();
509 this.dataSource.requestPage(this.pager);
513 // Sort the existing data source instead of requesting sorted
514 // data from the client. Reset pager to page 1. As with reload(),
515 // give the client a chance to setting before redisplaying.
519 this.sortLocalData();
520 this.dataSource.requestPage(this.pager);
524 // Subscribe or unsubscribe to page-change events from the pager.
526 if (this.pageChanges) { return; }
527 this.pageChanges = this.pager.onChange$.subscribe(
528 val => this.dataSource.requestPage(this.pager));
532 if (!this.pageChanges) { return; }
533 this.pageChanges.unsubscribe();
534 this.pageChanges = null;
537 // Sort data in the data source array
540 const sortDefs = this.dataSource.sort.map(sort => {
544 col: this.columnSet.getColByName(sort.name)
547 if (!def.col.comparator) {
548 def.col.comparator = (a, b) => {
549 if (a < b) { return -1; }
550 if (a > b) { return 1; }
558 this.dataSource.data.sort((rowA, rowB) => {
560 for (let idx = 0; idx < sortDefs.length; idx++) {
561 const sortDef = sortDefs[idx];
563 const valueA = this.getRowColumnValue(rowA, sortDef.col);
564 const valueB = this.getRowColumnValue(rowB, sortDef.col);
566 if (valueA === '' && valueB === '') { continue; }
567 if (valueA === '' && valueB !== '') { return 1; }
568 if (valueA !== '' && valueB === '') { return -1; }
570 const diff = sortDef.col.comparator(valueA, valueB);
571 if (diff === 0) { continue; }
573 console.log(valueA, valueB, diff);
575 return sortDef.dir === 'DESC' ? -diff : diff;
578 return 0; // No differences found.
582 getRowIndex(row: any): any {
583 const col = this.columnSet.indexColumn;
585 throw new Error('grid index column required');
587 return this.getRowColumnValue(row, col);
590 // Returns position in the data source array of the row with
591 // the provided index.
592 getRowPosition(index: any): number {
593 // for-loop for early exit
594 for (let idx = 0; idx < this.dataSource.data.length; idx++) {
595 const row = this.dataSource.data[idx];
596 if (row !== undefined && index === this.getRowIndex(row)) {
602 // Return the row with the provided index.
603 getRowByIndex(index: any): any {
604 for (let idx = 0; idx < this.dataSource.data.length; idx++) {
605 const row = this.dataSource.data[idx];
606 if (row !== undefined && index === this.getRowIndex(row)) {
612 // Returns all selected rows, regardless of whether they are
613 // currently visible in the grid display.
614 getSelectedRows(): any[] {
616 this.rowSelector.selected().forEach(index => {
617 const row = this.getRowByIndex(index);
625 getRowColumnValue(row: any, col: GridColumn): string {
627 if (col.name in row) {
628 val = this.getObjectFieldValue(row, col.name);
631 val = this.nestedItemFieldValue(row, col);
635 return this.format.transform({
637 datatype: col.datatype,
638 datePlusTime: Boolean(col.datePlusTime)
642 getObjectFieldValue(obj: any, name: string): any {
643 if (typeof obj[name] === 'function') {
650 nestedItemFieldValue(obj: any, col: GridColumn): string {
654 const original = obj;
655 const steps = col.path.split('.');
657 for (let i = 0; i < steps.length; i++) {
658 const step = steps[i];
660 if (typeof obj !== 'object') {
661 // We have run out of data to step through before
662 // reaching the end of the path. Conclude fleshing via
663 // callback if provided then exit.
664 if (col.flesher && obj !== undefined) {
665 return col.flesher(obj, col, original);
670 const class_ = obj.classname;
671 if (class_ && (idlClassDef = this.idl.classes[class_])) {
672 idlField = idlClassDef.field_map[step];
675 obj = this.getObjectFieldValue(obj, step);
678 // We found a nested IDL object which may or may not have
679 // been configured as a top-level column. Flesh the column
680 // metadata with our newly found IDL info.
683 col.datatype = idlField.datatype;
686 col.label = idlField.label || idlField.name;
694 getColumnTextContent(row: any, col: GridColumn): string {
695 if (col.cellTemplate) {
697 // Extract the text content from the rendered template.
699 return this.getRowColumnValue(row, col);
703 selectOneRow(index: any) {
704 this.rowSelector.clear();
705 this.rowSelector.select(index);
706 this.lastSelectedIndex = index;
709 // selects or deselects an item, without affecting the others.
710 // returns true if the item is selected; false if de-selected.
711 toggleSelectOneRow(index: any) {
712 if (this.rowSelector.contains(index)) {
713 this.rowSelector.deselect(index);
717 this.rowSelector.select(index);
721 selectRowByPos(pos: number) {
722 const row = this.dataSource.data[pos];
724 this.selectOneRow(this.getRowIndex(row));
728 selectPreviousRow() {
729 if (!this.lastSelectedIndex) { return; }
730 const pos = this.getRowPosition(this.lastSelectedIndex);
731 if (pos === this.pager.offset) {
732 this.toPrevPage().then(ok => this.selectLastRow(), err => {});
734 this.selectRowByPos(pos - 1);
739 if (!this.lastSelectedIndex) { return; }
740 const pos = this.getRowPosition(this.lastSelectedIndex);
741 if (pos === (this.pager.offset + this.pager.limit - 1)) {
742 this.toNextPage().then(ok => this.selectFirstRow(), err => {});
744 this.selectRowByPos(pos + 1);
749 this.selectRowByPos(this.pager.offset);
753 this.selectRowByPos(this.pager.offset + this.pager.limit - 1);
756 toPrevPage(): Promise<any> {
757 if (this.pager.isFirstPage()) {
758 return Promise.reject('on first');
760 // temp ignore pager events since we're calling requestPage manually.
762 this.pager.decrement();
763 this.listenToPager();
764 return this.dataSource.requestPage(this.pager);
767 toNextPage(): Promise<any> {
768 if (this.pager.isLastPage()) {
769 return Promise.reject('on last');
771 // temp ignore pager events since we're calling requestPage manually.
773 this.pager.increment();
774 this.listenToPager();
775 return this.dataSource.requestPage(this.pager);
778 getAllRows(): Promise<any> {
779 const pager = new Pager();
781 pager.limit = MAX_ALL_ROW_COUNT;
782 return this.dataSource.requestPage(pager);
785 // Returns a key/value pair object of visible column data as text.
786 getRowAsFlatText(row: any): any {
788 this.columnSet.displayColumns().forEach(col => {
790 this.getColumnTextContent(row, col);
795 getAllRowsAsText(): Observable<any> {
796 return Observable.create(observer => {
797 this.getAllRows().then(ok => {
798 this.dataSource.data.forEach(row => {
799 observer.next(this.getRowAsFlatText(row));
806 gridToCsv(): Promise<string> {
809 const columns = this.columnSet.displayColumns();
812 columns.forEach(col => {
813 csvStr += this.valueToCsv(col.label),
817 csvStr = csvStr.replace(/,$/, '\n');
819 return new Promise(resolve => {
820 this.getAllRowsAsText().subscribe(
822 columns.forEach(col => {
823 csvStr += this.valueToCsv(row[col.name]);
826 csvStr = csvStr.replace(/,$/, '\n');
829 () => resolve(csvStr)
835 // prepares a string for inclusion within a CSV document
836 // by escaping commas and quotes and removing newlines.
837 valueToCsv(str: string): string {
839 if (!str) { return ''; }
840 str = str.replace(/\n/g, '');
841 if (str.match(/\,/) || str.match(/"/)) {
842 str = str.replace(/"/g, '""');
843 str = '"' + str + '"';
849 if (!this.columnSet.idlClass) { return; }
851 const pkeyField = this.idl.classes[this.columnSet.idlClass].pkey;
853 // generate columns for all non-virtual fields on the IDL class
854 this.idl.classes[this.columnSet.idlClass].fields
855 .filter(field => !field.virtual)
857 const col = new GridColumn();
858 col.name = field.name;
859 col.label = field.label || field.name;
860 col.idlFieldDef = field;
861 col.datatype = field.datatype;
862 col.isIndex = (field.name === pkeyField);
864 this.columnSet.add(col);
868 saveGridConfig(): Promise<any> {
869 if (!this.persistKey) {
870 throw new Error('Grid persistKey required to save columns');
872 const conf = new GridPersistConf();
874 conf.limit = this.pager.limit;
875 conf.columns = this.columnSet.compileSaveObject();
877 return this.store.setItem('eg.grid.' + this.persistKey, conf);
880 // TODO: saveGridConfigAsOrgSetting(...)
882 getGridConfig(persistKey: string): Promise<GridPersistConf> {
883 if (!persistKey) { return Promise.resolve(null); }
884 return this.store.getItem('eg.grid.' + persistKey);
889 // Actions apply to specific rows
890 export class GridToolbarAction {
892 action: (rows: any[]) => any;
895 // Buttons are global actions
896 export class GridToolbarButton {
902 export class GridToolbarCheckbox {
904 onChange: (checked: boolean) => void;
907 export class GridDataSource {
911 allRowsRetrieved: boolean;
912 getRows: (pager: Pager, sort: any[]) => Observable<any>;
921 this.allRowsRetrieved = false;
924 // called from the template -- no data fetching
925 getPageOfRows(pager: Pager): any[] {
927 return this.data.slice(
928 pager.offset, pager.limit + pager.offset
929 ).filter(row => row !== undefined);
934 // called on initial component load and user action (e.g. paging, sorting).
935 requestPage(pager: Pager): Promise<any> {
938 this.getPageOfRows(pager).length === pager.limit
939 // already have all data
940 || this.allRowsRetrieved
941 // have no way to get more data.
944 return Promise.resolve();
947 return new Promise((resolve, reject) => {
948 let idx = pager.offset;
949 return this.getRows(pager, this.sort).subscribe(
950 row => this.data[idx++] = row,
952 console.error(`grid getRows() error ${err}`);
956 this.checkAllRetrieved(pager, idx);
963 // See if the last getRows() call resulted in the final set of data.
964 checkAllRetrieved(pager: Pager, idx: number) {
965 if (this.allRowsRetrieved) { return; }
967 if (idx === 0 || idx < (pager.limit + pager.offset)) {
968 // last query returned nothing or less than one page.
969 // confirm we have all of the preceding pages.
970 if (!this.data.includes(undefined)) {
971 this.allRowsRetrieved = true;
972 pager.resultCount = this.data.length;