All files / translate t.ts

84.61% Statements 11/13
33.33% Branches 1/3
100% Functions 2/2
84.61% Lines 11/13

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                        1x 9x           9x                                   1x   9x     9x 9x 9x 9x     9x 9x    
/**
 * Copyright (c) Siemens 2016 - 2025
 * SPDX-License-Identifier: MIT
 */
import { inject } from '@angular/core';
import { TranslatableString } from '@siemens/element-translate-ng/translate-types';
 
import { globalScope } from './global.scope';
import { SiTranslatableService } from './si-translatable.service';
import { injectSiTranslateService } from './si-translate.inject';
 
// an alternative implementation for $localize meant to be used for translation frameworks other than @angular/localize
const $localize = (strings: TemplateStringsArray, ...expressions: string[]): TranslatableString => {
  Iif (strings.length !== 1) {
    throw new Error(
      '$localize calls using @siemens/element-translate-ng do not support parameter interpolation'
    );
  }
 
  return strings[0];
};
 
/**
 * Always wrap `$localize` calls in this function within element components.
 * It may patch the global $localize based on the current translation framework.
 *
 * This function requires an `InjectionContext.`
 *
 * @internal
 *
 * @example
 * ```ts
 * class MyComponent {
 *   readonly myText = t(() => $localize`:@@my-text:This is a default text`);
 * }
 * ```
 */
export const t = (localizeWrapperFunction: () => string): TranslatableString => {
  let localizeString: string;
  Iif (injectSiTranslateService().prevent$LocalizeInit) {
    localizeString = localizeWrapperFunction();
  } else {
    const $localizeBackup = globalScope.$localize;
    globalScope.$localize = $localize;
    localizeString = localizeWrapperFunction();
    globalScope.$localize = $localizeBackup;
  }
 
  const [, key, value] = /:.*?@@(.*?):(.*)/.exec(localizeString)!;
  return inject(SiTranslatableService).resolveText(key, value);
};