All files / lib/dialog dialog-service.ts

98.03% Statements 550/561
86.53% Branches 45/52
95.65% Functions 22/23
98.03% Lines 550/561

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 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 5621x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 45x 45x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 9x 1x 1x 1x 1x 1x 1x 1x 1x 9x 9x 9x 9x 9x 9x 9x 9x 5x 5x 5x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 1x 1x 9x 9x 9x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 5x 5x 7x 7x 7x 7x 7x 7x 1x 1x           1x 1x 5x 5x 5x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x     1x 1x 1x 1x 1x 1x 297x 297x 297x 297x 297x 297x 297x 1x 1x 1x 1x 1x 1x 1x 1x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 4x 4x 4x 4x 4x 4x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 4x 4x 11x 11x 11x 11x 11x 11x   11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 1x 1x 1x 11x 11x 11x 11x 11x 11x 11x 11x 11x 1x 1x 1x 11x 11x 11x 11x 11x 11x 11x   11x 11x 11x 11x 11x 11x 11x     11x 11x 1x 1x 1x 11x 11x 11x 11x 11x 11x 11x 11x 11x 1x 1x 1x 11x 11x 11x 11x 11x 11x 11x 11x 1x 1x 1x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 1x 1x 1x 1x 1x 1x 1x 1x 1x 11x 11x 11x 11x 11x 11x 11x 11x 3x 11x 11x 1x 11x 11x 11x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 297x 297x 297x 1x 1x 1x 1x 1x 1x 1x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 54x 57x 57x 45x 57x 57x 57x 57x 1x 1x 1x 1x 1x 1x 1x 1x 9x 9x 9x 9x 9x 1x 1x 1x 1x 1x 1x 1x 1x 7x 7x 7x 7x 7x 1x 1x 1x 1x 1x 1x 11x 11x 11x 11x 11x 11x 11x 1x  
import {
  ApplicationRef,
  ComponentRef,
  ElementRef,
  EmbeddedViewRef,
  EventEmitter,
  Injectable,
  SecurityContext,
  StaticProvider,
  Type,
  createComponent,
  inject,
} from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
 
import { ActionEvent } from '../utils/event.types';
import { Callback, Item } from '../utils/util.types';
import { SoundType, playSound } from '../utils/utilities';
 
import { DialogOverlayRef } from '../internal/modal-overlay/dialog-modal-overlay-container/dialog-modal-overlay-container';
import {
  ModalConfig,
  ModalOverlayContainerService,
} from '../internal/modal-overlay/modal-overlay-container.service';
import { SidebarOverlayRef } from '../internal/modal-overlay/sidebar-overlay-container/sidebar-overlay-container.component';
import { NotificationMessageWrapperComponent } from '../internal/notification-message-wrapper/notification-message-wrapper.component';
import { SidebarComponent } from '../internal/sidebar/sidebar.component';
 
import {
  AlertContent,
  AlertDialogComponent,
} from '../alert-dialog/alert-dialog.component';
import { MessageTileComponent } from '../message-tile/message-tile.component';
 
/**
 * configuration for a dialog
 */
export interface DialogConfig<T> {
  /**
   * the title used by the dialog (required for a11y)
   */
  readonly title: string;
 
  /**
   * optional data passed on to the dialog
   */
  readonly data?: T;
}
 
/**
 * Data passed on to the dialog
 */
export class DialogData<T> {
  constructor(readonly data: T) {}
}
 
/**
 * configuration for a sidebar
 */
export interface SidebarConfig {
  readonly title: string;
  readonly width: number;
  readonly topOffset: number;
  readonly position: 'left' | 'right';
  readonly animateOnOpen?: boolean;
}
 
/**
 * Configuration for a notification message
 */
export interface NotificationMessageConfig {
  readonly title: string;
  readonly text: string;
  readonly type: 'info' | 'warning';
  readonly buttonLabel?: string;
}
 
/**
 * Global configuration for a notification message service.
 */
interface NotificationMessagesServiceConfig {
  /**
   * Width of the Notification Message container element.
   */
  width: number;
 
  /**
   * Gap between Notification Messages.
   */
  gap?: number;
 
  /**
   * Top margin for the Notification Message container element.
   */
  topMargin?: number;
 
  /**
   * Defines how long a Notification Message will stay on screen before disappearing (in miliseconds).
   */
  duration?: number;
}
 
/**
 * type of alert
 */
export type AlertType = 'default' | 'error';
 
/**
 * Reference to the alert dialog
 */
export class AlertRef {
  /**
   * event emited when one of the actions is executed
   */
  public readonly onAction: EventEmitter<Item> = new EventEmitter<Item>();
 
  constructor(private modalOverlayRef: DialogOverlayRef) {}
 
  close(): void {
    this.modalOverlayRef.close();
  }
}
 
