RenaiApp/src/main/modules/translation/t.ts

51 lines
1.4 KiB
TypeScript

// same as in renderer
import { IntlMessageFormat } from 'intl-messageformat';
import * as en from '../../../shared/translation/en.json';
const localeData = {
[Locale.EN]: en as TranslationData,
};
function getDeep(deepKey: string, data: TranslationData): string {
const keyChain = deepKey.split('.');
if (!keyChain.length) {
return deepKey;
}
let index = 0;
let curr: TranslationData | string = data;
do {
const key = keyChain[index];
curr = curr[key];
index++;
} while (typeof curr !== 'string' && index < keyChain.length);
if (typeof curr === 'string') {
return curr;
}
return deepKey;
}
const intlMessageFormatCache: Record<Locale, Record<string, IntlMessageFormat>> = {
[Locale.EN]: {},
};
/**
* translates a message
*
* @param key - a deep key of the format "labels.actions.save"
* @param values - arguments for the message
* @param locale - see {@link Locale} for implemented locales
*/
export function t(key: string, values?: Record<string, string | number | boolean>, locale: Locale = Locale.EN): string {
if (!intlMessageFormatCache[locale][key]) {
const message = getDeep(key, localeData[locale]);
intlMessageFormatCache[locale][key] = new IntlMessageFormat(message, locale);
}
const intlMessageFormat = intlMessageFormatCache[locale][key];
const formatted = intlMessageFormat.format(values);
if (typeof formatted === 'string') {
return formatted;
}
return key;
}