From 7635ab54a08991cccf58655b6fc0244b33899fb3 Mon Sep 17 00:00:00 2001 From: Frank Elsinga Date: Sun, 7 Jan 2024 16:55:10 +0100 Subject: [PATCH] made sure that the i18n does use `navigator.languages` instead of `navigator.language` for automatic language detection (#4244) --- src/i18n.js | 14 ++++++++++---- test/cypress/unit/i18n.spec.js | 12 ++++++++---- 2 files changed, 18 insertions(+), 8 deletions(-) diff --git a/src/i18n.js b/src/i18n.js index c33b523e2..ad3894d46 100644 --- a/src/i18n.js +++ b/src/i18n.js @@ -57,10 +57,16 @@ for (let lang in languageList) { const rtlLangs = [ "fa", "ar-SY", "ur" ]; -export const currentLocale = () => localStorage.locale - || languageList[navigator.language] && navigator.language - || languageList[navigator.language.substring(0, 2)] && navigator.language.substring(0, 2) - || "en"; +/** + * Find the best matching locale to display + * If no locale can be matched, the default is "en" + * @returns {string} the locale that should be displayed + */ +export function currentLocale() { + const potentialLocales = [ localStorage.locale, navigator.language, navigator.language.substring(0, 2), ...navigator.languages ]; + const availableLocales = potentialLocales.filter(l => languageList[l]); + return availableLocales[0] || "en"; +} export const localeDirection = () => { return rtlLangs.includes(currentLocale()) ? "rtl" : "ltr"; diff --git a/test/cypress/unit/i18n.spec.js b/test/cypress/unit/i18n.spec.js index da63d95a5..c53f341f2 100644 --- a/test/cypress/unit/i18n.spec.js +++ b/test/cypress/unit/i18n.spec.js @@ -4,9 +4,13 @@ describe("Test i18n.js", () => { it("currentLocale()", () => { const setLanguage = (language) => { - Object.defineProperty(window.navigator, 'language', { - value: language, - writable: true + Object.defineProperty(window.navigator, 'language', { + value: language, + writable: true + }); + Object.defineProperty(window.navigator, 'languages', { + value: [language], + writable: true }); } setLanguage('en-EN'); @@ -41,4 +45,4 @@ describe("Test i18n.js", () => { expect(currentLocale()).equal("zh-HK"); }); -}); \ No newline at end of file +});