/**
 * Reference to a (generic) dialog
 * @param T type of the component shown in the dialog
 * @param I type of input data which is passed to the dialog
 * @param R type of data returned by the dialog upon closure
 */
export class DialogRef<T, I = unknown, R = undefined> {
  /**
   * The instance of the component shown in the dialog
   */
  public readonly dialogInstance: T;
  /**
   * Promise resolved when the dialog is closed
   */
  public readonly result: Promise<R | undefined> = new Promise(resolve => {
    this.resolver = resolve;
  });
  private resolver!: (
    value: R | PromiseLike<R | undefined> | undefined,
  ) => void;
 
  private readonly modalOverlayRef: DialogOverlayRef;
 
  constructor(
    modalService: ModalOverlayContainerService,
    dialogComponent: Type<T>,
    config: DialogConfig<I>,
  ) {
    const providers: StaticProvider[] = [
      { provide: DialogRef, useValue: this },
    ];
    if (config.data !== undefined) {
      providers.push({
        provide: DialogData,
        useValue: new DialogData(config.data),
      });
    }
    const modalReference = modalService.openDialog(
      dialogComponent,
      new ModalConfig({ label: config.title }),
      providers,
    );
    this.modalOverlayRef = modalReference.overlayRef;
    this.dialogInstance = modalReference.instance;
    const viewRef = modalReference.componentRef
      .hostView as EmbeddedViewRef<never>; // NOSONAR - false positive typescript:S4325
    const rootElement = viewRef.rootNodes[0] as HTMLElement;
    rootElement.classList.add('gc-form-dialog-host');
  }
 
  close(result?: R) {
    this.resolver(result);
    this.modalOverlayRef.close();
  }
}
 
/**
 * Configuration options for an alert dialog
 */
export interface AlertConfig {
  /** the type of alert */
  readonly type: AlertType;
  /** the title displayed in the alert dialog */
  readonly title: string;
  /** the message displayed in the alert dialog. Items in an array are rendered in separate div elements */
  readonly message: string | AlertContent[];
  /** the primary action item */
  readonly primaryAction: Item;
  /** an optional secondary action item */
  readonly secondaryAction?: Item;
}
 
/**
 * Reference to a sidebar dialog.
 */
export class SidebarRef<T> {
  /**
   * Event emited when the Sidebar has been closed
   */
  public readonly onClosed: EventEmitter<SidebarRef<T>> = new EventEmitter<
    SidebarRef<T>
  >();
 
  private readonly sidebarComponentInstance: SidebarComponent;
  private readonly modalOverlayRef: SidebarOverlayRef;
 
  constructor(
    private readonly modalService: ModalOverlayContainerService,
    public readonly sidebarContentComponent: Type<T>,
    private readonly config: SidebarConfig,
  ) {
    const modalConfig = new ModalConfig({
      offsetTop: config.topOffset,
      variant: 'sidebar',
    });
 
    const providers: StaticProvider[] = [
      { provide: SidebarRef, useValue: this },
    ];
 
    const modalReference = this.modalService.openSidebar(
      SidebarComponent,
      modalConfig,
      providers,
    );
    this.modalOverlayRef = modalReference.overlayRef;
 
    this.sidebarComponentInstance = modalReference.instance;
    this.sidebarComponentInstance.label = this.config.title;
    this.sidebarComponentInstance.width = this.config.width;
    this.sidebarComponentInstance.position = this.config.position;
    this.sidebarComponentInstance.topOffset = this.config.topOffset;
    this.sidebarComponentInstance.content = this.sidebarContentComponent;
 
    if (this.config.animateOnOpen !== undefined) {
      this.sidebarComponentInstance.animateOnOpen = this.config.animateOnOpen;
    }
 
    this.sidebarComponentInstance.onClosed.subscribe(() => {
      this.destroySidebarOverlay();
      this.onClosed.emit(this);
    });
 
    setTimeout(() => {
      this.sidebarComponentInstance.isOpen = true;
    });
  }
 
  public close(animated = true): void {
    if (this.sidebarComponentInstance.isOpen) {
      this.sidebarComponentInstance.animateOnClose = animated;
      this.sidebarComponentInstance.isOpen = false;
    }
  }
 
  private destroySidebarOverlay(): void {
    this.modalOverlayRef.close();
    this.sidebarComponentInstance.onClosed.unsubscribe();
  }
}
 
// 30s
const SCREEN_READER_MESSAGE_DURATION = 30 * 1000;
 
/**
 * The notification messages service allows addition of fly-in notifications
 * in the form of `MessageTileComponent` components
 */
