From 67ed6552b831df66713bac9e672738796128d33f Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Tue, 23 Jun 2020 14:10:17 +0200 Subject: Reorganize client shared modules --- client/src/app/core/rest/rest-table.ts | 105 +++++++++++++++++++++++++++++++++ 1 file changed, 105 insertions(+) create mode 100644 client/src/app/core/rest/rest-table.ts (limited to 'client/src/app/core/rest/rest-table.ts') diff --git a/client/src/app/core/rest/rest-table.ts b/client/src/app/core/rest/rest-table.ts new file mode 100644 index 000000000..1b35ad47d --- /dev/null +++ b/client/src/app/core/rest/rest-table.ts @@ -0,0 +1,105 @@ +import { peertubeLocalStorage } from '@app/helpers/peertube-web-storage' +import { LazyLoadEvent, SortMeta } from 'primeng/api' +import { RestPagination } from './rest-pagination' +import { Subject } from 'rxjs' +import { debounceTime, distinctUntilChanged } from 'rxjs/operators' + +export abstract class RestTable { + + abstract totalRecords: number + abstract sort: SortMeta + abstract pagination: RestPagination + + search: string + rowsPerPageOptions = [ 10, 20, 50, 100 ] + rowsPerPage = this.rowsPerPageOptions[0] + expandedRows = {} + + private searchStream: Subject + + abstract getIdentifier (): string + + initialize () { + this.loadSort() + this.initSearch() + } + + loadSort () { + const result = peertubeLocalStorage.getItem(this.getSortLocalStorageKey()) + + if (result) { + try { + this.sort = JSON.parse(result) + } catch (err) { + console.error('Cannot load sort of local storage key ' + this.getSortLocalStorageKey(), err) + } + } + } + + loadLazy (event: LazyLoadEvent) { + this.sort = { + order: event.sortOrder, + field: event.sortField + } + + this.pagination = { + start: event.first, + count: this.rowsPerPage + } + + this.loadData() + this.saveSort() + } + + saveSort () { + peertubeLocalStorage.setItem(this.getSortLocalStorageKey(), JSON.stringify(this.sort)) + } + + initSearch () { + this.searchStream = new Subject() + + this.searchStream + .pipe( + debounceTime(400), + distinctUntilChanged() + ) + .subscribe(search => { + this.search = search + this.loadData() + }) + } + + onSearch (event: Event) { + const target = event.target as HTMLInputElement + this.searchStream.next(target.value) + } + + onPage (event: { first: number, rows: number }) { + if (this.rowsPerPage !== event.rows) { + this.rowsPerPage = event.rows + this.pagination = { + start: event.first, + count: this.rowsPerPage + } + this.loadData() + } + this.expandedRows = {} + } + + setTableFilter (filter: string) { + // FIXME: cannot use ViewChild, so create a component for the filter input + const filterInput = document.getElementById('table-filter') as HTMLInputElement + if (filterInput) filterInput.value = filter + } + + resetSearch () { + this.searchStream.next('') + this.setTableFilter('') + } + + protected abstract loadData (): void + + private getSortLocalStorageKey () { + return 'rest-table-sort-' + this.getIdentifier() + } +} -- cgit v1.2.3