-
Notifications
You must be signed in to change notification settings - Fork 39
/
translate.js
80 lines (71 loc) · 3.07 KB
/
translate.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// Initialize i18next with options
i18next
.use(i18nextXHRBackend) // Uses backend to load JSON files
.init({
lng: 'en', // Default language
fallbackLng: 'en', // Fallback language if requested language is not found
debug: true, // Mode débogage pour le développement
backend: {
loadPath: '/locales/{{lng}}/translation.json' // Path to translation files
}
})
.then(() => {
// Detects language and translates web page
detectLanguageAndTranslate();
})
.catch(error => {
console.error('Error while loading i18next:', error);
});
// Function to load translations using i18next
async function loadTranslations(lang) {
try {
await i18next.changeLanguage(lang); // Change language
document.querySelectorAll('[data-translate]').forEach(element => {
const key = element.getAttribute('data-translate');
let translation = i18next.t(key); // Use i18next to get translated text
// Purify the translation before injecting it into the DOM
element.innerHTML = DOMPurify.sanitize(translation, {
ALLOWED_TAGS: ['strong', 'em', 'u', 'span', 'pre'],
ALLOWED_ATTR: ['class'] // Allow class attribute in general, restricted by the hook
});
});
// Verifies whether language is RTL and applies fix
const isRtlLang = i18next.dir().toLowerCase() === 'rtl';
document.documentElement.setAttribute('dir', isRtlLang ? 'rtl' : 'ltr');
} catch (error) {
console.error(error);
}
}
// Function to detect browser language and apply it
function detectLanguageAndTranslate() {
// Gets URL parameters
const urlParams = new URLSearchParams(window.location.search);
const urlLang = urlParams.get('lang');
// Detects browser language if no URL parameter is specified
const userLang = urlLang || navigator.language || navigator.userLanguage;
const langCode = userLang.toLowerCase(); // Complete language code
const primaryLangCode = langCode.split('-')[0]; // Language code without regional indicator
// Tries loading translations with partial language code
loadTranslations(primaryLangCode)
.catch(() => {
// If no language is detected, try loading with the complete language code
return loadTranslations(langCode);
})
.catch(() => {
// If no translation is found, switch to default (English)
return loadTranslations('en');
});
}
// Manages language switching with dropdown menu
document.querySelectorAll('.lang-option').forEach(option => {
option.addEventListener('click', function(event) {
event.preventDefault(); // Prevents page from reloading
const selectedLang = option.getAttribute('data-lang');
// Updates URL with new language
const newUrl = new URL(window.location.href);
newUrl.searchParams.set('lang', selectedLang);
window.history.pushState({ path: newUrl.href }, '', newUrl.href);
loadTranslations(selectedLang);
document.getElementById('dropdownContent').style.display = 'none';
});
})