aboutsummaryrefslogtreecommitdiffhomepage
path: root/client/src/app/core/routing/route-filter.ts
blob: f783a0c40baf75f277cafdfa4a32387b70faaae1 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import * as debug from 'debug'
import { Subject } from 'rxjs'
import { debounceTime, distinctUntilChanged } from 'rxjs/operators'
import { ActivatedRoute, Params, Router } from '@angular/router'

const logger = debug('peertube:tables:RouteFilter')

export abstract class RouteFilter {
  search: string

  protected searchStream: Subject<string>

  protected route: ActivatedRoute
  protected router: Router

  initSearch () {
    this.searchStream = new Subject()

    this.searchStream
      .pipe(
        debounceTime(400),
        distinctUntilChanged()
      )
      .subscribe(search => {
        this.search = search

        logger('On search %s.', this.search)

        this.loadData()
      })
  }

  onSearch (event: Event) {
    const target = event.target as HTMLInputElement
    this.searchStream.next(target.value)

    this.setQueryParams(target.value)
  }

  resetTableFilter () {
    this.setTableFilter('')
    this.setQueryParams('')
    this.resetSearch()
  }

  resetSearch () {
    this.searchStream.next('')
    this.setTableFilter('')
  }

  listenToSearchChange () {
    this.route.queryParams
      .subscribe(params => {
        this.search = params.search || ''

        // Primeng table will run an event to load data
        this.setTableFilter(this.search)
      })
  }

  setTableFilter (filter: string, triggerEvent = true) {
    // FIXME: cannot use ViewChild, so create a component for the filter input
    const filterInput = document.getElementById('table-filter') as HTMLInputElement
    if (!filterInput) return

    filterInput.value = filter

    if (triggerEvent) filterInput.dispatchEvent(new Event('keyup'))
  }

  protected abstract loadData (): void

  private setQueryParams (search: string) {
    const queryParams: Params = {}

    if (search) Object.assign(queryParams, { search })
    this.router.navigate([ ], { queryParams })
  }
}