71 lines
1.5 KiB
JavaScript
71 lines
1.5 KiB
JavaScript
|
const LANGUAGE_KEY = "language";
|
||
|
const languages = {};
|
||
|
let language = "en";
|
||
|
|
||
|
/**
|
||
|
* @param {string} lang
|
||
|
*/
|
||
|
async function setLanguage(lang) {
|
||
|
if (languages[lang] == undefined) {
|
||
|
const res = await fetch(`/lang/${lang}.json`);
|
||
|
const json = await res.json();
|
||
|
|
||
|
languages[lang] = json;
|
||
|
}
|
||
|
|
||
|
language = lang;
|
||
|
translatePage();
|
||
|
localStorage.setItem(LANGUAGE_KEY, lang);
|
||
|
}
|
||
|
|
||
|
/** Translates a key
|
||
|
* @param {string} key
|
||
|
* @param {any} args
|
||
|
* @returns {string}
|
||
|
*/
|
||
|
function translate(key, ...args) {
|
||
|
const bundle = languages[language];
|
||
|
let value = bundle[key];
|
||
|
if (value == undefined) {
|
||
|
value = key;
|
||
|
}
|
||
|
|
||
|
for (let i = 0; i < args.length; i++) {
|
||
|
value = value.replaceAll(`{${i}}`, args[i]);
|
||
|
}
|
||
|
|
||
|
return value;
|
||
|
}
|
||
|
|
||
|
function translatePage() {
|
||
|
const elements = document.getElementsByTagName("*");
|
||
|
for (const element of elements) {
|
||
|
const key = element.getAttribute("t");
|
||
|
if (key == null) {
|
||
|
continue;
|
||
|
}
|
||
|
|
||
|
element.innerHTML = translate(key);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
function initLanguageButtons() {
|
||
|
const buttons = document.querySelectorAll("li.select-language");
|
||
|
for (const button of buttons) {
|
||
|
button.addEventListener("click", async (ev) => {
|
||
|
const self = ev.target;
|
||
|
const lang = self.getAttribute("data-lang");
|
||
|
await setLanguage(lang);
|
||
|
});
|
||
|
}
|
||
|
}
|
||
|
|
||
|
window.addEventListener("load", async () => {
|
||
|
const lang = localStorage.getItem(LANGUAGE_KEY);
|
||
|
if (lang != null) {
|
||
|
await setLanguage(lang);
|
||
|
}
|
||
|
|
||
|
initLanguageButtons();
|
||
|
});
|