]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/core/rest/rest-table.ts
Refactor search filters
[github/Chocobozzz/PeerTube.git] / client / src / app / core / rest / rest-table.ts
1 import * as debug from 'debug'
2 import { LazyLoadEvent, SortMeta } from 'primeng/api'
3 import { ActivatedRoute, Router } from '@angular/router'
4 import { peertubeLocalStorage } from '@root-helpers/peertube-web-storage'
5 import { RestPagination } from './rest-pagination'
6
7 const logger = debug('peertube:tables:RestTable')
8
9 export abstract class RestTable {
10
11 abstract totalRecords: number
12 abstract sort: SortMeta
13 abstract pagination: RestPagination
14
15 rowsPerPageOptions = [ 10, 20, 50, 100 ]
16 rowsPerPage = this.rowsPerPageOptions[0]
17 expandedRows = {}
18
19 search: string
20
21 protected route: ActivatedRoute
22 protected router: Router
23
24 abstract getIdentifier (): string
25
26 initialize () {
27 this.loadSort()
28 }
29
30 loadSort () {
31 const result = peertubeLocalStorage.getItem(this.getSortLocalStorageKey())
32
33 if (result) {
34 try {
35 this.sort = JSON.parse(result)
36 } catch (err) {
37 console.error('Cannot load sort of local storage key ' + this.getSortLocalStorageKey(), err)
38 }
39 }
40 }
41
42 loadLazy (event: LazyLoadEvent) {
43 logger('Load lazy %o.', event)
44
45 this.sort = {
46 order: event.sortOrder,
47 field: event.sortField
48 }
49
50 this.pagination = {
51 start: event.first,
52 count: this.rowsPerPage
53 }
54
55 this.reloadData()
56 this.saveSort()
57 }
58
59 saveSort () {
60 peertubeLocalStorage.setItem(this.getSortLocalStorageKey(), JSON.stringify(this.sort))
61 }
62
63 onPage (event: { first: number, rows: number }) {
64 logger('On page %o.', event)
65
66 if (this.rowsPerPage !== event.rows) {
67 this.rowsPerPage = event.rows
68 this.pagination = {
69 start: event.first,
70 count: this.rowsPerPage
71 }
72
73 this.reloadData()
74 }
75
76 this.expandedRows = {}
77 }
78
79 onSearch (search: string) {
80 this.search = search
81 this.reloadData()
82 }
83
84 protected abstract reloadData (): void
85
86 private getSortLocalStorageKey () {
87 return 'rest-table-sort-' + this.getIdentifier()
88 }
89 }