From 3c6d3106e82cf96fb06b70e866b0f7cd86b7c02a Mon Sep 17 00:00:00 2001 From: "Kalle (Sendou)" <38327916+Sendouc@users.noreply.github.com> Date: Wed, 2 Dec 2020 16:42:16 +0200 Subject: [PATCH] fix crash if locale "xx-xx" --- lib/lists/locales.ts | 15 +++++++++++++++ lingui.config.js | 18 +++--------------- next.config.js | 1 + pages/_app.tsx | 19 ++++++++++++++++++- 4 files changed, 37 insertions(+), 16 deletions(-) create mode 100644 lib/lists/locales.ts diff --git a/lib/lists/locales.ts b/lib/lists/locales.ts new file mode 100644 index 000000000..83db1b8f6 --- /dev/null +++ b/lib/lists/locales.ts @@ -0,0 +1,15 @@ +export const locales = [ + "de", + "en", + "es", + "fr", + "it", + "nl", + "pt", + "sv", + "el", + "ru", + "ja", + "ko", + "zh", +]; diff --git a/lingui.config.js b/lingui.config.js index b0ac4cd1a..59a78b3f3 100644 --- a/lingui.config.js +++ b/lingui.config.js @@ -1,19 +1,7 @@ +import { locales } from "./lib/lists/locales"; + module.exports = { - locales: [ - "de", - "en", - "es", - "fr", - "it", - "nl", - "pt", - "sv", - "el", - "ru", - "ja", - "ko", - "zh", - ], + locales, sourceLocale: "en", fallbackLocales: { "en-US": "en" }, orderBy: "origin", diff --git a/next.config.js b/next.config.js index f38e766f2..81947aec0 100644 --- a/next.config.js +++ b/next.config.js @@ -14,6 +14,7 @@ module.exports = withImages({ ]; }, // i18n: { + // v-- import from lib/locales // locales: [ // "de", // "el", diff --git a/pages/_app.tsx b/pages/_app.tsx index f5d678c25..3de6579fc 100644 --- a/pages/_app.tsx +++ b/pages/_app.tsx @@ -6,6 +6,7 @@ import { i18n } from "@lingui/core"; import { I18nProvider } from "@lingui/react"; import Layout from "components/layout"; import { activateLocale } from "lib/i18n"; +import { locales } from "lib/lists/locales"; import { Provider as NextAuthProvider } from "next-auth/client"; import GoogleFonts from "next-google-fonts"; import type { AppProps } from "next/app"; @@ -90,12 +91,28 @@ const extendedTheme = extendTheme({ }, }); +const getUsersLanguage = () => { + const localeFromLocalStorage = window.localStorage.getItem("locale"); + if (localeFromLocalStorage) { + return localeFromLocalStorage; + } + + const browserLanguage = navigator.languages + ? navigator.languages[0] + : navigator.language; + + // Could be either "en" or "en-US" for example - that's why the split + if (locales.includes(browserLanguage.split("-")[0])) return browserLanguage; + + return "en"; +}; + const setDisplayedLanguage = () => { const browserLanguage = navigator.languages ? navigator.languages[0] : navigator.language || "en"; const locale = window.localStorage.getItem("locale") ?? browserLanguage; - activateLocale(locale); + activateLocale(getUsersLanguage()); }; const MyApp = (props: AppProps) => {