refac: browser language detection

This commit is contained in:
Timothy J. Baek 2024-06-29 20:04:04 -07:00
parent 56137acd94
commit df8d1dacc4
2 changed files with 12 additions and 5 deletions

View File

@ -746,3 +746,10 @@ export const extractFrontmatter = (content) => {
return frontmatter; 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;
};

View File

@ -31,6 +31,7 @@
import { WEBUI_BASE_URL, WEBUI_HOSTNAME } from '$lib/constants'; import { WEBUI_BASE_URL, WEBUI_HOSTNAME } from '$lib/constants';
import i18n, { initI18n, getLanguages } from '$lib/i18n'; import i18n, { initI18n, getLanguages } from '$lib/i18n';
import { bestMatchingLanguage } from '$lib/utils';
setContext('i18n', i18n); setContext('i18n', i18n);
@ -92,12 +93,11 @@
// so `/error` can show something that's not `undefined`. // so `/error` can show something that's not `undefined`.
const languages = await getLanguages(); const languages = await getLanguages();
const browserLanguages = navigator.languages
? navigator.languages
: [navigator.language || navigator.userLanguage];
const browserLanguage = navigator.languages initI18n(bestMatchingLanguage(languages, browserLanguages, backendConfig.default_locale));
? navigator.languages[0]
: navigator.language || navigator.userLanguage;
initI18n(languages.includes(browserLanguage) ? browserLanguage : backendConfig?.default_locale);
if (backendConfig) { if (backendConfig) {
// Save Backend Status to Store // Save Backend Status to Store