From df8d1dacc4c57d4e91935759a68911cd33292d16 Mon Sep 17 00:00:00 2001 From: "Timothy J. Baek" Date: Sat, 29 Jun 2024 20:04:04 -0700 Subject: [PATCH] refac: browser language detection --- src/lib/utils/index.ts | 7 +++++++ src/routes/+layout.svelte | 10 +++++----- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/src/lib/utils/index.ts b/src/lib/utils/index.ts index 6e9f29205..cf7a826ab 100644 --- a/src/lib/utils/index.ts +++ b/src/lib/utils/index.ts @@ -746,3 +746,10 @@ export const extractFrontmatter = (content) => { return frontmatter; }; + +// Function to determine the best matching language +export const bestMatchingLanguage = (supportedLanguages, preferredLanguages, defaultLocale) => { + const languages = supportedLanguages.map((lang) => lang.code); + const match = preferredLanguages.find((lang) => languages.includes(lang)); + return match || defaultLocale; +}; diff --git a/src/routes/+layout.svelte b/src/routes/+layout.svelte index 7a703cce6..4409d3f05 100644 --- a/src/routes/+layout.svelte +++ b/src/routes/+layout.svelte @@ -31,6 +31,7 @@ import { WEBUI_BASE_URL, WEBUI_HOSTNAME } from '$lib/constants'; import i18n, { initI18n, getLanguages } from '$lib/i18n'; + import { bestMatchingLanguage } from '$lib/utils'; setContext('i18n', i18n); @@ -92,12 +93,11 @@ // so `/error` can show something that's not `undefined`. const languages = await getLanguages(); + const browserLanguages = navigator.languages + ? navigator.languages + : [navigator.language || navigator.userLanguage]; - const browserLanguage = navigator.languages - ? navigator.languages[0] - : navigator.language || navigator.userLanguage; - - initI18n(languages.includes(browserLanguage) ? browserLanguage : backendConfig?.default_locale); + initI18n(bestMatchingLanguage(languages, browserLanguages, backendConfig.default_locale)); if (backendConfig) { // Save Backend Status to Store