2021-10-23 23:44:24 +03:00
|
|
|
const path = require('path');
|
2021-10-23 02:53:33 +03:00
|
|
|
const fs = require('fs');
|
|
|
|
|
2021-10-23 23:44:24 +03:00
|
|
|
export class i18n
|
|
|
|
{
|
2021-10-24 10:19:20 +03:00
|
|
|
public static readonly localesDir = path.join(path.dirname(__dirname), '..', 'locales');
|
|
|
|
|
2021-10-23 23:44:24 +03:00
|
|
|
public static loadedLanguage: any;
|
|
|
|
|
|
|
|
public static translate (phrase: string)
|
|
|
|
{
|
|
|
|
if (i18n.loadedLanguage === undefined)
|
|
|
|
this.setLang(navigator.language);
|
|
|
|
|
|
|
|
return i18n.loadedLanguage[phrase] ?? phrase;
|
2021-10-23 16:37:15 +03:00
|
|
|
}
|
2021-10-23 02:53:33 +03:00
|
|
|
|
2021-10-23 23:44:24 +03:00
|
|
|
public static setLang (lang: string)
|
|
|
|
{
|
|
|
|
lang = lang.toLowerCase();
|
2021-10-23 02:53:33 +03:00
|
|
|
|
2021-10-23 23:44:24 +03:00
|
|
|
// Test if the locale is the same string so if it's de-de or id-id remove -de or -id like navigator.language does.
|
|
|
|
let samecode = new RegExp(`(${lang.replace(/-.*$/, '')}.*){2}`, 'g');
|
2021-10-23 02:53:33 +03:00
|
|
|
|
2021-10-24 00:07:02 +03:00
|
|
|
if (samecode.test(lang))
|
2021-10-23 23:44:24 +03:00
|
|
|
lang = lang.replace(/-.*$/, '');
|
2021-10-23 02:53:33 +03:00
|
|
|
|
2021-10-23 23:44:24 +03:00
|
|
|
switch (lang)
|
|
|
|
{
|
|
|
|
case 'ja-jp':
|
|
|
|
lang = 'ja';
|
2021-10-23 16:37:15 +03:00
|
|
|
|
2021-10-23 23:44:24 +03:00
|
|
|
break;
|
|
|
|
|
|
|
|
case 'vi-vn':
|
|
|
|
lang = 'vi';
|
|
|
|
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
2021-10-24 10:19:20 +03:00
|
|
|
i18n.loadedLanguage = JSON.parse(fs.readFileSync(path.join(this.localesDir,
|
|
|
|
fs.existsSync(path.join(this.localesDir, lang + '.json')) ?
|
2021-10-23 23:44:24 +03:00
|
|
|
lang + '.json' : 'en.json'
|
|
|
|
)));
|
2021-10-23 16:37:15 +03:00
|
|
|
}
|
|
|
|
}
|