Skip to content

Commit

Permalink
Set dialect when reading from local storage (#5095)
Browse files Browse the repository at this point in the history
  • Loading branch information
hpeebles authored Jan 2, 2024
1 parent 35407d6 commit 7666b22
Showing 1 changed file with 20 additions and 8 deletions.
28 changes: 20 additions & 8 deletions frontend/app/src/i18n/i18n.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand All @@ -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(),
Expand Down

0 comments on commit 7666b22

Please sign in to comment.