]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/app/shared/rest/rest-table.ts
Factorize rest-table and fix/simplify SQL
[github/Chocobozzz/PeerTube.git] / client / src / app / shared / rest / rest-table.ts
CommitLineData
88a7f93f 1import { peertubeLocalStorage } from '@app/shared/misc/peertube-web-storage'
f77eb73b 2import { LazyLoadEvent, SortMeta } from 'primeng/api'
d592e0a9 3import { RestPagination } from './rest-pagination'
24b9417c
C
4import { Subject } from 'rxjs'
5import { debounceTime, distinctUntilChanged } from 'rxjs/operators'
d592e0a9
C
6
7export abstract class RestTable {
ab998f7b 8
d592e0a9 9 abstract totalRecords: number
d592e0a9
C
10 abstract sort: SortMeta
11 abstract pagination: RestPagination
12
042daa70 13 search: string
0251197e
RK
14 rowsPerPageOptions = [ 10, 20, 50, 100 ]
15 rowsPerPage = this.rowsPerPageOptions[0]
16
24b9417c 17 private searchStream: Subject<string>
8e11a1b3
C
18
19 abstract getIdentifier (): string
ab998f7b 20
24b9417c
C
21 initialize () {
22 this.loadSort()
23 this.initSearch()
24 }
25
ab998f7b 26 loadSort () {
8e11a1b3 27 const result = peertubeLocalStorage.getItem(this.getSortLocalStorageKey())
ab998f7b
C
28
29 if (result) {
30 try {
31 this.sort = JSON.parse(result)
32 } catch (err) {
8e11a1b3 33 console.error('Cannot load sort of local storage key ' + this.getSortLocalStorageKey(), err)
ab998f7b
C
34 }
35 }
36 }
37
d592e0a9
C
38 loadLazy (event: LazyLoadEvent) {
39 this.sort = {
40 order: event.sortOrder,
41 field: event.sortField
42 }
43
44 this.pagination = {
45 start: event.first,
46 count: this.rowsPerPage
47 }
48
49 this.loadData()
ab998f7b
C
50 this.saveSort()
51 }
52
53 saveSort () {
8e11a1b3 54 peertubeLocalStorage.setItem(this.getSortLocalStorageKey(), JSON.stringify(this.sort))
d592e0a9
C
55 }
56
24b9417c
C
57 initSearch () {
58 this.searchStream = new Subject()
59
60 this.searchStream
61 .pipe(
62 debounceTime(400),
63 distinctUntilChanged()
64 )
65 .subscribe(search => {
66 this.search = search
67 this.loadData()
68 })
69 }
70
be27ef3b
C
71 onSearch (event: Event) {
72 const target = event.target as HTMLInputElement
73 this.searchStream.next(target.value)
24b9417c 74 }
dffd5d12
B
75
76 protected abstract loadData (): void
8e11a1b3
C
77
78 private getSortLocalStorageKey () {
79 return 'rest-table-sort-' + this.getIdentifier()
80 }
d592e0a9 81}