1 import { Subject, Subscription } from 'rxjs'
2 import { filter } from 'rxjs/operators'
3 import { Component, EventEmitter, Output, OnDestroy, OnInit, ViewChild } from '@angular/core'
4 import { NavigationEnd, Router } from '@angular/router'
5 import { Notifier, PeerTubeSocket, ScreenService } from '@app/core'
6 import { UserNotificationService } from '@app/shared/shared-main'
7 import { NgbPopover } from '@ng-bootstrap/ng-bootstrap'
10 selector: 'my-notification',
11 templateUrl: './notification.component.html',
12 styleUrls: [ './notification.component.scss' ]
14 export class NotificationComponent implements OnInit, OnDestroy {
15 @ViewChild('popover', { static: true }) popover: NgbPopover
17 @Output() navigate = new EventEmitter<HTMLAnchorElement>()
19 unreadNotifications = 0
23 markAllAsReadSubject = new Subject<boolean>()
25 private notificationSub: Subscription
26 private routeSub: Subscription
29 private userNotificationService: UserNotificationService,
30 private screenService: ScreenService,
31 private peertubeSocket: PeerTubeSocket,
32 private notifier: Notifier,
33 private router: Router
38 this.userNotificationService.countUnreadNotifications()
41 this.unreadNotifications = Math.min(result, 99) // Limit number to 99
42 this.subscribeToNotifications()
45 error: err => this.notifier.error(err.message)
48 this.routeSub = this.router.events
49 .pipe(filter(event => event instanceof NavigationEnd))
50 .subscribe(() => this.closePopover())
54 if (this.notificationSub) this.notificationSub.unsubscribe()
55 if (this.routeSub) this.routeSub.unsubscribe()
58 get isInMobileView () {
59 return this.screenService.isInMobileView()
69 document.querySelector('menu').scrollTo(0, 0) // Reset menu scroll to easy lock
70 document.querySelector('menu').addEventListener('scroll', this.onMenuScrollEvent)
77 document.querySelector('menu').removeEventListener('scroll', this.onMenuScrollEvent)
80 // Lock menu scroll when menu scroll to avoid fleeing / detached dropdown
81 onMenuScrollEvent () {
82 document.querySelector('menu').scrollTo(0, 0)
85 onNotificationLoaded () {
89 onNavigate (link: HTMLAnchorElement) {
91 this.navigate.emit(link)
95 this.markAllAsReadSubject.next(true)
98 private async subscribeToNotifications () {
99 const obs = await this.peertubeSocket.getMyNotificationsSocket()
101 this.notificationSub = obs.subscribe(data => {
102 if (data.type === 'new') return this.unreadNotifications++
103 if (data.type === 'read') return this.unreadNotifications--
104 if (data.type === 'read-all') return this.unreadNotifications = 0