2 * Collection of grid related classses and interfaces.
4 import {TemplateRef, EventEmitter} from '@angular/core';
5 import {Observable, Subscription} 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';
12 const MAX_ALL_ROW_COUNT = 10000;
14 export class GridColumn {
23 // IDL class of the object which contains this field.
24 // Not to be confused with the class of a linked object.
28 datePlusTime: boolean;
29 cellTemplate: TemplateRef<any>;
32 isDragTarget: boolean;
34 isMultiSortable: boolean;
35 comparator: (valueA: any, valueB: any) => number;
37 // True if the column was automatically generated.
40 flesher: (obj: any, col: GridColumn, item: any) => any;
42 getCellContext(row: any) {
46 userContext: this.cellContext
51 export class GridColumnSet {
52 columns: GridColumn[];
54 indexColumn: GridColumn;
56 isMultiSortable: boolean;
57 stockVisible: string[];
59 defaultHiddenFields: string[];
60 defaultVisibleFields: string[];
62 constructor(idl: IdlService, idlClass?: string) {
65 this.stockVisible = [];
66 this.idlClass = idlClass;
69 add(col: GridColumn) {
71 this.applyColumnDefaults(col);
73 if (!this.insertColumn(col)) {
74 // Column was rejected as a duplicate.
78 if (col.isIndex) { this.indexColumn = col; }
80 // track which fields are visible on page load.
82 this.stockVisible.push(col.name);
85 this.applyColumnSortability(col);
88 // Returns true if the new column was inserted, false otherwise.
89 // Declared columns take precedence over auto-generated columns
90 // when collisions occur.
91 // Declared columns are inserted in front of auto columns.
92 insertColumn(col: GridColumn): boolean {
95 if (this.getColByName(col.name)) {
96 // New auto-generated column conflicts with existing
100 // No collisions. Add to the end of the list
101 this.columns.push(col);
106 // Adding a declared column.
109 for (let idx = 0; idx < this.columns.length; idx++) {
110 const testCol = this.columns[idx];
111 if (testCol.name === col.name) { // match found
112 if (testCol.isAuto) {
113 // new column takes precedence, remove the existing column.
114 this.columns.splice(idx, 1);
117 // New column does not take precedence. Avoid
124 // Delcared columns are inserted just before the first auto-column
125 for (let idx = 0; idx < this.columns.length; idx++) {
126 const testCol = this.columns[idx];
127 if (testCol.isAuto) {
129 this.columns.unshift(col);
131 this.columns.splice(idx - 1, 0, col);
137 // No insertion point found. Toss the new column on the end.
138 this.columns.push(col);
142 getColByName(name: string): GridColumn {
143 return this.columns.filter(c => c.name === name)[0];
146 idlInfoFromDotpath(dotpath: string): any {
147 if (!dotpath || !this.idlClass) { return null; }
151 let idlClass = this.idl.classes[this.idlClass];
153 const pathParts = dotpath.split(/\./);
155 for (let i = 0; i < pathParts.length; i++) {
156 const part = pathParts[i];
157 idlParent = idlField;
158 idlField = idlClass.field_map[part];
161 if (idlField['class'] && (
162 idlField.datatype === 'link' ||
163 idlField.datatype === 'org_unit')) {
164 idlClass = this.idl.classes[idlField['class']];
172 idlParent: idlParent,
180 this.columns.forEach(col => {
184 col.visible = this.stockVisible.includes(col.name);
188 applyColumnDefaults(col: GridColumn) {
190 if (!col.idlFieldDef && col.path) {
191 const idlInfo = this.idlInfoFromDotpath(col.path);
193 col.idlFieldDef = idlInfo.idlField;
194 col.idlClass = idlInfo.idlClass.name;
196 col.label = col.idlFieldDef.label || col.idlFieldDef.name;
197 col.datatype = col.idlFieldDef.datatype;
202 if (!col.name) { col.name = col.path; }
203 if (!col.flex) { col.flex = 2; }
204 if (!col.align) { col.align = 'left'; }
205 if (!col.label) { col.label = col.name; }
206 if (!col.datatype) { col.datatype = 'text'; }
208 col.visible = !col.hidden;
211 applyColumnSortability(col: GridColumn) {
212 // column sortability defaults to the sortability of the column set.
213 if (col.isSortable === undefined && this.isSortable) {
214 col.isSortable = true;
217 if (col.isMultiSortable === undefined && this.isMultiSortable) {
218 col.isMultiSortable = true;
221 if (col.isMultiSortable) {
222 col.isSortable = true;
226 displayColumns(): GridColumn[] {
227 return this.columns.filter(c => c.visible);
230 insertBefore(source: GridColumn, target: GridColumn) {
233 this.columns.forEach((col, idx) => {
234 if (col.name === target.name) { targetIdx = idx; }});
236 this.columns.forEach((col, idx) => {
237 if (col.name === source.name) { sourceIdx = idx; }});
239 if (sourceIdx >= 0) {
240 this.columns.splice(sourceIdx, 1);
243 this.columns.splice(targetIdx, 0, source);
246 // Move visible columns to the front of the list.
247 moveVisibleToFront() {
248 const newCols = this.displayColumns();
249 this.columns.forEach(col => {
250 if (!col.visible) { newCols.push(col); }});
251 this.columns = newCols;
254 moveColumn(col: GridColumn, diff: number) {
255 let srcIdx, targetIdx;
257 this.columns.forEach((c, i) => {
258 if (c.name === col.name) { srcIdx = i; }
261 targetIdx = srcIdx + diff;
264 } else if (targetIdx >= this.columns.length) {
265 // Target index follows the last visible column.
267 this.columns.forEach((c, idx) => {
268 if (c.visible) { lastVisible = idx; }
271 // When moving a column (down) causes one or more
272 // visible columns to shuffle forward, our column
273 // moves into the slot of the last visible column.
274 // Otherwise, put it into the slot directly following
275 // the last visible column.
276 targetIdx = srcIdx <= lastVisible ? lastVisible : lastVisible + 1;
279 // Splice column out of old position, insert at new position.
280 this.columns.splice(srcIdx, 1);
281 this.columns.splice(targetIdx, 0, col);
284 compileSaveObject(): GridColumnPersistConf[] {
285 // only store information about visible columns.
286 // scrunch the data down to just the needed info.
287 return this.displayColumns().map(col => {
288 const c: GridColumnPersistConf = {name : col.name};
289 if (col.align !== 'left') { c.align = col.align; }
290 if (col.flex !== 2) { c.flex = Number(col.flex); }
291 if (Number(col.sort)) { c.sort = Number(c.sort); }
296 applyColumnSettings(conf: GridColumnPersistConf[]) {
298 if (!conf || conf.length === 0) {
299 // No configuration is available, but we have a list of
300 // fields to show or hide by default
302 if (this.defaultVisibleFields) {
303 this.columns.forEach(col => {
304 if (this.defaultVisibleFields.includes(col.name)) {
311 } else if (this.defaultHiddenFields) {
312 this.defaultHiddenFields.forEach(name => {
313 const col = this.getColByName(name);
325 conf.forEach(colConf => {
326 const col = this.getColByName(colConf.name);
327 if (!col) { return; } // no such column in this grid.
330 if (colConf.align) { col.align = colConf.align; }
331 if (colConf.flex) { col.flex = Number(colConf.flex); }
332 if (colConf.sort) { col.sort = Number(colConf.sort); }
334 // Add to new columns array, avoid dupes.
335 if (newCols.filter(c => c.name === col.name).length === 0) {
340 // columns which are not expressed within the saved
341 // configuration are marked as non-visible and
342 // appended to the end of the new list of columns.
343 this.columns.forEach(c => {
344 if (conf.filter(cf => cf.name === c.name).length === 0) {
350 this.columns = newCols;
355 export class GridRowSelector {
356 indexes: {[string: string]: boolean};
362 // Returns true if all of the requested indexes exist in the selector.
363 contains(index: string | string[]): boolean {
364 const indexes = [].concat(index);
365 for (let i = 0; i < indexes.length; i++) { // early exit
366 if (!this.indexes[indexes[i]]) {
373 select(index: string | string[]) {
374 const indexes = [].concat(index);
375 indexes.forEach(i => this.indexes[i] = true);
378 deselect(index: string | string[]) {
379 const indexes = [].concat(index);
380 indexes.forEach(i => delete this.indexes[i]);
383 // Returns the list of selected index values.
384 // in some contexts (template checkboxes) the value for an index is
385 // set to false to deselect instead of having it removed (via deselect()).
387 return Object.keys(this.indexes).filter(
388 ind => Boolean(this.indexes[ind]));
392 return this.selected().length === 0;
400 export interface GridRowFlairEntry {
401 icon: string; // name of material icon
402 title?: string; // tooltip string
405 export class GridColumnPersistConf {
412 export class GridPersistConf {
415 columns: GridColumnPersistConf[];
418 export class GridContext {
423 isMultiSortable: boolean;
424 useLocalSort: boolean;
426 disableMultiSelect: boolean;
427 disableSelect: boolean;
428 dataSource: GridDataSource;
429 columnSet: GridColumnSet;
430 rowSelector: GridRowSelector;
431 toolbarButtons: GridToolbarButton[];
432 toolbarCheckboxes: GridToolbarCheckbox[];
433 toolbarActions: GridToolbarAction[];
434 lastSelectedIndex: any;
435 pageChanges: Subscription;
436 rowFlairIsEnabled: boolean;
437 rowFlairCallback: (row: any) => GridRowFlairEntry;
438 rowClassCallback: (row: any) => string;
439 cellClassCallback: (row: any, col: GridColumn) => string;
440 defaultVisibleFields: string[];
441 defaultHiddenFields: string[];
442 overflowCells: boolean;
443 showLinkSelectors: boolean;
445 // Services injected by our grid component
448 store: ServerStoreService;
449 format: FormatService;
454 store: ServerStoreService,
455 format: FormatService) {
460 this.format = format;
461 this.pager = new Pager();
462 this.pager.limit = 10;
463 this.rowSelector = new GridRowSelector();
464 this.toolbarButtons = [];
465 this.toolbarCheckboxes = [];
466 this.toolbarActions = [];
470 this.columnSet = new GridColumnSet(this.idl, this.idlClass);
471 this.columnSet.isSortable = this.isSortable === true;
472 this.columnSet.isMultiSortable = this.isMultiSortable === true;
473 this.columnSet.defaultHiddenFields = this.defaultHiddenFields;
474 this.columnSet.defaultVisibleFields = this.defaultVisibleFields;
475 this.generateColumns();
478 // Load initial settings and data.
480 this.applyGridConfig()
481 .then(ok => this.dataSource.requestPage(this.pager))
482 .then(ok => this.listenToPager());
489 applyGridConfig(): Promise<void> {
490 return this.getGridConfig(this.persistKey)
494 columns = conf.columns;
496 this.pager.limit = conf.limit;
500 // This is called regardless of the presence of saved
501 // settings so defaults can be applied.
502 this.columnSet.applyColumnSettings(columns);
507 // Give the UI time to settle before reloading grid data.
508 // This can help when data retrieval depends on a value
509 // getting modified by an angular digest cycle.
512 this.dataSource.reset();
513 this.dataSource.requestPage(this.pager);
517 // Sort the existing data source instead of requesting sorted
518 // data from the client. Reset pager to page 1. As with reload(),
519 // give the client a chance to setting before redisplaying.
523 this.sortLocalData();
524 this.dataSource.requestPage(this.pager);
528 // Subscribe or unsubscribe to page-change events from the pager.
530 if (this.pageChanges) { return; }
531 this.pageChanges = this.pager.onChange$.subscribe(
532 val => this.dataSource.requestPage(this.pager));
536 if (!this.pageChanges) { return; }
537 this.pageChanges.unsubscribe();
538 this.pageChanges = null;
541 // Sort data in the data source array
544 const sortDefs = this.dataSource.sort.map(sort => {
548 col: this.columnSet.getColByName(sort.name)
551 if (!def.col.comparator) {
552 def.col.comparator = (a, b) => {
553 if (a < b) { return -1; }
554 if (a > b) { return 1; }
562 this.dataSource.data.sort((rowA, rowB) => {
564 for (let idx = 0; idx < sortDefs.length; idx++) {
565 const sortDef = sortDefs[idx];
567 const valueA = this.getRowColumnValue(rowA, sortDef.col);
568 const valueB = this.getRowColumnValue(rowB, sortDef.col);
570 if (valueA === '' && valueB === '') { continue; }
571 if (valueA === '' && valueB !== '') { return 1; }
572 if (valueA !== '' && valueB === '') { return -1; }
574 const diff = sortDef.col.comparator(valueA, valueB);
575 if (diff === 0) { continue; }
577 console.log(valueA, valueB, diff);
579 return sortDef.dir === 'DESC' ? -diff : diff;
582 return 0; // No differences found.
586 getRowIndex(row: any): any {
587 const col = this.columnSet.indexColumn;
589 throw new Error('grid index column required');
591 return this.getRowColumnValue(row, col);
594 // Returns position in the data source array of the row with
595 // the provided index.
596 getRowPosition(index: any): number {
597 // for-loop for early exit
598 for (let idx = 0; idx < this.dataSource.data.length; idx++) {
599 const row = this.dataSource.data[idx];
600 if (row !== undefined && index === this.getRowIndex(row)) {
606 // Return the row with the provided index.
607 getRowByIndex(index: any): any {
608 for (let idx = 0; idx < this.dataSource.data.length; idx++) {
609 const row = this.dataSource.data[idx];
610 if (row !== undefined && index === this.getRowIndex(row)) {
616 // Returns all selected rows, regardless of whether they are
617 // currently visible in the grid display.
618 getSelectedRows(): any[] {
620 this.rowSelector.selected().forEach(index => {
621 const row = this.getRowByIndex(index);
629 getRowColumnValue(row: any, col: GridColumn): string {
633 val = this.nestedItemFieldValue(row, col);
634 } else if (col.name in row) {
635 val = this.getObjectFieldValue(row, col.name);
638 return this.format.transform({
640 idlClass: col.idlClass,
641 idlField: col.idlFieldDef ? col.idlFieldDef.name : col.name,
642 datatype: col.datatype,
643 datePlusTime: Boolean(col.datePlusTime)
647 getObjectFieldValue(obj: any, name: string): any {
648 if (typeof obj[name] === 'function') {
655 nestedItemFieldValue(obj: any, col: GridColumn): string {
659 const original = obj;
660 const steps = col.path.split('.');
662 for (let i = 0; i < steps.length; i++) {
663 const step = steps[i];
665 if (obj === null || obj === undefined || typeof obj !== 'object') {
666 // We have run out of data to step through before
667 // reaching the end of the path. Conclude fleshing via
668 // callback if provided then exit.
669 if (col.flesher && obj !== undefined) {
670 return col.flesher(obj, col, original);
675 const class_ = obj.classname;
676 if (class_ && (idlClassDef = this.idl.classes[class_])) {
677 idlField = idlClassDef.field_map[step];
680 obj = this.getObjectFieldValue(obj, step);
683 // We found a nested IDL object which may or may not have
684 // been configured as a top-level column. Flesh the column
685 // metadata with our newly found IDL info.
688 col.datatype = idlField.datatype;
690 if (!col.idlFieldDef) {
691 idlField = col.idlFieldDef;
694 col.idlClass = idlClassDef.name;
697 col.label = idlField.label || idlField.name;
705 getColumnTextContent(row: any, col: GridColumn): string {
706 if (col.cellTemplate) {
708 // Extract the text content from the rendered template.
710 return this.getRowColumnValue(row, col);
714 selectOneRow(index: any) {
715 this.rowSelector.clear();
716 this.rowSelector.select(index);
717 this.lastSelectedIndex = index;
720 // selects or deselects an item, without affecting the others.
721 // returns true if the item is selected; false if de-selected.
722 toggleSelectOneRow(index: any) {
723 if (this.rowSelector.contains(index)) {
724 this.rowSelector.deselect(index);
728 this.rowSelector.select(index);
732 selectRowByPos(pos: number) {
733 const row = this.dataSource.data[pos];
735 this.selectOneRow(this.getRowIndex(row));
739 selectPreviousRow() {
740 if (!this.lastSelectedIndex) { return; }
741 const pos = this.getRowPosition(this.lastSelectedIndex);
742 if (pos === this.pager.offset) {
743 this.toPrevPage().then(ok => this.selectLastRow(), err => {});
745 this.selectRowByPos(pos - 1);
750 if (!this.lastSelectedIndex) { return; }
751 const pos = this.getRowPosition(this.lastSelectedIndex);
752 if (pos === (this.pager.offset + this.pager.limit - 1)) {
753 this.toNextPage().then(ok => this.selectFirstRow(), err => {});
755 this.selectRowByPos(pos + 1);
760 this.selectRowByPos(this.pager.offset);
764 this.selectRowByPos(this.pager.offset + this.pager.limit - 1);
767 toPrevPage(): Promise<any> {
768 if (this.pager.isFirstPage()) {
769 return Promise.reject('on first');
771 // temp ignore pager events since we're calling requestPage manually.
773 this.pager.decrement();
774 this.listenToPager();
775 return this.dataSource.requestPage(this.pager);
778 toNextPage(): Promise<any> {
779 if (this.pager.isLastPage()) {
780 return Promise.reject('on last');
782 // temp ignore pager events since we're calling requestPage manually.
784 this.pager.increment();
785 this.listenToPager();
786 return this.dataSource.requestPage(this.pager);
789 getAllRows(): Promise<any> {
790 const pager = new Pager();
792 pager.limit = MAX_ALL_ROW_COUNT;
793 return this.dataSource.requestPage(pager);
796 // Returns a key/value pair object of visible column data as text.
797 getRowAsFlatText(row: any): any {
799 this.columnSet.displayColumns().forEach(col => {
801 this.getColumnTextContent(row, col);
806 getAllRowsAsText(): Observable<any> {
807 return Observable.create(observer => {
808 this.getAllRows().then(ok => {
809 this.dataSource.data.forEach(row => {
810 observer.next(this.getRowAsFlatText(row));
817 gridToCsv(): Promise<string> {
820 const columns = this.columnSet.displayColumns();
823 columns.forEach(col => {
824 csvStr += this.valueToCsv(col.label),
828 csvStr = csvStr.replace(/,$/, '\n');
830 return new Promise(resolve => {
831 this.getAllRowsAsText().subscribe(
833 columns.forEach(col => {
834 csvStr += this.valueToCsv(row[col.name]);
837 csvStr = csvStr.replace(/,$/, '\n');
840 () => resolve(csvStr)
846 // prepares a string for inclusion within a CSV document
847 // by escaping commas and quotes and removing newlines.
848 valueToCsv(str: string): string {
850 if (!str) { return ''; }
851 str = str.replace(/\n/g, '');
852 if (str.match(/\,/) || str.match(/"/)) {
853 str = str.replace(/"/g, '""');
854 str = '"' + str + '"';
860 if (!this.columnSet.idlClass) { return; }
862 const pkeyField = this.idl.classes[this.columnSet.idlClass].pkey;
864 // generate columns for all non-virtual fields on the IDL class
865 this.idl.classes[this.columnSet.idlClass].fields
866 .filter(field => !field.virtual)
868 const col = new GridColumn();
869 col.name = field.name;
870 col.label = field.label || field.name;
871 col.idlFieldDef = field;
872 col.idlClass = this.columnSet.idlClass;
873 col.datatype = field.datatype;
874 col.isIndex = (field.name === pkeyField);
877 if (this.showLinkSelectors) {
878 const selector = this.idl.getLinkSelector(
879 this.columnSet.idlClass, field.name);
881 col.path = field.name + '.' + selector;
885 this.columnSet.add(col);
889 saveGridConfig(): Promise<any> {
890 if (!this.persistKey) {
891 throw new Error('Grid persistKey required to save columns');
893 const conf = new GridPersistConf();
895 conf.limit = this.pager.limit;
896 conf.columns = this.columnSet.compileSaveObject();
898 return this.store.setItem('eg.grid.' + this.persistKey, conf);
901 // TODO: saveGridConfigAsOrgSetting(...)
903 getGridConfig(persistKey: string): Promise<GridPersistConf> {
904 if (!persistKey) { return Promise.resolve(null); }
905 return this.store.getItem('eg.grid.' + persistKey);
910 // Actions apply to specific rows
911 export class GridToolbarAction {
913 onClick: EventEmitter<any []>;
914 action: (rows: any[]) => any; // DEPRECATED
916 isGroup: boolean; // used for group placeholder entries
917 disableOnRows: (rows: any[]) => boolean;
920 // Buttons are global actions
921 export class GridToolbarButton {
923 onClick: EventEmitter<any []>;
924 action: () => any; // DEPRECATED
928 export class GridToolbarCheckbox {
930 onChange: EventEmitter<boolean>;
933 export class GridDataSource {
937 allRowsRetrieved: boolean;
938 getRows: (pager: Pager, sort: any[]) => Observable<any>;
947 this.allRowsRetrieved = false;
950 // called from the template -- no data fetching
951 getPageOfRows(pager: Pager): any[] {
953 return this.data.slice(
954 pager.offset, pager.limit + pager.offset
955 ).filter(row => row !== undefined);
960 // called on initial component load and user action (e.g. paging, sorting).
961 requestPage(pager: Pager): Promise<any> {
964 this.getPageOfRows(pager).length === pager.limit
965 // already have all data
966 || this.allRowsRetrieved
967 // have no way to get more data.
970 return Promise.resolve();
973 return new Promise((resolve, reject) => {
974 let idx = pager.offset;
975 return this.getRows(pager, this.sort).subscribe(
976 row => this.data[idx++] = row,
978 console.error(`grid getRows() error ${err}`);
982 this.checkAllRetrieved(pager, idx);
989 // See if the last getRows() call resulted in the final set of data.
990 checkAllRetrieved(pager: Pager, idx: number) {
991 if (this.allRowsRetrieved) { return; }
993 if (idx === 0 || idx < (pager.limit + pager.offset)) {
994 // last query returned nothing or less than one page.
995 // confirm we have all of the preceding pages.
996 if (!this.data.includes(undefined)) {
997 this.allRowsRetrieved = true;
998 pager.resultCount = this.data.length;