All files / toast-notification si-toast-notification.service.ts

81.81% Statements 54/66
71.42% Branches 10/14
66.66% Functions 12/18
82.81% Lines 53/64

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187                                1x           7x   7x 7x 7x         7x 7x 7x 7x           7x 7x 9x 9x 1x   9x 9x 8x       8x   5x         7x 7x         7x 7x                               9x                 9x               9x 9x 9x 9x 9x               8x 8x 8x 16x 7x   9x       8x 8x   8x 7x 7x 7x 7x                                                     7x     7x         7x 7x 7x     7x               7x 7x 7x         7x      
/**
 * Copyright (c) Siemens 2016 - 2025
 * SPDX-License-Identifier: MIT
 */
import { Overlay, OverlayRef } from '@angular/cdk/overlay';
import { ComponentPortal } from '@angular/cdk/portal';
import { isPlatformBrowser } from '@angular/common';
import { ComponentRef, inject, Injectable, Injector, OnDestroy, PLATFORM_ID } from '@angular/core';
import { Link } from '@siemens/element-ng/link';
import { SiNoTranslateService, SiTranslateService } from '@siemens/element-translate-ng/translate';
import { ReplaySubject, Subject } from 'rxjs';
 
import { SiToastNotificationDrawerComponent } from './si-toast-notification-drawer/si-toast-notification-drawer.component';
import { SI_TOAST_AUTO_HIDE_DELAY, SiToast, ToastStateName } from './si-toast.model';
 
@Injectable({ providedIn: 'root' })
export class SiToastNotificationService implements OnDestroy {
  /**
   * List of currently active toasts to see details or close them.
   *
   * @defaultValue []
   */
  activeToasts: SiToast[] = [];
 
  private activeToastsSubject = new ReplaySubject<SiToast[]>(1);
  private queuedToastSubject = new Subject<SiToast>();
  private readonly maxToasts = 3;
 
  private componentRef?: ComponentRef<SiToastNotificationDrawerComponent>;
  private overlayRef?: OverlayRef;
 
  private injector = inject(Injector);
  private overlay = inject(Overlay);
  private toastTimeoutMap = new Map<SiToast, any>();
  private toastTimerDefaults = new Map<
    SiToast,
    { pendingTimeout: number; initializeTime: number }
  >();
 
  constructor() {
    const isBrowser = isPlatformBrowser(inject(PLATFORM_ID));
    this.queuedToastSubject.subscribe((toast: SiToast) => {
      this.activeToasts.push(toast);
      if (this.activeToasts.length > this.maxToasts) {
        this.hideToastNotification(this.activeToasts[0]);
      }
      this.activeToastsSubject.next(this.activeToasts);
      if (!toast.disableAutoClose && toast.timeout) {
        this.toastTimerDefaults.set(toast, {
          pendingTimeout: toast.timeout,
          initializeTime: Date.now()
        });
        this.toastTimeoutMap.set(
          toast,
          setTimeout(() => this.hideToastNotification(toast), toast.timeout)
        );
      }
    });
 
    if (isBrowser) {
      this.addToastDrawer();
    }
  }
 
  ngOnDestroy(): void {
    this.overlayRef?.dispose();
    this.componentRef?.destroy();
  }
 
  /**
   * Queue a new toast to be shown.
   * @param action - Passing a Link object will optionally add a clickable link to the toast which can contain an action.
   * @returns the toast object
   */
  queueToastNotification(
    state: ToastStateName,
    title: string,
    message: string,
    disableAutoClose?: boolean,
    disableManualClose?: boolean,
    action?: Link
  ): SiToast {
    const toast: SiToast = {
      state,
      title,
      message,
      disableAutoClose,
      disableManualClose,
      action,
      hidden: new Subject()
    };
    return this.showToastNotification(toast);
  }
 
  /**
   * Show a toast notification
   * @param toast - The toast object of the toast to be shown, can also be constructed while calling this.
   */
  showToastNotification(toast: SiToast): SiToast {
    toast.timeout ??= SI_TOAST_AUTO_HIDE_DELAY;
    toast.hidden ??= new Subject();
    toast.close = () => this.hideToastNotification(toast);
    this.queuedToastSubject.next(toast);
    return toast;
  }
 
  /**
   * Hide a toast notification
   * @param toast - The toast object of the toast to be hidden, can be retrieved from {@link activeToasts} and is returned by {@link queueToastNotification}.
   */
  hideToastNotification(toast?: SiToast): void {
    const hiddenToasts: SiToast[] = [];
    const activeToasts: SiToast[] = [];
    this.activeToasts.forEach(item => {
      if (!toast || item === toast) {
        hiddenToasts.push(item);
      } else {
        activeToasts.push(item);
      }
    });
 
    this.activeToasts = activeToasts;
    this.activeToastsSubject.next(this.activeToasts);
 
    hiddenToasts.forEach(item => {
      item.hidden?.next();
      item.hidden?.complete();
      this.toastTimerDefaults.delete(item);
      this.toastTimeoutMap.delete(item);
    });
  }
 
  private pauseToastNotification(toast: SiToast): void {
    Iif (!toast.disableAutoClose) {
      clearTimeout(this.toastTimeoutMap.get(toast));
 
      const initialTimeout = this.toastTimerDefaults.get(toast)?.initializeTime;
      const elapsedTime = initialTimeout ? Date.now() - initialTimeout : 0;
      this.toastTimerDefaults.get(toast)!.pendingTimeout -= elapsedTime;
    }
  }
 
  private resumeToastNotification(toast: SiToast): void {
    Iif (!toast.disableAutoClose) {
      this.toastTimerDefaults.get(toast)!.initializeTime = Date.now();
      this.toastTimeoutMap.set(
        toast,
        setTimeout(() => {
          this.hideToastNotification(this.activeToasts.find(t => t === toast));
        }, this.toastTimerDefaults.get(toast)!.pendingTimeout)
      );
    }
  }
 
  private addToastDrawer(): void {
    this.overlayRef = this.overlay.create({
      positionStrategy: this.overlay.position().global().end('20px').bottom()
    });
    const portal = new ComponentPortal(
      SiToastNotificationDrawerComponent,
      null,
      this.buildInjector()
    );
    this.componentRef = this.overlayRef.attach(portal);
    this.componentRef.setInput('toasts', this.activeToastsSubject);
    this.componentRef.instance.paused.subscribe(toast => {
      this.pauseToastNotification(toast);
    });
    this.componentRef.instance.resumed.subscribe(toast => {
      this.resumeToastNotification(toast);
    });
  }
 
  // TODO remove once translation must be defined at application start
  // Notification service is provided in 'root'. If no translation is defined, SiNoTranslateService is not provided
  private buildInjector(): Injector {
    let injector = this.injector;
    if (!injector.get(SiTranslateService, null)) {
      injector = Injector.create({
        providers: [{ provide: SiTranslateService, useClass: SiNoTranslateService, deps: [] }],
        parent: this.injector
      });
    }
    return injector;
  }
}