]>
Commit | Line | Data |
---|---|---|
2e46eb97 C |
1 | import * as debug from 'debug' |
2 | import { Subject } from 'rxjs' | |
3 | import { debounceTime, distinctUntilChanged } from 'rxjs/operators' | |
4 | import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core' | |
5 | import { ActivatedRoute, Params, Router } from '@angular/router' | |
1fd61899 C |
6 | |
7 | export type AdvancedInputFilter = { | |
8 | label: string | |
9 | queryParams: Params | |
10 | } | |
11 | ||
2e46eb97 C |
12 | const logger = debug('peertube:AdvancedInputFilterComponent') |
13 | ||
1fd61899 C |
14 | @Component({ |
15 | selector: 'my-advanced-input-filter', | |
16 | templateUrl: './advanced-input-filter.component.html', | |
17 | styleUrls: [ './advanced-input-filter.component.scss' ] | |
18 | }) | |
2e46eb97 | 19 | export class AdvancedInputFilterComponent implements OnInit { |
1fd61899 C |
20 | @Input() filters: AdvancedInputFilter[] = [] |
21 | ||
2e46eb97 C |
22 | @Output() search = new EventEmitter<string>() |
23 | ||
24 | searchValue: string | |
25 | ||
26 | private searchStream: Subject<string> | |
27 | ||
28 | constructor ( | |
29 | private route: ActivatedRoute, | |
30 | private router: Router | |
31 | ) { } | |
32 | ||
33 | ngOnInit () { | |
34 | this.initSearchStream() | |
35 | this.listenToRouteSearchChange() | |
36 | } | |
1fd61899 | 37 | |
2e46eb97 C |
38 | onInputSearch (event: Event) { |
39 | this.updateSearch((event.target as HTMLInputElement).value) | |
1fd61899 C |
40 | } |
41 | ||
42 | onResetTableFilter () { | |
2e46eb97 C |
43 | this.updateSearch('') |
44 | } | |
45 | ||
46 | hasFilters () { | |
47 | return this.filters.length !== 0 | |
48 | } | |
49 | ||
50 | private updateSearch (value: string) { | |
51 | this.searchValue = value | |
52 | this.searchStream.next(this.searchValue) | |
53 | } | |
54 | ||
55 | private listenToRouteSearchChange () { | |
56 | this.route.queryParams | |
57 | .subscribe(params => { | |
58 | const search = params.search || '' | |
59 | ||
60 | logger('On route search change "%s".', search) | |
61 | ||
62 | this.updateSearch(search) | |
63 | }) | |
64 | } | |
65 | ||
66 | private initSearchStream () { | |
67 | this.searchStream = new Subject() | |
68 | ||
69 | this.searchStream | |
70 | .pipe( | |
71 | debounceTime(200), | |
72 | distinctUntilChanged() | |
73 | ) | |
74 | .subscribe(() => { | |
75 | logger('On search "%s".', this.searchValue) | |
76 | ||
77 | this.setQueryParams(this.searchValue) | |
78 | this.search.emit(this.searchValue) | |
79 | }) | |
80 | } | |
81 | ||
82 | private setQueryParams (search: string) { | |
83 | const queryParams: Params = {} | |
84 | ||
85 | if (search) Object.assign(queryParams, { search }) | |
86 | this.router.navigate([ ], { queryParams }) | |
1fd61899 C |
87 | } |
88 | } |