All files / src/components/web-component-wrapper si-web-component-wrapper-base.component.ts

52.17% Statements 12/23
34.78% Branches 8/23
25% Functions 1/4
42.1% Lines 8/19

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                                        3x           1x       1x 1x   1x 1x         1x 1x                                                    
/**
 * Copyright (c) Siemens 2016 - 2026
 * SPDX-License-Identifier: MIT
 */
import {
  AfterViewInit,
  ElementRef,
  inject,
  Renderer2,
  DOCUMENT,
  Directive,
  input,
  viewChild,
  SimpleChanges,
  OnChanges
} from '@angular/core';
 
import { WidgetConfig, WidgetInstance, WidgetInstanceEditor } from '../../model/widgets.model';
 
@Directive()
export abstract class SiWebComponentWrapperBaseComponentE<
  T extends WidgetInstance | WidgetInstanceEditor
>
  implements AfterViewInit, OnChanges
{
  readonly config =
    input.required<
      T extends WidgetInstance ? WidgetConfig : WidgetConfig | Omit<WidgetConfig, 'id'>
    >();
 
  readonly elementTagName = input.required<string>();
  readonly url = input.required<string>();
 
  protected readonly webComponentHost = viewChild.required('webComponentHost', {
    read: ElementRef
  });
 
  protected webComponent?: HTMLElement & T;
 
  private renderer2 = inject(Renderer2);
  private document = inject(DOCUMENT);
 
  ngOnChanges(changes: SimpleChanges<this>): void {
    if (changes.config && this.webComponent) {
      this.webComponent.config = this.config();
    }
  }
 
  ngAfterViewInit(): void {
    if (!this.isScriptLoaded(this.url())) {
      const script = this.renderer2.createElement('script');
      script.src = this.url();
      this.renderer2.appendChild(this.document.body, script);
    }
 
    this.webComponent = this.renderer2.createElement(this.elementTagName());
    if (this.webComponent) {
      this.webComponent.config = this.config();
    }
  }
 
  private isScriptLoaded(url: string): boolean {
    const script = document.querySelector(`script[src='${url}']`);
    return script ? true : false;
  }
}