All files / language-switcher si-language-switcher.component.ts

100% Statements 18/18
88.88% Branches 8/9
100% Functions 4/4
100% Lines 18/18

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                                      1x             7x                 7x 7x               7x   7x   7x 7x 7x 3x 8x 8x           7x       2x 2x 2x 1x   1x      
/**
 * Copyright (c) Siemens 2016 - 2025
 * SPDX-License-Identifier: MIT
 */
import { Component, computed, input } from '@angular/core';
import {
  injectSiTranslateService,
  SiTranslatePipe,
  t
} from '@siemens/element-translate-ng/translate';
 
import { IsoLanguageValue } from './iso-language-value';
 
@Component({
  selector: 'si-language-switcher',
  imports: [SiTranslatePipe],
  templateUrl: './si-language-switcher.component.html',
  styleUrl: './si-language-switcher.component.scss'
})
export class SiLanguageSwitcherComponent {
  /**
   * Key for translation.
   * If the key is set to an empty string, the language of the underlying translation framework will not be switched.
   *
   * @defaultValue 'LANGUAGE'
   */
  readonly translationKey = input('LANGUAGE');
  /**
   * Text for aria label for the language selector. Needed for a11y
   *
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_LANGUAGE_SWITCHER.LABEL:Language switcher`)
   * ```
   */
  readonly languageSwitcherLabel = input(
    t(() => $localize`:@@SI_LANGUAGE_SWITCHER.LABEL:Language switcher`)
  );
 
  /**
   * List of all available languages in this application.
   *
   * @defaultValue null
   */
  readonly availableLanguages = input<(string | IsoLanguageValue)[] | null>(null);
 
  protected readonly translate = injectSiTranslateService();
 
  protected readonly availableIsoLanguages = computed(() => {
    let languages = this.availableLanguages() ?? this.translate.availableLanguages;
    if (typeof languages[0] !== 'object') {
      languages = (languages as string[]).map(languageValue => {
        const translationKey = this.translationKey();
        return {
          value: languageValue,
          name: translationKey ? `${translationKey}.${languageValue.toUpperCase()}` : languageValue
        };
      });
    }
    return languages as IsoLanguageValue[];
  });
 
  protected switchLanguage(target: EventTarget | null): void {
    const language = (target as HTMLSelectElement)?.value;
    const translationKey = this.translationKey();
    if (!language || !translationKey || translationKey.length === 0) {
      return;
    }
    this.translate.setCurrentLanguage(language);
  }
}