From 7666b2265b22d0889fa7b17e44d1cddaeb41acaa Mon Sep 17 00:00:00 2001 From: Hamish Peebles Date: Tue, 2 Jan 2024 18:04:01 +0000 Subject: [PATCH] Set dialect when reading from local storage (#5095) --- frontend/app/src/i18n/i18n.ts | 28 ++++++++++++++++++++-------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/frontend/app/src/i18n/i18n.ts b/frontend/app/src/i18n/i18n.ts index 9fdf0dc974..09563780eb 100644 --- a/frontend/app/src/i18n/i18n.ts +++ b/frontend/app/src/i18n/i18n.ts @@ -79,17 +79,17 @@ register("vi", () => import("./vi.json")); register("iw", () => import("./iw.json")); export function getStoredLocale(): string { - return localStorage.getItem(configKeys.locale) ?? (getLocaleFromNavigator() || "en"); + const fromStorage = localStorage.getItem(configKeys.locale); + + if (fromStorage === null) { + return getLocaleFromNavigator() || "en"; + } + + return setDialectIfMatchesBrowserLocale(fromStorage); } export function setLocale(code: string): void { - const localeFromNavigator = getLocaleFromNavigator(); - - // If the browser is set to a dialect of the chosen locale, use that dialect, else use the locale passed in. - // Eg. if the user selects "en" and the browser is set to "en-US", then we use "en-US" - if (localeFromNavigator !== null && localeFromNavigator.startsWith(code)) { - code = localeFromNavigator; - } + code = setDialectIfMatchesBrowserLocale(code); localStorage.setItem(configKeys.locale, code); @@ -102,6 +102,18 @@ export function i18nFormatter(str: string): string { return get(_)(str); } +function setDialectIfMatchesBrowserLocale(code: string): string { + const localeFromNavigator = getLocaleFromNavigator(); + + // If the browser is set to a dialect of the chosen locale, use that dialect, else use the locale passed in. + // Eg. if the user selects "en" and the browser is set to "en-US", then we use "en-US" + if (localeFromNavigator !== null && localeFromNavigator.startsWith(code)) { + return localeFromNavigator; + } + + return code; +} + init({ fallbackLocale: "en", initialLocale: getStoredLocale(),