import { DataSource } from '@angular/cdk/collections'; import { EventEmitter } from '@angular/core'; import { MatPaginator, PageEvent } from '@angular/material/paginator'; import { MatSort, Sort } from '@angular/material/sort'; import { merge, Observable } from 'rxjs'; import { map, tap } from 'rxjs/operators'; import { Recipe } from '../recipe'; export class RecipeListDatasource extends DataSource { public data: Recipe[]; public filteredData: Recipe[]; public productGroup: string; constructor( private readonly productGroupFilter: Observable, private readonly dataObs: Observable, private paginator?: MatPaginator, private sort?: MatSort, ) { super(); this.data = []; this.filteredData = []; this.productGroup = ''; } connect(): Observable { const dataMutations: (EventEmitter | EventEmitter)[] = []; const d = this.dataObs.pipe( tap((x) => { this.data = x; }), ); const pg = this.productGroupFilter.pipe( tap((x) => { this.productGroup = x; }), ); if (this.paginator) { dataMutations.push((this.paginator as MatPaginator).page); } if (this.sort) { dataMutations.push((this.sort as MatSort).sortChange); } return merge(d, pg, ...dataMutations).pipe( map(() => this.getFilteredData(this.data, this.productGroup)), tap((x: Recipe[]) => { if (this.paginator) { this.paginator.length = x.length; } }), tap((x) => { this.filteredData = x; }), map(() => this.getPagedData(this.getSortedData([...this.filteredData]))), ); } disconnect() {} private getFilteredData(data: Recipe[], productGroup: string): Recipe[] { return data.filter((x: Recipe) => productGroup === '' || x.productGroupId === productGroup); } private getPagedData(data: Recipe[]) { if (this.paginator === undefined) { return data; } const startIndex = this.paginator.pageIndex * this.paginator.pageSize; return data.splice(startIndex, this.paginator.pageSize); } private getSortedData(data: Recipe[]) { if (this.sort === undefined) { return data; } if (!this.sort.active || this.sort.direction === '') { return data; } const sort = this.sort as MatSort; return data.sort((a, b) => { const isAsc = sort.direction === 'asc'; switch (sort.active) { case 'name': return compare(a.sku.name, b.sku.name, isAsc); default: return 0; } }); } } /** Simple sort comparator for example ID/Name columns (for client-side sorting). */ const compare = (a: string | number | Date, b: string | number | Date, isAsc: boolean) => (a < b ? -1 : 1) * (isAsc ? 1 : -1); // const compareDate = (a: string, b: string, isAsc: boolean) => // (moment(a, 'DD-MMM-YYYY').toDate() < moment(b, 'DD-MMM-YYYY').toDate() ? -1 : 1) * // (isAsc ? 1 : -1);