Clyde/frontend/src/i18n.js
Anthony Debucquoy e69ece23d0
All checks were successful
Build and test backend / Build-backend (push) Successful in 2m9s
Build and test backend / Test-backend (push) Successful in 1m19s
deploy to production / deploy-frontend (push) Successful in 21s
deploy to production / deploy-backend (push) Successful in 2m20s
Build and test FrontEnd / Build-frontend (push) Successful in 21s
adding set cookie and set lang (#68)
simple set cookie (je deteste javascript) et un setlang pour le syntastic sugar

Reviewed-on: #68
Reviewed-by: Maxime <231026@umons.ac.be>
Reviewed-by: Wal <karpinskiwal@gmail.com>
Co-authored-by: Anthony Debucquoy <debucquoy.anthony@gmail.com>
Co-committed-by: Anthony Debucquoy <debucquoy.anthony@gmail.com>
2024-03-08 11:23:32 +01:00

65 lines
1.7 KiB
JavaScript

/**
* 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
*
*/
import { getCookie, setCookie } from './utils.js';
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
*/
export default function i18n(key, options) {
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
*/
export async function loadLangs(lang){
lang = lang != null ? lang : getCookie("lang");
lang = lang != "" ? lang : default_lang;
const filename = "/i18n/" + lang.toUpperCase() + ".txt";
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);
};
}
langs = filteredLines;
}
await loadLangs();
export async function setLang(lang){
setCookie("lang", lang);
await loadLangs();
}