42_ft_transcendence/frontend/static/js/api/LanguageManager.js
2024-01-24 14:13:11 +01:00

46 lines
1.2 KiB
JavaScript

export default class LanguageManager {
constructor() {
this.availableLanguages = ['en', 'fr'];
this.currentLang = 'en'
this.chosenLang = localStorage.getItem('preferedLanguage') || this.currentLang;
if (this.chosenLang !== this.currentLang && this.availableLanguages.includes(this.chosenLang)) {
this.translatePage();
}
}
async translatePage() {
if (this.currentLang === this.chosenLang)
return;
let dictUrl = `${location.origin}/static/js/lang/${this.chosenLang}.json`;
let translation = await fetch(dictUrl).then(response => {
if (response.status !== 200)
return null;
return response.json();
});
if (!translation) {
console.log(`No translation found for language ${this.chosenLang}`);
return 1;
}
document.querySelectorAll('[data-i18n]').forEach(el => {
let key = el.getAttribute('data-i18n');
el.innerHTML = translation[key];
})
this.currentLang = this.chosenLang;
return 0;
}
async changeLanguage(lang) {
if (lang === this.currentLang || !this.availableLanguages.includes(lang))
return;
this.chosenLang = lang;
if (await this.translatePage() !== 0)
return;
localStorage.setItem('preferedLanguage', lang);
}
}