]>
Commit | Line | Data |
---|---|---|
1 | import { Component, Input, OnDestroy, OnInit, ViewChild } from '@angular/core' | |
2 | import { User } from '../shared/users/user.model' | |
3 | import { UserNotificationService } from '@app/shared/users/user-notification.service' | |
4 | import { Subject, Subscription } from 'rxjs' | |
5 | import { Notifier, UserNotificationSocket } from '@app/core' | |
6 | import { NgbPopover } from '@ng-bootstrap/ng-bootstrap' | |
7 | import { NavigationEnd, Router } from '@angular/router' | |
8 | import { filter } from 'rxjs/operators' | |
9 | ||
10 | @Component({ | |
11 | selector: 'my-avatar-notification', | |
12 | templateUrl: './avatar-notification.component.html', | |
13 | styleUrls: [ './avatar-notification.component.scss' ] | |
14 | }) | |
15 | export class AvatarNotificationComponent implements OnInit, OnDestroy { | |
16 | @ViewChild('popover', { static: true }) popover: NgbPopover | |
17 | ||
18 | @Input() user: User | |
19 | ||
20 | unreadNotifications = 0 | |
21 | loaded = false | |
22 | ||
23 | markAllAsReadSubject = new Subject<boolean>() | |
24 | ||
25 | private notificationSub: Subscription | |
26 | private routeSub: Subscription | |
27 | ||
28 | constructor ( | |
29 | private userNotificationService: UserNotificationService, | |
30 | private userNotificationSocket: UserNotificationSocket, | |
31 | private notifier: Notifier, | |
32 | private router: Router | |
33 | ) { | |
34 | } | |
35 | ||
36 | ngOnInit () { | |
37 | this.userNotificationService.countUnreadNotifications() | |
38 | .subscribe( | |
39 | result => { | |
40 | this.unreadNotifications = Math.min(result, 99) // Limit number to 99 | |
41 | this.subscribeToNotifications() | |
42 | }, | |
43 | ||
44 | err => this.notifier.error(err.message) | |
45 | ) | |
46 | ||
47 | this.routeSub = this.router.events | |
48 | .pipe(filter(event => event instanceof NavigationEnd)) | |
49 | .subscribe(() => this.closePopover()) | |
50 | } | |
51 | ||
52 | ngOnDestroy () { | |
53 | if (this.notificationSub) this.notificationSub.unsubscribe() | |
54 | if (this.routeSub) this.routeSub.unsubscribe() | |
55 | } | |
56 | ||
57 | closePopover () { | |
58 | this.popover.close() | |
59 | } | |
60 | ||
61 | onPopoverHidden () { | |
62 | this.loaded = false | |
63 | } | |
64 | ||
65 | onNotificationLoaded () { | |
66 | this.loaded = true | |
67 | } | |
68 | ||
69 | markAllAsRead () { | |
70 | this.markAllAsReadSubject.next(true) | |
71 | } | |
72 | ||
73 | private async subscribeToNotifications () { | |
74 | const obs = await this.userNotificationSocket.getMyNotificationsSocket() | |
75 | ||
76 | this.notificationSub = obs.subscribe(data => { | |
77 | if (data.type === 'new') return this.unreadNotifications++ | |
78 | if (data.type === 'read') return this.unreadNotifications-- | |
79 | if (data.type === 'read-all') return this.unreadNotifications = 0 | |
80 | }) | |
81 | } | |
82 | ||
83 | } |