From 5db4897725aef61d529611de48cbc560b7de4b4a Mon Sep 17 00:00:00 2001 From: Lenny Angst Date: Tue, 8 Jul 2025 18:22:10 +0200 Subject: [PATCH] Enhance getUserLocale to better find the best lang The current implementation of getUserLocale didn't catch regional variations of the languages. These are separated by a dash and uppercase letters. E.g. a user with 'de-CH' didn't get the German translation but fell back to English. This new implementation also considers these variations and falls back to the more general language if the exact variation is not available. Additionally, instead of navigator.language we now use navigator.languages, which contains all of the browsers preferred languages in order. This features is supported by all major browsers since 2017. ['it', 'de'] will then resolve to German instead of English. --- materialious/src/lib/i18n/index.ts | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/materialious/src/lib/i18n/index.ts b/materialious/src/lib/i18n/index.ts index e4f3f121..e62b5313 100644 --- a/materialious/src/lib/i18n/index.ts +++ b/materialious/src/lib/i18n/index.ts @@ -23,8 +23,16 @@ const resources: Record Promise>> = { function getUserLocale(): string { if (typeof navigator !== 'undefined') { - const lang = navigator.language; - return resources[lang] ? lang : defaultLocale; + for (const lang of navigator.languages) { + if (resources[lang]) { + return lang; + } + // In case of a regional code (e.g. 'de-CH'), fallback to the more general lang + const baseLang = lang.split('-')[0] + if (resources[baseLang]) { + return baseLang + } + } } return defaultLocale; }