brewman/overlord/src/app/purchase-entries/purchase-entries-datasource.ts

63 lines
1.9 KiB
TypeScript
Raw Normal View History

import { DataSource } from '@angular/cdk/collections';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { merge, Observable, of as observableOf } from 'rxjs';
import { map } from 'rxjs/operators';
import { PurchaseEntriesItem } from './purchase-entries-item';
/** Simple sort comparator for example ID/Name columns (for client-side sorting). */
function compare(a, b, isAsc) {
return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
}
export class PurchaseEntriesDataSource extends DataSource<PurchaseEntriesItem> {
constructor(
private paginator: MatPaginator,
private sort: MatSort,
public data: PurchaseEntriesItem[],
) {
super();
}
connect(): Observable<PurchaseEntriesItem[]> {
const dataMutations = [observableOf(this.data), this.paginator.page, this.sort.sortChange];
// Set the paginators length
this.paginator.length = this.data.length;
return merge(...dataMutations).pipe(
map(() => this.getPagedData(this.getSortedData([...this.data]))),
);
}
disconnect() {}
private getPagedData(data: PurchaseEntriesItem[]) {
const startIndex = this.paginator.pageIndex * this.paginator.pageSize;
return data.splice(startIndex, this.paginator.pageSize);
}
private getSortedData(data: PurchaseEntriesItem[]) {
if (!this.sort.active || this.sort.direction === '') {
return data;
}
return data.sort((a, b) => {
const isAsc = this.sort.direction === 'asc';
switch (this.sort.active) {
case 'date':
return compare(a.date, b.date, isAsc);
case 'supplier':
return compare(a.supplier, b.supplier, isAsc);
case 'product':
return compare(a.product, b.product, isAsc);
case 'amount':
return compare(+a.amount, +b.amount, isAsc);
default:
return 0;
}
});
}
}