feat: compile messages

This commit is contained in:
Nybkox
2025-02-27 13:35:40 +01:00
parent 82eabc41fe
commit 138fadf672
3 changed files with 83 additions and 8 deletions

View File

@@ -1,16 +1,23 @@
import enUS from '../../../translations/en-US.json';
import csCZ from '../../../translations/cs-CZ.json';
import MessageFormat, { MessageFunction } from '@messageformat/core';
import { getStringSettingsValue } from './settings/settingsTools';
const translations = {
'en-US': enUS,
'cs-CZ': csCZ,
};
const supportedLanguages = Object.keys(translations);
const compiledMessages: Partial<Record<string, Record<string, MessageFunction<'string'>>>> = {};
export function getSelectedLanguage(): string {
const borwserLanguage = getBrowserLanguage();
const selectedLanguage = getStringSettingsValue('localization.language', borwserLanguage);
if (!supportedLanguages.includes(selectedLanguage)) return 'en-US';
return selectedLanguage;
}
@@ -26,18 +33,34 @@ type TranslateOptions = {
values?: Record<string, unknown>;
};
export function _t(key: string, options: TranslateOptions): string {
const { defaultMessage } = options;
const selectedLanguage = getSelectedLanguage();
const selectedTranslations = translations[selectedLanguage] ?? enUS;
function getTranslation(key: string, defaultMessage: string, language: string) {
const selectedTranslations = translations[language] ?? enUS;
const translation = selectedTranslations[key];
if (!translation) {
console.warn(`Translation not found for key: ${key}. For language: ${selectedLanguage}`);
console.warn(`Translation not found for key: ${key}. For language: ${language}`);
return defaultMessage;
}
return translation;
}
export function _t(key: string, options: TranslateOptions): string {
const { defaultMessage, values } = options;
const selectedLanguage = getSelectedLanguage();
if (!compiledMessages[selectedLanguage]) {
compiledMessages[selectedLanguage] = {};
}
if (!compiledMessages[selectedLanguage][key]) {
const translation = getTranslation(key, defaultMessage, selectedLanguage);
const complied = new MessageFormat(selectedLanguage).compile(translation);
compiledMessages[selectedLanguage][key] = complied;
}
const compliledTranslation = compiledMessages[selectedLanguage][key];
return compliledTranslation(values ?? {});
}