aboutsummaryrefslogtreecommitdiffhomepage
path: root/client/src/app/shared/shared-forms/advanced-input-filter.component.ts
blob: 1b0eed34b3e8cb52eb89d1fa5d712801d093f363 (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
80
81
82
83
84
85
86
87
88
import * as debug from 'debug'
import { Subject } from 'rxjs'
import { debounceTime, distinctUntilChanged } from 'rxjs/operators'
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core'
import { ActivatedRoute, Params, Router } from '@angular/router'

export type AdvancedInputFilter = {
  label: string
  queryParams: Params
}

const logger = debug('peertube:AdvancedInputFilterComponent')

@Component({
  selector: 'my-advanced-input-filter',
  templateUrl: './advanced-input-filter.component.html',
  styleUrls: [ './advanced-input-filter.component.scss' ]
})
export class AdvancedInputFilterComponent implements OnInit {
  @Input() filters: AdvancedInputFilter[] = []

  @Output() search = new EventEmitter<string>()

  searchValue: string

  private searchStream: Subject<string>

  constructor (
    private route: ActivatedRoute,
    private router: Router
  ) { }

  ngOnInit () {
    this.initSearchStream()
    this.listenToRouteSearchChange()
  }

  onInputSearch (event: Event) {
    this.updateSearch((event.target as HTMLInputElement).value)
  }

  onResetTableFilter () {
    this.updateSearch('')
  }

  hasFilters () {
    return this.filters.length !== 0
  }

  private updateSearch (value: string) {
    this.searchValue = value
    this.searchStream.next(this.searchValue)
  }

  private listenToRouteSearchChange () {
    this.route.queryParams
      .subscribe(params => {
        const search = params.search || ''

        logger('On route search change "%s".', search)

        this.updateSearch(search)
      })
  }

  private initSearchStream () {
    this.searchStream = new Subject()

    this.searchStream
      .pipe(
        debounceTime(200),
        distinctUntilChanged()
      )
      .subscribe(() => {
        logger('On search "%s".', this.searchValue)

        this.setQueryParams(this.searchValue)
        this.search.emit(this.searchValue)
      })
  }

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

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