All files / translate si-translatable.service.ts

100% Statements 9/9
100% Branches 7/7
100% Functions 3/3
100% Lines 8/8

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                              1x           10x 10x   10x 10x       13x 2x     13x      
/**
 * Copyright (c) Siemens 2016 - 2025
 * SPDX-License-Identifier: MIT
 */
import { inject, Injectable } from '@angular/core';
import { TranslatableString } from '@siemens/element-translate-ng/translate-types';
 
import { SiNoTranslateService } from './si-no-translate.service';
import { SI_TRANSLATABLE_VALUES } from './si-translatable.model';
import { injectSiTranslateService } from './si-translate.inject';
import { SiTranslateService } from './si-translate.service';
 
@Injectable({
  providedIn: 'root'
})
export class SiTranslatableService {
  private readonly translatableValues: Record<string, string>;
  private readonly isNoTranslate: boolean;
  private readonly siTranslateService: SiTranslateService;
 
  constructor() {
    this.siTranslateService = injectSiTranslateService();
    const translateValues = inject(SI_TRANSLATABLE_VALUES, { optional: true });
 
    this.translatableValues = translateValues?.reduce((a, b) => ({ ...a, ...b })) ?? {};
    this.isNoTranslate = this.siTranslateService instanceof SiNoTranslateService;
  }
 
  resolveText(key: string, originalText: string): TranslatableString {
    if (this.siTranslateService.setTranslation) {
      this.siTranslateService.setTranslation(key, originalText);
    }
 
    return this.translatableValues[key] ?? (this.isNoTranslate ? originalText : key);
  }
}