All files / app/services language.service.ts

12.5% Statements 4/32
12.5% Branches 3/24
0% Functions 0/6
10.34% Lines 3/29

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            1x 1x         1x                                                                                                                    
import { DOCUMENT, isPlatformBrowser } from '@angular/common';
import { Injectable, PLATFORM_ID, inject, signal } from '@angular/core';
import { TranslocoService } from '@jsverse/transloco';
 
export type AppLanguage = 'de' | 'en';
 
const LANGUAGE_STORAGE_KEY = 'nimmit-language';
const SUPPORTED_LANGUAGES: readonly AppLanguage[] = ['de', 'en'] as const;
 
@Injectable({
  providedIn: 'root',
})
export class LanguageService {
  private readonly platformId = inject(PLATFORM_ID);
  private readonly isBrowser = isPlatformBrowser(this.platformId);
  private readonly transloco = inject(TranslocoService);
  private readonly document = inject(DOCUMENT);
 
  readonly language = signal<AppLanguage>(this.getInitialLanguage());
 
  init(): void {
    this.applyLanguage(this.language());
  }
 
  setLanguage(language: AppLanguage): void {
    if (!SUPPORTED_LANGUAGES.includes(language)) {
      return;
    }
 
    this.language.set(language);
    this.applyLanguage(language);
  }
 
  getSupportedLanguages(): readonly AppLanguage[] {
    return SUPPORTED_LANGUAGES;
  }
 
  getLocale(): string {
    return this.language() === 'de' ? 'de-DE' : 'en-US';
  }
 
  private applyLanguage(language: AppLanguage): void {
    this.transloco.setActiveLang(language);
 
    if (this.isBrowser) {
      localStorage.setItem(LANGUAGE_STORAGE_KEY, language);
    }
 
    this.document.documentElement.lang = language;
  }
 
  private getInitialLanguage(): AppLanguage {
    if (this.isBrowser) {
      const stored = localStorage.getItem(LANGUAGE_STORAGE_KEY);
      if (stored === 'de' || stored === 'en') {
        return stored;
      }
 
      const browserLang = navigator.language?.toLowerCase() ?? '';
      if (browserLang.startsWith('de')) {
        return 'de';
      }
      if (browserLang.startsWith('en')) {
        return 'en';
      }
    }
 
    return 'de';
  }
}