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

61 lines
1.5 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');
import { constants } from './constants';
2021-10-23 23:44:24 +03:00
export class i18n
{
public static readonly localesDir = path.join(path.dirname(__dirname), '..', 'locales');
public static loadedLanguage: any;
public static translate (phrase: string): string
{
if (i18n.loadedLanguage === undefined)
this.setLang(navigator.language);
let translation = i18n.loadedLanguage[phrase] ?? phrase;
let item;
while ((item = /\{([a-zA-Z\.]+)\}/g.exec(translation)) !== null)
{
2021-11-03 23:10:37 +03:00
let value: any = constants;
item[1].split('.').forEach(ref => value = value[ref]);
2021-10-23 23:44:24 +03:00
translation = translation.replace(item[0], value);
}
2021-10-23 23:44:24 +03:00
return translation;
}
2021-10-23 02:53:33 +03:00
public static setLang (lang: string)
{
lang = lang.toLowerCase();
2021-10-23 02:53:33 +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
if (samecode.test(lang))
lang = lang.replace(/-.*$/, '');
2021-10-23 02:53:33 +03:00
switch (lang)
{
case 'ja-jp':
lang = 'ja';
2021-10-23 16:37:15 +03:00
break;
2021-10-23 23:44:24 +03:00
case 'vi-vn':
lang = 'vi';
2021-10-23 23:44:24 +03:00
break;
}
2021-10-23 23:44:24 +03:00
i18n.loadedLanguage = JSON.parse(fs.readFileSync(path.join(this.localesDir,
fs.existsSync(path.join(this.localesDir, lang + '.json')) ?
lang + '.json' : 'en.json'
)));
}
2021-10-23 16:37:15 +03:00
}