bitwarden-estensione-browser/src/services/i18n.service.ts

65 lines
1.9 KiB
TypeScript
Raw Normal View History

2018-01-24 21:22:13 +01:00
import * as path from 'path';
2018-01-24 20:59:03 +01:00
// First locale is the default (English)
const SupportedLocales = [
'en', 'es',
];
export class I18nService {
defaultMessages: any = {};
localeMessages: any = {};
language: string;
inited: boolean;
2018-01-24 22:02:18 +01:00
constructor(private systemLanguage: string, private localesDirectory: string) {
2018-01-24 20:59:03 +01:00
}
async init(language?: string) {
if (this.inited) {
throw new Error('i18n already initialized.');
}
this.inited = true;
this.language = language != null ? language : this.systemLanguage;
if (SupportedLocales.indexOf(this.language) === -1) {
this.language = this.language.slice(0, 2);
if (SupportedLocales.indexOf(this.language) === -1) {
this.language = SupportedLocales[0];
}
}
await this.loadMessages(this.language, this.localeMessages);
if (this.language !== SupportedLocales[0]) {
await this.loadMessages(SupportedLocales[0], this.defaultMessages);
}
}
t(id: string): string {
2018-01-24 22:02:18 +01:00
return this.translate(id);
2018-01-24 20:59:03 +01:00
}
2018-01-24 22:02:18 +01:00
translate(id: string): string {
2018-01-24 20:59:03 +01:00
if (this.localeMessages.hasOwnProperty(id) && this.localeMessages[id]) {
return this.localeMessages[id];
} else if (this.defaultMessages.hasOwnProperty(id) && this.defaultMessages[id]) {
return this.defaultMessages[id];
}
return '';
}
2018-01-24 21:22:13 +01:00
private loadMessages(locale: string, messagesObj: any): Promise<any> {
2018-01-24 20:59:03 +01:00
const formattedLocale = locale.replace('-', '_');
2018-01-24 21:22:13 +01:00
const filePath = path.join(__dirname, this.localesDirectory + '/' + formattedLocale + '/messages.json');
const locales = (window as any).require(filePath);
2018-01-24 20:59:03 +01:00
for (const prop in locales) {
if (locales.hasOwnProperty(prop)) {
messagesObj[prop] = locales[prop].message;
}
}
2018-01-24 21:22:13 +01:00
return Promise.resolve();
2018-01-24 20:59:03 +01:00
}
}