an-anime-game-launcher/src/ts/lib/i18n.ts

47 lines
1.2 KiB
TypeScript
Raw Normal View History

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
{
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;
}
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
}
}