@Injectable({ providedIn: 'root' })
export class NotificationMessagesService {
  private notificationMessages: ComponentRef<MessageTileComponent>[] = [];
  private appRef = inject(ApplicationRef);
  private domSanitzer = inject(DomSanitizer);
  private ulElement = document.createElement('ul');
  private ariaLiveContainerElement = document.createElement('div');
  private wrapperComponent = createComponent(
    NotificationMessageWrapperComponent,
    {
      environmentInjector: this.appRef.injector,
      projectableNodes: [
        this.notificationMessages.map(
          nm =>
            nm.injector.get<ElementRef<HTMLElement>>(ElementRef<HTMLElement>)
              .nativeElement,
        ),
      ],
    },
  );
 
  constructor() {
    this.ulElement.classList.add('gc-notification-message-container');
    this.ariaLiveContainerElement.setAttribute('aria-live', 'polite');
    this.ariaLiveContainerElement.setAttribute('role', 'log');
    this.ariaLiveContainerElement.setAttribute('aria-label', 'Meldungen');
    this.ariaLiveContainerElement.classList.add('gc-scr-only');
    document.body.appendChild(this.ariaLiveContainerElement);
  }
 
  /**
   * Adds a new notification message to the screen based on provided configurations.
   * @param notificationMessage configuration for the individual message that is going to be added
   * @param config global configuration for the service
   * @returns reference to the added notification message
   */
  addNotificationMessage(
    notificationMessage: NotificationMessageConfig,
    config: NotificationMessagesServiceConfig,
  ): NotificationMessageRef {
    const nmComponent = createComponent(MessageTileComponent, {
      environmentInjector: this.appRef.injector,
    });
    const wrapperComponentElement = this.wrapperComponent.injector.get<
      ElementRef<HTMLElement>
    >(ElementRef<HTMLElement>).nativeElement;
    const liElement = document.createElement('li');
 
    this.initNotificationMessageComponent(nmComponent, notificationMessage);
    this.initWrapperContainer(config, this.wrapperComponent.instance);
    this.initLiElement(liElement, config);
 
    this.handleAriaElement(notificationMessage);
 
    const beforeDestroy = () => {
      this.notificationMessages = this.notificationMessages.filter(
        nm => nm !== nmComponent,
      );
      liElement.style.transform = `translateX(${(
        config.width + (config.gap ?? 0)
      ).toFixed(0)}px)`;
    };
 
    this.appRef.attachView(this.wrapperComponent.hostView);
    this.appRef.attachView(nmComponent.hostView);
 
    this.assembleElements(liElement, nmComponent, wrapperComponentElement);
 
    this.notificationMessages.push(nmComponent);
 
    const afterDestroy = () => {
      if (this.notificationMessages.length === 0) {
        this.appRef.detachView(this.wrapperComponent.hostView);
      }
    };
 
    playSound(
      notificationMessage.type === 'info' ? SoundType.INFO : SoundType.WARNING,
    ).catch((e: unknown) => {
      console.error(e);
    });
 
    return new NotificationMessageRef(
      nmComponent,
      beforeDestroy,
      afterDestroy,
      liElement,
      config.duration,
    );
  }
 
  /** @ignore */
  private assembleElements(
    liElement: HTMLLIElement,
    nmComponent: ComponentRef<MessageTileComponent>,
    wrapperComponentElement: HTMLElement,
  ) {
    liElement.appendChild(nmComponent.injector.get(ElementRef).nativeElement);
    this.ulElement.appendChild(liElement);
    wrapperComponentElement.appendChild(this.ulElement);
    document.body.appendChild(wrapperComponentElement);
  }
 
  /** @ignore */
  private handleAriaElement(
    notificationMessage: NotificationMessageConfig,
  ): void {
    const textEl = document.createElement('span');
    const sanitizedText =
      this.domSanitzer.sanitize(
        SecurityContext.HTML,
        notificationMessage.text,
      ) ?? '';
    const prefixText =
      notificationMessage.type === 'info' ? 'Hinweis: ' : 'Warnung: ';
 
    textEl.textContent = prefixText + sanitizedText;
    this.ariaLiveContainerElement.appendChild(textEl);
 
    const timeout = setTimeout(() => {
      textEl.remove();
      clearTimeout(timeout);
    }, SCREEN_READER_MESSAGE_DURATION);
  }
 
  /** @ignore */
  private initNotificationMessageComponent(
    nmComponent: ComponentRef<MessageTileComponent>,
    notificationMessage: NotificationMessageConfig,
  ) {
    nmComponent.instance.label = notificationMessage.title;
    nmComponent.instance.variant = notificationMessage.type;
    nmComponent.instance.buttonLabel = notificationMessage.buttonLabel ?? '';
    nmComponent.instance.textContent = notificationMessage.text;
    nmComponent.instance.closeButtonEnabled = true;
  }
 
