All files / src i18n.ts

92.85% Statements 13/14
61.53% Branches 8/13
100% Functions 4/4
92.3% Lines 12/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                  13x   13x   13x 21x     16x 17x 17x   1x     13x                   4x 4x       2x            
import i18n from 'i18next'
import { initReactI18next } from 'react-i18next'
import type { components } from './api'
import { EN } from './locales/en'
import { DE } from './locales/de'
import { HU } from './locales/hu'
 
export type Language = NonNullable<components['schemas']['UserPreferences']['language']>
 
export const SUPPORTED_LANGUAGES = ['EN', 'DE', 'HU'] as const satisfies readonly Language[]
 
const FALLBACK_LANGUAGE: Language = 'EN'
 
const isSupported = (lang: string): lang is Language =>
	(SUPPORTED_LANGUAGES as readonly string[]).includes(lang)
 
export function detectInitialLanguage(): Language {
	for (const tag of navigator.languages ?? [navigator.language]) {
		const base = tag.toUpperCase().split('-')[0]
		if (isSupported(base)) return base
	}
	return FALLBACK_LANGUAGE
}
 
i18n.use(initReactI18next).init({
	resources: { EN, DE, HU },
	lng: detectInitialLanguage(),
	fallbackLng: FALLBACK_LANGUAGE,
	supportedLngs: SUPPORTED_LANGUAGES,
	interpolation: { escapeValue: false }, // React already escapes
	returnNull: false,
})
 
export function currentLanguage(): Language {
	const lang = i18n.resolvedLanguage
	return lang && isSupported(lang) ? lang : FALLBACK_LANGUAGE
}
 
export function applyUserLanguage(lang: string | undefined | null) {
	Iif (lang && isSupported(lang) && i18n.resolvedLanguage !== lang) {
		void i18n.changeLanguage(lang)
	}
}
 
export default i18n