Improve + refactor the Auto-Detect language apply method

This commit is contained in:
Alicia Sykes 2021-07-25 12:30:43 +01:00
parent 0f5b6a2ec7
commit bc9011ee0b

View File

@ -17,6 +17,7 @@ import {
localStorageKeys,
splashScreenTime,
visibleComponents as defaultVisibleComponents,
language as defaultLanguage,
} from '@/utils/defaults';
const Accumulator = new ConfigAccumulator();
@ -72,23 +73,26 @@ export default {
},
/* Checks local storage, then appConfig, and if a custom language is specified, its applied */
applyLanguage() {
// If user has specified a language, then check and apply it
const lang = localStorage[localStorageKeys.LANGUAGE] || this.appConfig.language;
if (lang && this.$i18n.availableLocales.includes(lang)) {
this.$i18n.locale = lang;
let language = defaultLanguage; // Language to apply
const availibleLocales = this.$i18n.availableLocales; // All available locales
// If user has specified a language, locally or in config, then check and apply it
const usersLang = localStorage[localStorageKeys.LANGUAGE] || this.appConfig.language;
if (usersLang && availibleLocales.includes(usersLang)) {
language = usersLang;
} else {
// Attempt to apply language automatically, based on their system language
let locale;
// Otherwise, attempt to apply language automatically, based on their system language
const usersBorwserLang1 = window.navigator.language || ''; // e.g. en-GB or or ''
const usersBorwserLang2 = usersBorwserLang1.split('-')[0]; // e.g. en or undefined
const availibleLocales = this.$i18n.availableLocales;
if (availibleLocales.includes(usersBorwserLang1)) {
locale = usersBorwserLang1;
language = usersBorwserLang1;
} else if (availibleLocales.includes(usersBorwserLang2)) {
locale = usersBorwserLang2;
language = usersBorwserLang2;
}
if (locale) this.$i18n.locale = locale; // If lanuage was found, apply it
}
// Apply Language
this.$i18n.locale = language;
document.getElementsByTagName('html')[0].setAttribute('lang', language);
},
},
/* When component mounted, hide splash and initiate the injection of custom styles */