All files / translate si-translate.pipe.ts

95.45% Statements 21/22
83.33% Branches 5/6
100% Functions 4/4
95% Lines 19/20

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                                              1x   9x   9x 9x                     21x       21x   21x 5x     16x   16x 16x 8x   9x     16x       9x 9x       17x 17x 17x      
/**
 * Copyright (c) Siemens 2016 - 2025
 * SPDX-License-Identifier: MIT
 */
import { ChangeDetectorRef, inject, OnDestroy, Pipe, PipeTransform } from '@angular/core';
import { Subscription } from 'rxjs';
 
import { injectSiTranslateService } from './si-translate.inject';
import { SiTranslateService } from './si-translate.service';
 
/**
 * Translates keys by using the {@link SiTranslateService}.
 * Within Element this pipe should be used instead of ngx-translates `translate` pipe.
 * Outside Element, this pipe should NOT be used.
 *
 * @internal
 */
 
@Pipe({
  name: 'translate',
  // eslint-disable-next-line @angular-eslint/no-pipe-impure
  pure: false
})
export class SiTranslatePipe implements PipeTransform, OnDestroy {
  private lastKeyParams?: string;
  private value = '';
  private subscription?: Subscription;
  private siTranslateService = injectSiTranslateService();
  private cdRef = inject(ChangeDetectorRef);
 
  /**
   * Method which is called on any data passed to the pipe.
   * Called by Angular, should not be called directly.
   */
  // The first type is for cases when there is definitely defined string, so that we can use the pipe to assign values to a required variable.
  // The second type is for everything else, so that we can use the pipe for optional inputs
  transform(key: string, params?: any): string;
  transform(key: string | null | undefined, params?: any): string | null | undefined;
  transform(key: string | null | undefined, params?: any): string | null | undefined {
    Iif (!key) {
      return key;
    }
 
    const currentKeyParams = params ? `${key}-${JSON.stringify(params)}` : key;
 
    if (this.lastKeyParams === currentKeyParams) {
      return this.value;
    }
 
    this.subscription?.unsubscribe();
 
    const translate = this.siTranslateService.translate(key, params);
    if (typeof translate === 'string') {
      this.updateValue(currentKeyParams, translate);
    } else {
      this.subscription = translate.subscribe(value => this.updateValue(currentKeyParams, value));
    }
 
    return this.value;
  }
 
  ngOnDestroy(): void {
    this.subscription?.unsubscribe();
    this.subscription = undefined;
  }
 
  private updateValue(currentKeyParams: string, value: string): void {
    this.lastKeyParams = currentKeyParams;
    this.value = value;
    this.cdRef.markForCheck();
  }
}