Adds front-end set-up
This commit is contained in:
@@ -0,0 +1,54 @@
|
||||
import i18n from 'i18next';
|
||||
import { initReactI18next } from 'react-i18next';
|
||||
import LanguageDetector from 'i18next-browser-languagedetector';
|
||||
import enTranslation from './locales/en/translation.json';
|
||||
|
||||
export const SUPPORTED_LANGUAGES = ['en', 'nl'] as const;
|
||||
export type SupportedLanguage = (typeof SUPPORTED_LANGUAGES)[number];
|
||||
|
||||
export const LANGUAGE_LABELS: Record<SupportedLanguage, string> = {
|
||||
en: 'English',
|
||||
nl: 'Nederlands',
|
||||
};
|
||||
|
||||
// English (the fallback) is bundled eagerly so the UI never flashes raw keys.
|
||||
// Other locales are lazy-loaded on demand (Q4-B / NFR-U1-05).
|
||||
const loaded = new Set<string>(['en']);
|
||||
|
||||
async function loadLocale(lng: string): Promise<void> {
|
||||
if (loaded.has(lng) || !SUPPORTED_LANGUAGES.includes(lng as SupportedLanguage)) {
|
||||
return;
|
||||
}
|
||||
const module = await import(`./locales/${lng}/translation.json`);
|
||||
i18n.addResourceBundle(lng, 'translation', module.default, true, true);
|
||||
loaded.add(lng);
|
||||
}
|
||||
|
||||
void i18n
|
||||
.use(LanguageDetector)
|
||||
.use(initReactI18next)
|
||||
.init({
|
||||
resources: {
|
||||
en: { translation: enTranslation },
|
||||
},
|
||||
fallbackLng: 'en',
|
||||
supportedLngs: SUPPORTED_LANGUAGES as unknown as string[],
|
||||
nonExplicitSupportedLngs: true,
|
||||
interpolation: { escapeValue: false },
|
||||
detection: {
|
||||
order: ['localStorage', 'navigator'],
|
||||
caches: ['localStorage'],
|
||||
},
|
||||
react: { useSuspense: false },
|
||||
});
|
||||
|
||||
// Ensure the detected language is loaded after init.
|
||||
void loadLocale(i18n.resolvedLanguage ?? 'en');
|
||||
|
||||
/** Lazy-load the target locale, then switch to it (persisted by the detector). */
|
||||
export async function changeLanguage(lng: SupportedLanguage): Promise<void> {
|
||||
await loadLocale(lng);
|
||||
await i18n.changeLanguage(lng);
|
||||
}
|
||||
|
||||
export default i18n;
|
||||
Reference in New Issue
Block a user