2024-03-01 21:56:42 +01:00
|
|
|
/**
|
|
|
|
* Usage:
|
|
|
|
* import i18n from './i18n.js'
|
|
|
|
*
|
|
|
|
* console.log( i18n('parentcontext.childcontext.key', {user: username}) );
|
|
|
|
*
|
|
|
|
* language is loaded from cookie: lang=XX
|
|
|
|
* translations are loaded from /public/i18n/XX.txt
|
|
|
|
*
|
|
|
|
*/
|
|
|
|
|
2024-03-08 11:23:32 +01:00
|
|
|
import { getCookie, setCookie } from './utils.js';
|
2024-03-06 21:38:09 +01:00
|
|
|
|
2024-03-01 21:56:42 +01:00
|
|
|
const default_lang = "EN";
|
|
|
|
let langs;
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Fetch the translation from a key using the current language.
|
|
|
|
* could also replace certain value of the form `$variable` by providing an object
|
|
|
|
* with { variable: "value" }
|
|
|
|
* @param key :string translation key (can be null)
|
|
|
|
* @param options: Object element to replace in the translation
|
|
|
|
*
|
|
|
|
* @return :string The translated text
|
|
|
|
*/
|
2024-03-05 20:28:23 +01:00
|
|
|
export default function i18n(key, options) {
|
2024-03-01 21:56:42 +01:00
|
|
|
let ret = langs[key];
|
|
|
|
if(options != null){
|
|
|
|
for (let key in options) {
|
|
|
|
ret = ret.replaceAll("$" + key, options[key]);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return ret;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Function that load the file with translation from the specified lang and return a dictionnary
|
|
|
|
* @param select the language to load. could be null to fetch the cookies for an answer
|
|
|
|
* if nothing is found. default to EN.txt
|
|
|
|
*/
|
2024-03-05 20:28:23 +01:00
|
|
|
export async function loadLangs(lang){
|
2024-03-01 21:56:42 +01:00
|
|
|
lang = lang != null ? lang : getCookie("lang");
|
|
|
|
lang = lang != "" ? lang : default_lang;
|
|
|
|
|
2024-03-06 14:41:03 +01:00
|
|
|
const filename = "/i18n/" + lang.toUpperCase() + ".txt";
|
2024-03-01 21:56:42 +01:00
|
|
|
const content = await (await fetch(filename)).text();
|
|
|
|
const lines = content.split("\n");
|
|
|
|
|
|
|
|
let filteredLines = {};
|
|
|
|
for (let line of lines) {
|
|
|
|
if(!line.trim().startsWith("#") && line.trim() != ""){
|
|
|
|
let split = line.indexOf("=")
|
|
|
|
filteredLines[line.substr(0, split)] = line.substr(split+1, line.length);
|
|
|
|
};
|
|
|
|
}
|
2024-03-05 20:28:23 +01:00
|
|
|
langs = filteredLines;
|
2024-03-01 21:56:42 +01:00
|
|
|
}
|
2024-03-05 20:28:23 +01:00
|
|
|
await loadLangs();
|
2024-03-08 11:23:32 +01:00
|
|
|
|
|
|
|
export async function setLang(lang){
|
|
|
|
setCookie("lang", lang);
|
|
|
|
await loadLangs();
|
|
|
|
}
|