2 * Collection of grid related classses and interfaces.
4 import {TemplateRef} 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 {
26 datePlusTime: boolean;
27 cellTemplate: TemplateRef<any>;
30 isDragTarget: boolean;
32 isMultiSortable: boolean;
33 comparator: (valueA: any, valueB: any) => number;
35 // True if the column was automatically generated.
38 flesher: (obj: any, col: GridColumn, item: any) => any;
40 getCellContext(row: any) {
44 userContext: this.cellContext
49 export class GridColumnSet {
50 columns: GridColumn[];
52 indexColumn: GridColumn;
54 isMultiSortable: boolean;
55 stockVisible: string[];
57 defaultHiddenFields: string[];
58 defaultVisibleFields: string[];
60 constructor(idl: IdlService, idlClass?: string) {
63 this.stockVisible = [];
64 this.idlClass = idlClass;
67 add(col: GridColumn) {
69 this.applyColumnDefaults(col);
71 if (!this.insertColumn(col)) {
72 // Column was rejected as a duplicate.
76 if (col.isIndex) { this.indexColumn = col; }
78 // track which fields are visible on page load.
80 this.stockVisible.push(col.name);
83 this.applyColumnSortability(col);
86 // Returns true if the new column was inserted, false otherwise.
87 // Declared columns take precedence over auto-generated columns
88 // when collisions occur.
89 // Declared columns are inserted in front of auto columns.
90 insertColumn(col: GridColumn): boolean {
93 if (this.getColByName(col.name)) {
94 // New auto-generated column conflicts with existing
98 // No collisions. Add to the end of the list
99 this.columns.push(col);
104 // Adding a declared column.
107 for (let idx = 0; idx < this.columns.length; idx++) {
108 const testCol = this.columns[idx];
109 if (testCol.name === col.name) { // match found
110 if (testCol.isAuto) {
111 // new column takes precedence, remove the existing column.
112 this.columns.splice(idx, 1);
115 // New column does not take precedence. Avoid
122 // Delcared columns are inserted just before the first auto-column
123 for (let idx = 0; idx < this.columns.length; idx++) {
124 const testCol = this.columns[idx];
125 if (testCol.isAuto) {
127 this.columns.unshift(col);
129 this.columns.splice(idx - 1, 0, col);
135 // No insertion point found. Toss the new column on the end.
136 this.columns.push(col);
140 getColByName(name: string): GridColumn {
141 return this.columns.filter(c => c.name === name)[0];
144 idlInfoFromDotpath(dotpath: string): any {
145 if (!dotpath || !this.idlClass) { return null; }
149 let idlClass = this.idl.classes[this.idlClass];
151 const pathParts = dotpath.split(/\./);
153 for (let i = 0; i < pathParts.length; i++) {
154 const part = pathParts[i];
155 idlParent = idlField;
156 idlField = idlClass.field_map[part];
159 if (idlField['class'] && (
160 idlField.datatype === 'link' ||
161 idlField.datatype === 'org_unit')) {
162 idlClass = this.idl.classes[idlField['class']];
170 idlParent: idlParent,
178 this.columns.forEach(col => {
182 col.visible = this.stockVisible.includes(col.name);
186 applyColumnDefaults(col: GridColumn) {
188 if (!col.idlFieldDef && col.path) {
189 const idlInfo = this.idlInfoFromDotpath(col.path);
191 col.idlFieldDef = idlInfo.idlField;
193 col.label = col.idlFieldDef.label || col.idlFieldDef.name;
194 col.datatype = col.idlFieldDef.datatype;
199 if (!col.name) { col.name = col.path; }
200 if (!col.flex) { col.flex = 2; }
201 if (!col.align) { col.align = 'left'; }
202 if (!col.label) { col.label = col.name; }
203 if (!col.datatype) { col.datatype = 'text'; }
205 col.visible = !col.hidden;
208 applyColumnSortability(col: GridColumn) {
209 // column sortability defaults to the sortability of the column set.
210 if (col.isSortable === undefined && this.isSortable) {
211 col.isSortable = true;
214 if (col.isMultiSortable === undefined && this.isMultiSortable) {
215 col.isMultiSortable = true;
218 if (col.isMultiSortable) {
219 col.isSortable = true;
223 displayColumns(): GridColumn[] {
224 return this.columns.filter(c => c.visible);
227 insertBefore(source: GridColumn, target: GridColumn) {
230 this.columns.forEach((col, idx) => {
231 if (col.name === target.name) { targetIdx = idx; }});
233 this.columns.forEach((col, idx) => {
234 if (col.name === source.name) { sourceIdx = idx; }});
236 if (sourceIdx >= 0) {
237 this.columns.splice(sourceIdx, 1);
240 this.columns.splice(targetIdx, 0, source);
243 // Move visible columns to the front of the list.
244 moveVisibleToFront() {
245 const newCols = this.displayColumns();
246 this.columns.forEach(col => {
247 if (!col.visible) { newCols.push(col); }});
248 this.columns = newCols;
251 moveColumn(col: GridColumn, diff: number) {
252 let srcIdx, targetIdx;
254 this.columns.forEach((c, i) => {
255 if (c.name === col.name) { srcIdx = i; }
258 targetIdx = srcIdx + diff;
261 } else if (targetIdx >= this.columns.length) {
262 // Target index follows the last visible column.
264 this.columns.forEach((c, idx) => {
265 if (c.visible) { lastVisible = idx; }
268 // When moving a column (down) causes one or more
269 // visible columns to shuffle forward, our column
270 // moves into the slot of the last visible column.
271 // Otherwise, put it into the slot directly following
272 // the last visible column.
273 targetIdx = srcIdx <= lastVisible ? lastVisible : lastVisible + 1;
276 // Splice column out of old position, insert at new position.
277 this.columns.splice(srcIdx, 1);
278 this.columns.splice(targetIdx, 0, col);
281 compileSaveObject(): GridColumnPersistConf[] {
282 // only store information about visible columns.
283 // scrunch the data down to just the needed info.
284 return this.displayColumns().map(col => {
285 const c: GridColumnPersistConf = {name : col.name};
286 if (col.align !== 'left') { c.align = col.align; }
287 if (col.flex !== 2) { c.flex = Number(col.flex); }
288 if (Number(col.sort)) { c.sort = Number(c.sort); }
293 applyColumnSettings(conf: GridColumnPersistConf[]) {
295 if (!conf || conf.length === 0) {
296 // No configuration is available, but we have a list of
297 // fields to show or hide by default
299 if (this.defaultVisibleFields) {
300 this.columns.forEach(col => {
301 if (this.defaultVisibleFields.includes(col.name)) {
308 } else if (this.defaultHiddenFields) {
309 this.defaultHiddenFields.forEach(name => {
310 const col = this.getColByName(name);
322 conf.forEach(colConf => {
323 const col = this.getColByName(colConf.name);
324 if (!col) { return; } // no such column in this grid.
327 if (colConf.align) { col.align = colConf.align; }
328 if (colConf.flex) { col.flex = Number(colConf.flex); }
329 if (colConf.sort) { col.sort = Number(colConf.sort); }
331 // Add to new columns array, avoid dupes.
332 if (newCols.filter(c => c.name === col.name).length === 0) {
337 // columns which are not expressed within the saved
338 // configuration are marked as non-visible and
339 // appended to the end of the new list of columns.
340 this.columns.forEach(c => {
341 if (conf.filter(cf => cf.name === c.name).length === 0) {
347 this.columns = newCols;
352 export class GridRowSelector {
353 indexes: {[string: string]: boolean};
359 // Returns true if all of the requested indexes exist in the selector.
360 contains(index: string | string[]): boolean {
361 const indexes = [].concat(index);
362 for (let i = 0; i < indexes.length; i++) { // early exit
363 if (!this.indexes[indexes[i]]) {
370 select(index: string | string[]) {
371 const indexes = [].concat(index);
372 indexes.forEach(i => this.indexes[i] = true);
375 deselect(index: string | string[]) {
376 const indexes = [].concat(index);
377 indexes.forEach(i => delete this.indexes[i]);
380 // Returns the list of selected index values.
381 // in some contexts (template checkboxes) the value for an index is
382 // set to false to deselect instead of having it removed (via deselect()).
384 return Object.keys(this.indexes).filter(
385 ind => Boolean(this.indexes[ind]));
389 return this.selected().length === 0;
397 export interface GridRowFlairEntry {
398 icon: string; // name of material icon
399 title?: string; // tooltip string
402 export class GridColumnPersistConf {
409 export class GridPersistConf {
412 columns: GridColumnPersistConf[];
415 export class GridContext {
420 isMultiSortable: boolean;
421 useLocalSort: boolean;
423 disableMultiSelect: boolean;
424 disableSelect: 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;
893 disableOnRows: (rows: any[]) => boolean;
896 // Buttons are global actions
897 export class GridToolbarButton {
903 export class GridToolbarCheckbox {
905 onChange: (checked: boolean) => void;
908 export class GridDataSource {
912 allRowsRetrieved: boolean;
913 getRows: (pager: Pager, sort: any[]) => Observable<any>;
922 this.allRowsRetrieved = false;
925 // called from the template -- no data fetching
926 getPageOfRows(pager: Pager): any[] {
928 return this.data.slice(
929 pager.offset, pager.limit + pager.offset
930 ).filter(row => row !== undefined);
935 // called on initial component load and user action (e.g. paging, sorting).
936 requestPage(pager: Pager): Promise<any> {
939 this.getPageOfRows(pager).length === pager.limit
940 // already have all data
941 || this.allRowsRetrieved
942 // have no way to get more data.
945 return Promise.resolve();
948 return new Promise((resolve, reject) => {
949 let idx = pager.offset;
950 return this.getRows(pager, this.sort).subscribe(
951 row => this.data[idx++] = row,
953 console.error(`grid getRows() error ${err}`);
957 this.checkAllRetrieved(pager, idx);
964 // See if the last getRows() call resulted in the final set of data.
965 checkAllRetrieved(pager: Pager, idx: number) {
966 if (this.allRowsRetrieved) { return; }
968 if (idx === 0 || idx < (pager.limit + pager.offset)) {
969 // last query returned nothing or less than one page.
970 // confirm we have all of the preceding pages.
971 if (!this.data.includes(undefined)) {
972 this.allRowsRetrieved = true;
973 pager.resultCount = this.data.length;