-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtranslation-intl.js
80 lines (74 loc) · 2.33 KB
/
translation-intl.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
class Translator {
/**
* Creates a new Translator instance.
*
* @param {string} locale - The locale to use for translations (e.g. 'en-US', 'uk-UA', etc.). Defaults to 'en-US'.
* @param {object} translations - An object containing translations for each locale.
*
* Example:
* const translations = {
* 'en-US': {
* hello: 'Hello',
* goodbye: 'Goodbye'
* },
* 'uk-UA': {
* hello: 'Привіт',
* goodbye: 'До побачення'
* }
* };
* const translator = new Translator('uk-UA', translations);
*/
constructor(locale, translations) {
this.locale = locale || 'en-US';
this.translations = translations || {};
this.formatter = new Intl.MessageFormat(this.translations[this.locale] || {}, this.locale);
}
/**
* Translates all elements with a `data-translate` attribute.
*
* Example:
* <div data-translate="hello"></div>
* translator.translate(); // translates the element to "Привіт" (or "Hello" depending on the locale)
*/
translate() {
document.querySelectorAll('[data-translate]').forEach(element => {
const key = element.dataset.translate;
const translation = this.formatter.format({ id: key });
if (translation) {
element.innerHTML = translation;
} else {
console.warn(`Translation not found for key: ${key} in locale: ${this.locale}`);
}
});
}
/**
* Sets a new locale for the translator.
*
* @param {string} locale - The new locale to use for translations.
*
* Example:
* translator.setLocale('en-US');
* translator.translate(); // translates elements to English
*/
setLocale(locale) {
this.locale = locale;
this.formatter = new Intl.MessageFormat(this.translations[this.locale] || {}, this.locale);
}
}
// Usage example:
const translations = {
'en-US': {
hello: 'Hello',
goodbye: 'Goodbye'
},
'uk-UA': {
hello: 'Привіт',
goodbye: 'До побачення'
}
// other locales...
};
const translator = new Translator('uk-UA', translations);
translator.translate();
// To change the locale:
translator.setLocale('en-US');
translator.translate();