2978e846717874919ac414c44637792976df71d4
[src/xds/xds-agent.git] / webapp / src / app / services / alert.service.ts
1 import { Injectable, SecurityContext } from '@angular/core';
2 import { DomSanitizer } from '@angular/platform-browser';
3 import { Observable } from 'rxjs/Observable';
4 import { Subject } from 'rxjs/Subject';
5
6
7 export type AlertType = "danger" | "warning" | "info" | "success";
8
9 export interface IAlert {
10     type: AlertType;
11     msg: string;
12     show?: boolean;
13     dismissible?: boolean;
14     dismissTimeout?: number;     // close alert after this time (in seconds)
15     id?: number;
16 }
17
18 @Injectable()
19 export class AlertService {
20     public alerts: Observable<IAlert[]>;
21
22     private _alerts: IAlert[];
23     private alertsSubject = <Subject<IAlert[]>>new Subject();
24     private uid = 0;
25     private defaultDissmissTmo = 5; // in seconds
26
27     constructor(private sanitizer: DomSanitizer) {
28         this.alerts = this.alertsSubject.asObservable();
29         this._alerts = [];
30         this.uid = 0;
31     }
32
33     public error(msg: string, dismissTime?: number) {
34         this.add({
35             type: "danger", msg: msg, dismissible: true, dismissTimeout: dismissTime
36         });
37     }
38
39     public warning(msg: string, dismissible?: boolean) {
40         this.add({ type: "warning", msg: msg, dismissible: true, dismissTimeout: (dismissible ? this.defaultDissmissTmo : 0) });
41     }
42
43     public info(msg: string) {
44         this.add({ type: "info", msg: msg, dismissible: true, dismissTimeout: this.defaultDissmissTmo });
45     }
46
47     public add(al: IAlert) {
48         let msg = String(al.msg).replace("\n", "<br>");
49         this._alerts.push({
50             show: true,
51             type: al.type,
52             msg: this.sanitizer.sanitize(SecurityContext.HTML, msg),
53             dismissible: al.dismissible || true,
54             dismissTimeout: (al.dismissTimeout * 1000) || 0,
55             id: this.uid,
56         });
57         this.uid += 1;
58         this.alertsSubject.next(this._alerts);
59     }
60
61     public del(al: IAlert) {
62         let idx = this._alerts.findIndex((a) => a.id === al.id);
63         if (idx > -1) {
64             this._alerts.splice(idx, 1);
65         }
66     }
67 }