This repository has been archived on 2025-04-11. You can view files and clone it, but cannot push or open issues or pull requests.
bee-frontend-ARCHIVED/src/app/core/components/notification-bar/notification-bar.component.ts
2024-08-31 22:18:08 +00:00

70 lines
1.6 KiB
TypeScript

import { Component } from "@angular/core";
import { NotificationService } from "../../services/notification.service";
export interface NotificationElement {
message: string;
type: "info" | "danger" | "warn" | "success";
timeout: number | undefined;
}
interface NotificationItem {
element: NotificationElement;
shownAt: Date;
}
@Component({
selector: "app-notification-bar",
templateUrl: "./notification-bar.component.html",
styleUrls: ["./notification-bar.component.scss"],
})
export class NotificationBarComponent {
items: NotificationItem[] = [];
isRunning: boolean;
constructor(private notificationService: NotificationService) {
this.isRunning = false;
this.notificationService.notification$.subscribe((notification) => {
if (notification !== undefined) {
this.items.push({
element: notification,
shownAt: new Date(),
});
this.startTimeoutIfNecessary();
}
});
}
startTimeoutIfNecessary(): void {
if (this.isRunning === true) {
return;
}
let intervalId = setInterval(() => {
this.isRunning = true;
let now = new Date();
this.items.forEach((item) => {
if (item.element.timeout !== undefined) {
let timeout = new Date(
item.shownAt.getTime() + item.element.timeout * 1000
);
if (timeout < now) {
this.dismiss(item);
}
}
});
if (this.items.length === 0) {
clearInterval(intervalId);
this.isRunning = false;
}
}, 1000);
}
dismiss(item: NotificationItem): void {
this.items = this.items.filter((i) => i !== item);
}
}