2020-10-01 15:21:22 +00:00
|
|
|
import { DataSource } from '@angular/cdk/collections';
|
2019-06-12 11:55:10 +00:00
|
|
|
import { MatPaginator } from '@angular/material/paginator';
|
|
|
|
import { MatSort } from '@angular/material/sort';
|
2020-10-01 15:21:22 +00:00
|
|
|
import { map } from 'rxjs/operators';
|
|
|
|
import { merge, Observable, of as observableOf } from 'rxjs';
|
|
|
|
import { LedgerItem } from './ledger';
|
2018-05-25 13:49:00 +00:00
|
|
|
|
|
|
|
export class LedgerDataSource extends DataSource<LedgerItem> {
|
|
|
|
constructor(private paginator: MatPaginator, private sort: MatSort, public data: LedgerItem[]) {
|
|
|
|
super();
|
|
|
|
}
|
|
|
|
|
|
|
|
connect(): Observable<LedgerItem[]> {
|
2020-10-01 15:21:22 +00:00
|
|
|
const dataMutations = [observableOf(this.data), this.paginator.page, this.sort.sortChange];
|
2018-05-25 13:49:00 +00:00
|
|
|
|
|
|
|
// Set the paginators length
|
|
|
|
this.paginator.length = this.data.length;
|
|
|
|
|
2020-10-01 15:21:22 +00:00
|
|
|
return merge(...dataMutations).pipe(
|
|
|
|
map(() => {
|
|
|
|
return this.getPagedData(this.getSortedData([...this.data]));
|
|
|
|
}),
|
|
|
|
);
|
2018-05-25 13:49:00 +00:00
|
|
|
}
|
|
|
|
|
2020-10-01 15:21:22 +00:00
|
|
|
disconnect() {}
|
2018-05-25 13:49:00 +00:00
|
|
|
|
|
|
|
private getPagedData(data: LedgerItem[]) {
|
|
|
|
const startIndex = this.paginator.pageIndex * this.paginator.pageSize;
|
|
|
|
return data.splice(startIndex, this.paginator.pageSize);
|
|
|
|
}
|
|
|
|
|
|
|
|
private getSortedData(data: LedgerItem[]) {
|
|
|
|
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 'debit':
|
|
|
|
return compare(+a.debit, +b.debit, isAsc);
|
|
|
|
case 'credit':
|
|
|
|
return compare(+a.credit, +b.credit, isAsc);
|
|
|
|
default:
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/** 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);
|
|
|
|
}
|