Fix language auto-detection

This commit is contained in:
Denis Perov 2022-04-21 19:41:56 +03:00
parent 566527dfad
commit 8f43b74bbc
3 changed files with 17 additions and 3 deletions

View file

@ -16,6 +16,15 @@ Meteor.startup(() => {
navigator.userLanguage,
].filter(Boolean);
if (language) {
TAPi18n.setLanguage(language);
// Try with potentially complex language tag
if (TAPi18n.isLanguageSupported(language)) {
TAPi18n.setLanguage(language);
} else if (language.includes('-')) {
// Fallback to a general language
const [general] = language.split('-');
if (TAPi18n.isLanguageSupported(general)) {
TAPi18n.setLanguage(general);
}
}
}
});

View file

@ -78,8 +78,8 @@ describe('TAPi18n', () => {
expect(TAPi18n.i18n.addResourceBundle.firstCall.args[2]).to.have.property('accept');
});
it('does nothing if language is missing', async () => {
await expect(TAPi18n.loadLanguage('miss')).to.be.fulfilled;
it('throws error if language is missing', async () => {
await expect(TAPi18n.loadLanguage('miss')).to.be.rejectedWith('not supported');
expect(TAPi18n.i18n.addResourceBundle).to.not.be.called;
});

View file

@ -32,6 +32,9 @@ export const TAPi18n = {
// Load the current language data
await TAPi18n.loadLanguage(DEFAULT_LANGUAGE);
},
isLanguageSupported(language) {
return Object.values(languages).some(({ tag }) => tag === language);
},
getSupportedLanguages() {
return Object.values(languages).map(({ name, code, tag }) => ({ name, code, tag }));
},
@ -42,6 +45,8 @@ export const TAPi18n = {
if (language in languages && 'load' in languages[language]) {
const data = await languages[language].load();
this.i18n.addResourceBundle(language, DEFAULT_NAMESPACE, data);
} else {
throw new Error(`Language ${language} is not supported`);
}
},
async setLanguage(language) {