1 import * as debug from 'debug'
2 import { LazyLoadEvent, SortMeta } from 'primeng/api'
3 import { Subject } from 'rxjs'
4 import { debounceTime, distinctUntilChanged } from 'rxjs/operators'
5 import { ActivatedRoute, Params, Router } from '@angular/router'
6 import { peertubeLocalStorage } from '@root-helpers/peertube-web-storage'
7 import { RestPagination } from './rest-pagination'
9 const logger = debug('peertube:tables:RestTable')
11 export abstract class RestTable {
13 abstract totalRecords: number
14 abstract sort: SortMeta
15 abstract pagination: RestPagination
18 rowsPerPageOptions = [ 10, 20, 50, 100 ]
19 rowsPerPage = this.rowsPerPageOptions[0]
24 protected searchStream: Subject<string>
26 protected route: ActivatedRoute
27 protected router: Router
29 abstract getIdentifier (): string
37 const result = peertubeLocalStorage.getItem(this.getSortLocalStorageKey())
41 this.sort = JSON.parse(result)
43 console.error('Cannot load sort of local storage key ' + this.getSortLocalStorageKey(), err)
48 loadLazy (event: LazyLoadEvent) {
49 logger('Load lazy %o.', event)
52 order: event.sortOrder,
53 field: event.sortField
58 count: this.rowsPerPage
66 peertubeLocalStorage.setItem(this.getSortLocalStorageKey(), JSON.stringify(this.sort))
70 this.searchStream = new Subject()
75 distinctUntilChanged()
77 .subscribe(search => {
80 logger('On search %s.', this.search)
86 onSearch (event: Event) {
87 const target = event.target as HTMLInputElement
88 this.searchStream.next(target.value)
90 this.setQueryParams((event.target as HTMLInputElement).value)
93 setQueryParams (search: string) {
94 if (!this.baseRoute) return
96 const queryParams: Params = {}
98 if (search) Object.assign(queryParams, { search })
99 this.router.navigate([ this.baseRoute ], { queryParams })
102 resetTableFilter () {
103 this.setTableFilter('')
104 this.setQueryParams('')
108 listenToSearchChange () {
109 this.route.queryParams
110 .subscribe(params => {
111 this.search = params.search || ''
113 // Primeng table will run an event to load data
114 this.setTableFilter(this.search)
118 onPage (event: { first: number, rows: number }) {
119 logger('On page %o.', event)
121 if (this.rowsPerPage !== event.rows) {
122 this.rowsPerPage = event.rows
125 count: this.rowsPerPage
131 this.expandedRows = {}
134 setTableFilter (filter: string, triggerEvent = true) {
135 // FIXME: cannot use ViewChild, so create a component for the filter input
136 const filterInput = document.getElementById('table-filter') as HTMLInputElement
137 if (!filterInput) return
139 filterInput.value = filter
141 if (triggerEvent) filterInput.dispatchEvent(new Event('keyup'))
145 this.searchStream.next('')
146 this.setTableFilter('')
149 protected abstract loadData (): void
151 private getSortLocalStorageKey () {
152 return 'rest-table-sort-' + this.getIdentifier()