All files / translate si-no-translate.service.ts

80.95% Statements 17/21
100% Branches 6/6
57.14% Functions 8/14
80% Lines 16/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 74 75 76 77 78 79 80 81 82                  1x 1x   3x 3x         1x 4x 6x                   1x                                                 8x 10x     8x 7x   1x 1x               1x             1x      
/**
 * Copyright (c) Siemens 2016 - 2025
 * SPDX-License-Identifier: MIT
 */
import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
 
import { SiTranslateService, TranslationResult } from './si-translate.service';
 
const arrayToRecord = (keys: string[]): Record<string, string> =>
  keys.reduce(
    (acc, cur) => {
      acc[cur] = cur;
      return acc;
    },
    {} as Record<string, string>
  );
 
const replacePlaceholders = (str: string, params: Record<string, unknown>): string => {
  return str.replace(/{{\s*([^}]+)\s*}}/g, (match, p1) => {
    return params[p1] !== undefined ? String(params[p1]) : match;
  });
};
 
/**
 * Pass through implementation of the {@link SiTranslateService} which is used as a default.
 *
 * @internal
 */
@Injectable({ providedIn: 'root' })
export class SiNoTranslateService extends SiTranslateService {
  override get currentLanguage(): string {
    return 'en';
  }
 
  override get availableLanguages(): string[] {
    return ['en'];
  }
 
  override set availableLanguages(lang: string[]) {}
 
  override setCurrentLanguage(lang: string): Observable<void> {
    return of();
  }
 
  override getDefaultLanguage(): string {
    return 'en';
  }
 
  override setDefaultLanguage(lang: string): void {}
 
  override translate<T extends string | string[]>(
    keys: T,
    _params?: Record<string, unknown>
  ): TranslationResult<T> {
    const translateKey = (key: string): string => {
      return _params ? replacePlaceholders(key, _params) : key;
    };
 
    if (typeof keys === 'string') {
      return translateKey(keys) as TranslationResult<T>;
    } else {
      const translatedKeys = keys.map(translateKey);
      return arrayToRecord(translatedKeys) as TranslationResult<T>;
    }
  }
 
  override translateSync<T extends string | string[]>(
    keys: T,
    params?: Record<string, unknown>
  ): TranslationResult<T> {
    return this.translate(keys, params);
  }
 
  override translateAsync<T extends string | string[]>(
    keys: T,
    params?: Record<string, unknown>
  ): Observable<TranslationResult<T>> {
    return of(this.translate(keys, params));
  }
}