lavkach3
1// The locale our app first shows
2const defaultLocale = "en";3
4// The active locale
5
6let locale;7
8// Gets filled with active locale translations
9
10let translations = {};11
12// When the page content is ready...
13
14document.addEventListener("DOMContentLoaded", () => {15
16// Translate the page to the default locale17
18setLocale(userSettings.locale);19
20});21
22// Load translations for the given locale and translate
23
24// the page to this locale
25
26async function setLocale(newLocale) {27document.getElementsByTagName('html')[0].setAttribute('lang', newLocale);28userSettings.locale = newLocale;29document.cookie = "locale="+userSettings.locale+";path=/;"30if (newLocale === locale) return;31
32const newTranslations = await fetchTranslationsFor(newLocale);33
34locale = newLocale;35
36translations = newTranslations;37
38translatePage();39
40}
41
42// Retrieve translations JSON object for the given
43
44// locale over the network
45
46async function fetchTranslationsFor(newLocale) {47
48const response = await fetch(`/static/js/i18n/${newLocale}.json`);49
50return await response.json();51
52}
53
54// Replace the inner text of each element that has a
55
56// data-i18n-key attribute with the translation corresponding
57
58// to its data-i18n-key
59
60function translatePage() {61
62document.querySelectorAll("[data-key]").forEach(translateElement);63
64}
65
66// Replace the inner text of the given HTML element
67
68// with the translation in the active locale,
69
70// corresponding to the element's data-i18n-key
71
72function translateElement(element) {73
74const key = element.getAttribute("data-key");75
76const translation = translations[key];77if (!translation) {78
79console.warn(`No translation found for key: ${key}`);80
81return82
83
84} else {85element.innerText = translation;86}87}
88
89
90///--->
91