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 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 dataSource: GridDataSource;
425 columnSet: GridColumnSet;
426 rowSelector: GridRowSelector;
427 toolbarButtons: GridToolbarButton[];
428 toolbarCheckboxes: GridToolbarCheckbox[];
429 toolbarActions: GridToolbarAction[];
430 lastSelectedIndex: any;
431 pageChanges: Subscription;
432 rowFlairIsEnabled: boolean;
433 rowFlairCallback: (row: any) => GridRowFlairEntry;
434 rowClassCallback: (row: any) => string;
435 cellClassCallback: (row: any, col: GridColumn) => string;
436 defaultVisibleFields: string[];
437 defaultHiddenFields: string[];
438 overflowCells: boolean;
440 // Services injected by our grid component
443 store: ServerStoreService;
444 format: FormatService;
449 store: ServerStoreService,
450 format: FormatService) {
455 this.format = format;
456 this.pager = new Pager();
457 this.pager.limit = 10;
458 this.rowSelector = new GridRowSelector();
459 this.toolbarButtons = [];
460 this.toolbarCheckboxes = [];
461 this.toolbarActions = [];
465 this.columnSet = new GridColumnSet(this.idl, this.idlClass);
466 this.columnSet.isSortable = this.isSortable === true;
467 this.columnSet.isMultiSortable = this.isMultiSortable === true;
468 this.columnSet.defaultHiddenFields = this.defaultHiddenFields;
469 this.columnSet.defaultVisibleFields = this.defaultVisibleFields;
470 this.generateColumns();
473 // Load initial settings and data.
475 this.applyGridConfig()
476 .then(ok => this.dataSource.requestPage(this.pager))
477 .then(ok => this.listenToPager());
484 applyGridConfig(): Promise<void> {
485 return this.getGridConfig(this.persistKey)
489 columns = conf.columns;
491 this.pager.limit = conf.limit;
495 // This is called regardless of the presence of saved
496 // settings so defaults can be applied.
497 this.columnSet.applyColumnSettings(columns);
502 // Give the UI time to settle before reloading grid data.
503 // This can help when data retrieval depends on a value
504 // getting modified by an angular digest cycle.
507 this.dataSource.reset();
508 this.dataSource.requestPage(this.pager);
512 // Sort the existing data source instead of requesting sorted
513 // data from the client. Reset pager to page 1. As with reload(),
514 // give the client a chance to setting before redisplaying.
518 this.sortLocalData();
519 this.dataSource.requestPage(this.pager);
523 // Subscribe or unsubscribe to page-change events from the pager.
525 if (this.pageChanges) { return; }
526 this.pageChanges = this.pager.onChange$.subscribe(
527 val => this.dataSource.requestPage(this.pager));
531 if (!this.pageChanges) { return; }
532 this.pageChanges.unsubscribe();
533 this.pageChanges = null;
536 // Sort data in the data source array
539 const sortDefs = this.dataSource.sort.map(sort => {
543 col: this.columnSet.getColByName(sort.name)
546 if (!def.col.comparator) {
547 def.col.comparator = (a, b) => {
548 if (a < b) { return -1; }
549 if (a > b) { return 1; }
557 this.dataSource.data.sort((rowA, rowB) => {
559 for (let idx = 0; idx < sortDefs.length; idx++) {
560 const sortDef = sortDefs[idx];
562 const valueA = this.getRowColumnValue(rowA, sortDef.col);
563 const valueB = this.getRowColumnValue(rowB, sortDef.col);
565 if (valueA === '' && valueB === '') { continue; }
566 if (valueA === '' && valueB !== '') { return 1; }
567 if (valueA !== '' && valueB === '') { return -1; }
569 const diff = sortDef.col.comparator(valueA, valueB);
570 if (diff === 0) { continue; }
572 console.log(valueA, valueB, diff);
574 return sortDef.dir === 'DESC' ? -diff : diff;
577 return 0; // No differences found.
581 getRowIndex(row: any): any {
582 const col = this.columnSet.indexColumn;
584 throw new Error('grid index column required');
586 return this.getRowColumnValue(row, col);
589 // Returns position in the data source array of the row with
590 // the provided index.
591 getRowPosition(index: any): number {
592 // for-loop for early exit
593 for (let idx = 0; idx < this.dataSource.data.length; idx++) {
594 const row = this.dataSource.data[idx];
595 if (row !== undefined && index === this.getRowIndex(row)) {
601 // Return the row with the provided index.
602 getRowByIndex(index: any): any {
603 for (let idx = 0; idx < this.dataSource.data.length; idx++) {
604 const row = this.dataSource.data[idx];
605 if (row !== undefined && index === this.getRowIndex(row)) {
611 // Returns all selected rows, regardless of whether they are
612 // currently visible in the grid display.
613 getSelectedRows(): any[] {
615 this.rowSelector.selected().forEach(index => {
616 const row = this.getRowByIndex(index);
624 getRowColumnValue(row: any, col: GridColumn): string {
626 if (col.name in row) {
627 val = this.getObjectFieldValue(row, col.name);
630 val = this.nestedItemFieldValue(row, col);
633 return this.format.transform({value: val, datatype: col.datatype});
636 getObjectFieldValue(obj: any, name: string): any {
637 if (typeof obj[name] === 'function') {
644 nestedItemFieldValue(obj: any, col: GridColumn): string {
648 const original = obj;
649 const steps = col.path.split('.');
651 for (let i = 0; i < steps.length; i++) {
652 const step = steps[i];
654 if (typeof obj !== 'object') {
655 // We have run out of data to step through before
656 // reaching the end of the path. Conclude fleshing via
657 // callback if provided then exit.
658 if (col.flesher && obj !== undefined) {
659 return col.flesher(obj, col, original);
664 const class_ = obj.classname;
665 if (class_ && (idlClassDef = this.idl.classes[class_])) {
666 idlField = idlClassDef.field_map[step];
669 obj = this.getObjectFieldValue(obj, step);
672 // We found a nested IDL object which may or may not have
673 // been configured as a top-level column. Flesh the column
674 // metadata with our newly found IDL info.
677 col.datatype = idlField.datatype;
680 col.label = idlField.label || idlField.name;
688 getColumnTextContent(row: any, col: GridColumn): string {
689 if (col.cellTemplate) {
691 // Extract the text content from the rendered template.
693 return this.getRowColumnValue(row, col);
697 selectOneRow(index: any) {
698 this.rowSelector.clear();
699 this.rowSelector.select(index);
700 this.lastSelectedIndex = index;
703 // selects or deselects an item, without affecting the others.
704 // returns true if the item is selected; false if de-selected.
705 toggleSelectOneRow(index: any) {
706 if (this.rowSelector.contains(index)) {
707 this.rowSelector.deselect(index);
711 this.rowSelector.select(index);
715 selectRowByPos(pos: number) {
716 const row = this.dataSource.data[pos];
718 this.selectOneRow(this.getRowIndex(row));
722 selectPreviousRow() {
723 if (!this.lastSelectedIndex) { return; }
724 const pos = this.getRowPosition(this.lastSelectedIndex);
725 if (pos === this.pager.offset) {
726 this.toPrevPage().then(ok => this.selectLastRow(), err => {});
728 this.selectRowByPos(pos - 1);
733 if (!this.lastSelectedIndex) { return; }
734 const pos = this.getRowPosition(this.lastSelectedIndex);
735 if (pos === (this.pager.offset + this.pager.limit - 1)) {
736 this.toNextPage().then(ok => this.selectFirstRow(), err => {});
738 this.selectRowByPos(pos + 1);
743 this.selectRowByPos(this.pager.offset);
747 this.selectRowByPos(this.pager.offset + this.pager.limit - 1);
750 toPrevPage(): Promise<any> {
751 if (this.pager.isFirstPage()) {
752 return Promise.reject('on first');
754 // temp ignore pager events since we're calling requestPage manually.
756 this.pager.decrement();
757 this.listenToPager();
758 return this.dataSource.requestPage(this.pager);
761 toNextPage(): Promise<any> {
762 if (this.pager.isLastPage()) {
763 return Promise.reject('on last');
765 // temp ignore pager events since we're calling requestPage manually.
767 this.pager.increment();
768 this.listenToPager();
769 return this.dataSource.requestPage(this.pager);
772 getAllRows(): Promise<any> {
773 const pager = new Pager();
775 pager.limit = MAX_ALL_ROW_COUNT;
776 return this.dataSource.requestPage(pager);
779 // Returns a key/value pair object of visible column data as text.
780 getRowAsFlatText(row: any): any {
782 this.columnSet.displayColumns().forEach(col => {
784 this.getColumnTextContent(row, col);
789 getAllRowsAsText(): Observable<any> {
790 return Observable.create(observer => {
791 this.getAllRows().then(ok => {
792 this.dataSource.data.forEach(row => {
793 observer.next(this.getRowAsFlatText(row));
800 gridToCsv(): Promise<string> {
803 const columns = this.columnSet.displayColumns();
806 columns.forEach(col => {
807 csvStr += this.valueToCsv(col.label),
811 csvStr = csvStr.replace(/,$/, '\n');
813 return new Promise(resolve => {
814 this.getAllRowsAsText().subscribe(
816 columns.forEach(col => {
817 csvStr += this.valueToCsv(row[col.name]);
820 csvStr = csvStr.replace(/,$/, '\n');
823 () => resolve(csvStr)
829 // prepares a string for inclusion within a CSV document
830 // by escaping commas and quotes and removing newlines.
831 valueToCsv(str: string): string {
833 if (!str) { return ''; }
834 str = str.replace(/\n/g, '');
835 if (str.match(/\,/) || str.match(/"/)) {
836 str = str.replace(/"/g, '""');
837 str = '"' + str + '"';
843 if (!this.columnSet.idlClass) { return; }
845 const pkeyField = this.idl.classes[this.columnSet.idlClass].pkey;
847 // generate columns for all non-virtual fields on the IDL class
848 this.idl.classes[this.columnSet.idlClass].fields
849 .filter(field => !field.virtual)
851 const col = new GridColumn();
852 col.name = field.name;
853 col.label = field.label || field.name;
854 col.idlFieldDef = field;
855 col.datatype = field.datatype;
856 col.isIndex = (field.name === pkeyField);
858 this.columnSet.add(col);
862 saveGridConfig(): Promise<any> {
863 if (!this.persistKey) {
864 throw new Error('Grid persistKey required to save columns');
866 const conf = new GridPersistConf();
868 conf.limit = this.pager.limit;
869 conf.columns = this.columnSet.compileSaveObject();
871 return this.store.setItem('eg.grid.' + this.persistKey, conf);
874 // TODO: saveGridConfigAsOrgSetting(...)
876 getGridConfig(persistKey: string): Promise<GridPersistConf> {
877 if (!persistKey) { return Promise.resolve(null); }
878 return this.store.getItem('eg.grid.' + persistKey);
883 // Actions apply to specific rows
884 export class GridToolbarAction {
886 action: (rows: any[]) => any;
889 // Buttons are global actions
890 export class GridToolbarButton {
896 export class GridToolbarCheckbox {
898 onChange: (checked: boolean) => void;
901 export class GridDataSource {
905 allRowsRetrieved: boolean;
906 getRows: (pager: Pager, sort: any[]) => Observable<any>;
915 this.allRowsRetrieved = false;
918 // called from the template -- no data fetching
919 getPageOfRows(pager: Pager): any[] {
921 return this.data.slice(
922 pager.offset, pager.limit + pager.offset
923 ).filter(row => row !== undefined);
928 // called on initial component load and user action (e.g. paging, sorting).
929 requestPage(pager: Pager): Promise<any> {
932 this.getPageOfRows(pager).length === pager.limit
933 // already have all data
934 || this.allRowsRetrieved
935 // have no way to get more data.
938 return Promise.resolve();
941 return new Promise((resolve, reject) => {
942 let idx = pager.offset;
943 return this.getRows(pager, this.sort).subscribe(
944 row => this.data[idx++] = row,
946 console.error(`grid getRows() error ${err}`);
950 this.checkAllRetrieved(pager, idx);
957 // See if the last getRows() call resulted in the final set of data.
958 checkAllRetrieved(pager: Pager, idx: number) {
959 if (this.allRowsRetrieved) { return; }
961 if (idx === 0 || idx < (pager.limit + pager.offset)) {
962 // last query returned nothing or less than one page.
963 // confirm we have all of the preceding pages.
964 if (!this.data.includes(undefined)) {
965 this.allRowsRetrieved = true;
966 pager.resultCount = this.data.length;