  /** @ignore */
  private initWrapperContainer(
    config: NotificationMessagesServiceConfig,
    wrapperComponent: NotificationMessageWrapperComponent,
  ) {
    wrapperComponent.containerTop = config.topMargin ?? config.gap ?? 0;
    wrapperComponent.containerRight = config.gap ?? 0;
    wrapperComponent.containerGap = config.gap ?? 0;
    wrapperComponent.containerWidth = config.width;
  }
 
  /** @ignore */
  private initLiElement(
    liElement: HTMLLIElement,
    config: NotificationMessagesServiceConfig,
  ) {
    liElement.classList.add('gc-notification-message-child');
    liElement.style.transform = `translateX(${(
      config.width + (config.gap ?? 0)
    ).toFixed(0)}px)`;
    setTimeout(() => {
      liElement.style.transform = 'translateX(0)';
    });
  }
}
 
export class NotificationMessageRef {
  public readonly onCloseButtonAction: EventEmitter<ActionEvent> =
    new EventEmitter<ActionEvent>();
  public readonly onButtonAction: EventEmitter<ActionEvent> =
    new EventEmitter<ActionEvent>();
 
  constructor(
    private mtc: ComponentRef<MessageTileComponent>,
    private readonly beforeDestroy: Callback,
    private readonly afterDestroy: Callback,
    private listElement: HTMLElement,
    private duration?: number,
  ) {
    mtc.instance.onButtonAction.subscribe(v => this.onButtonAction.emit(v));
    mtc.instance.onCloseButtonAction.subscribe(v =>
      this.onCloseButtonAction.emit(v),
    );
    setTimeout(() => {
      this.close();
      // default duration is 5s === 5000ms
    }, this.duration ?? 5000);
  }
 
  /**
   * Closes the notification message.
   */
  public close(): void {
    // hides tooltips of child button components within the MessageTileComponent scope.
    this.mtc.instance._hideButtonTooltips();
    this.listElement.addEventListener('transitionend', () => {
      this.mtc.destroy();
      this.listElement.remove();
      this.afterDestroy();
    });
    this.beforeDestroy();
  }
}
 
/**
 * The dialog services allows the user to open dialogs above the main page.
 */
@Injectable()
export class DialogService {
  /**
   * Global configuration object for the Notification Messages Service.
   */
  public notificationMessageGlobalConfig: NotificationMessagesServiceConfig = {
    width: 300,
    gap: 16,
    topMargin: 56,
    duration: 5000,
  };
 
  constructor(
    private modalService: ModalOverlayContainerService,
    private notificationMessagesService: NotificationMessagesService,
  ) {}
 
  /**
   * Open an alert dialog to request feedback from the user.
   * @param config sets the content and style of the dialog
   * @returns reference to the created alert dialog
   */
  openAlert(config: AlertConfig): AlertRef {
    const alert = this.modalService.openDialog(
      AlertDialogComponent,
      new ModalConfig({
        type: config.type,
        label: config.title,
        variant: 'alertdialog',
      }),
    );
    const alertRef = new AlertRef(alert.overlayRef);
 
    alert.instance.label = config.title;
    alert.instance.description = config.message;
    alert.instance.primaryAction = config.primaryAction;
    alert.instance.variant = config.type === 'error' ? 'warning' : 'info';
    if (config.secondaryAction) {
      alert.instance.actions = [config.secondaryAction];
    }
    alert.instance.onItemAction.subscribe(item => {
      alertRef.onAction.emit(item);
    });
 
    return alertRef;
  }
 
  /**
   * Open a generic dialog, for example to present an input form to the user.
   * @param dialogComponent the component to show within the dialog.
   * @param config configuration options for the dialog
   * @returns reference to the created dialog which can be used to control the dialog
   */
  openDialog<T, I = unknown, R = undefined>(
    dialogComponent: Type<T>,
    config: DialogConfig<I>,
  ): DialogRef<T, I, R> {
    return new DialogRef(this.modalService, dialogComponent, config);
  }
 
  /**
   * Opens the sidebar dialog which shows passed component as it's content.
   * @param sidebarContentComponent the component that will be rendered as the sidebar content.
   * @param config configuration options for the sidebar.
   * @returns reference to the sidebar dialog which can be used to control the sidebar.
   */
  openSidebar<T>(
    sidebarContentComponent: Type<T>,
    config: SidebarConfig,
  ): SidebarRef<T> {
    return new SidebarRef(this.modalService, sidebarContentComponent, config);
  }
 
  /**
   * Creates a new notification message and shows it on the screen with a fly-in effect.
   * @param notification configuration used to create a notification message
   */
  addNotificationMessage(
    notification: NotificationMessageConfig,
  ): NotificationMessageRef {
    return this.notificationMessagesService.addNotificationMessage(
      notification,
      this.notificationMessageGlobalConfig,
    );
  }
}