ladylilia.com/apps/twitch-logs/src/app/comments/comments.component.ts

113 lines
3.0 KiB

import {
AfterViewInit,
Component,
ElementRef,
OnDestroy,
OnInit,
ViewChild
} from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import {
MatPaginator,
MatSort,
MatTableDataSource
} from '@angular/material';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import {
debounceTime,
delay,
distinctUntilChanged,
startWith,
tap
} from 'rxjs/operators';
import { merge } from 'rxjs/observable/merge';
import { fromEvent } from 'rxjs/observable/fromEvent';
import { CommentsService } from '../services/comments.service';
import { ImagesService } from '../services/images.service';
import { CommentsDataSource } from '../services/comments.datasource';
@Component({
selector: 'comments',
templateUrl: './comments.component.html',
styleUrls: [ './comments.component.css' ]
})
export class CommentsComponent implements OnInit, OnDestroy, AfterViewInit {
private badgesSubject = new BehaviorSubject<any[]>([]);
private emotesSubject = new BehaviorSubject<any[]>([]);
dataSource: CommentsDataSource;
videoID: string;
displayedColumns = [
'offset',
'commenter_display_name',
'message_body'
];
@ViewChild(MatPaginator) paginator: MatPaginator;
@ViewChild(MatSort) sort: MatSort;
@ViewChild('input') input: ElementRef;
public badges$ = this.badgesSubject.asObservable();
public emotes$ = this.emotesSubject.asObservable();
constructor(private route: ActivatedRoute,
private commentsService: CommentsService,
private imagesService: ImagesService) { }
ngOnInit() {
this.dataSource = new CommentsDataSource(this.commentsService);
this.videoID = this.route.snapshot.paramMap.get('id');
this.dataSource.loadComments(this.videoID, '', 'offset', 'asc', 0, 20);
this.imagesService.getBadges().subscribe(
(data: any[]) => this.badgesSubject.next(data)
);
this.imagesService.getEmotes().subscribe(
(data: any[]) => this.emotesSubject.next(data)
);
}
ngOnDestroy() {
this.badgesSubject.complete();
this.emotesSubject.complete();
}
ngAfterViewInit() {
this.sort.sortChange.subscribe(() => this.paginator.pageIndex = 0);
fromEvent(this.input.nativeElement, 'keyup')
.pipe(
debounceTime(150),
distinctUntilChanged(),
tap(() => {
this.paginator.pageIndex = 0;
this.loadCommentsPage();
})
)
.subscribe();
merge(this.sort.sortChange, this.paginator.page)
.pipe(
tap(() => this.loadCommentsPage())
)
.subscribe();
}
loadCommentsPage() {
this.dataSource.loadComments(
this.videoID,
this.input.nativeElement.value,
this.sort.active,
this.sort.direction,
this.paginator.pageIndex,
this.paginator.pageSize);
}
}