diff --git a/src/lib/i18n/index.ts b/src/lib/i18n/index.ts index 548e6709e8..48872052ba 100644 --- a/src/lib/i18n/index.ts +++ b/src/lib/i18n/index.ts @@ -6,6 +6,7 @@ import { writable } from 'svelte/store'; import type { I18nOverrides } from '$lib/utils/translationDictionary'; import { assembleSettingsTranslations } from './settings-translations'; +import languages from './locales/languages.json'; let overrides: I18nOverrides = {}; @@ -71,6 +72,19 @@ const createIsLoadingStore = (i18n: i18nType) => { return isLoading; }; +const languageCodes = languages.map(({ code }) => code); + +const toBundleCode = (code: string) => { + const ownBundle = languageCodes.find((bundle) => bundle.toLowerCase() === code.toLowerCase()); + if (ownBundle) return ownBundle; + const baseLanguage = code.split('-')[0].toLowerCase(); + const primaryBundle = `${baseLanguage}-${baseLanguage.toUpperCase()}`; + if (languageCodes.includes(primaryBundle)) return primaryBundle; + // the first sibling of a regional code can be another script (zh-HK would get zh-CN) + if (code.includes('-')) return code; + return languageCodes.find((bundle) => bundle.startsWith(`${baseLanguage}-`)) ?? code; +}; + export const initI18n = (defaultLocale?: string, value: I18nOverrides = {}) => { overrides = value; const detectionOrder = defaultLocale @@ -87,7 +101,8 @@ export const initI18n = (defaultLocale?: string, value: I18nOverrides = {}) => { order: detectionOrder, caches: ['localStorage'], lookupQuerystring: 'lang', - lookupLocalStorage: 'locale' + lookupLocalStorage: 'locale', + convertDetectedLanguage: toBundleCode }, fallbackLng: { fr: ['fr-FR'], @@ -106,10 +121,7 @@ export const initI18n = (defaultLocale?: string, value: I18nOverrides = {}) => { const i18n = createI18nStore(i18next); const isLoadingStore = createIsLoadingStore(i18next); -export const getLanguages = async () => { - const languages = (await import(`./locales/languages.json`)).default; - return languages; -}; +export const getLanguages = async () => languages; export const changeLanguage = (lang: string) => { document.documentElement.setAttribute('lang', lang); return i18next.changeLanguage(lang);