Skip to content

Commit

Permalink
Merge pull request #253 from jairo-bc/STRF-9379
Browse files Browse the repository at this point in the history
STRF-9379 Revert messageformat to pre-GraalVM condition
  • Loading branch information
jairo-bc authored Oct 4, 2021
2 parents 372be6f + d5f4f86 commit 6fde818
Show file tree
Hide file tree
Showing 6 changed files with 25 additions and 196 deletions.
14 changes: 2 additions & 12 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -182,12 +182,11 @@ class Paper {
* Load translation files and give a translator to renderer.
*
* @param {String} acceptLanguage The accept-language header, used to select a locale
* @param {Boolean} omitTransforming If set to true, translations won't be transformted(flattened) and used as provided
* @return {Promise} Promise to load the translations into the renderer.
*/
loadTranslations(acceptLanguage, omitTransforming = false) {
loadTranslations(acceptLanguage) {
return this._assembler.getTranslations().then(translations => {
const translator = Translator.create(acceptLanguage, translations, this.logger, omitTransforming);
const translator = Translator.create(acceptLanguage, translations, this.logger);
this.renderer.setTranslator(translator);
return translations;
});
Expand Down Expand Up @@ -289,15 +288,6 @@ class Paper {
addTemplates(templates) {
this.renderer.addTemplates(templates);
}

/**
* Precompiles translations to string representations of translation function source code
*
* @param {Object} translations transformed translations object
*/
precompileTranslations(translations) {
return Translator.precompileTranslations(translations);
}
}

module.exports = Paper;
56 changes: 4 additions & 52 deletions lib/translator/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@
* @module paper/lib/translator
*/

const MessageFormat = require('@messageformat/core');
const { plural } = require('@messageformat/runtime');
const MessageFormat = require('messageformat');
const Filter = require('./filter');
const LocaleParser = require('./locale-parser');
const Transformer = require('./transformer');
Expand Down Expand Up @@ -57,36 +56,12 @@ function Translator(acceptLanguage, allTranslations, logger = console, omitTrans
* @param {string} acceptLanguage
* @param {Object} allTranslations
* @param {Object} logger
* @param {Boolean} omitTransforming
* @returns {Translator}
*/
Translator.create = function (acceptLanguage, allTranslations, logger = console, omitTransforming = false) {
return new Translator(acceptLanguage, allTranslations, logger, omitTransforming);
Translator.create = function (acceptLanguage, allTranslations, logger = console) {
return new Translator(acceptLanguage, allTranslations, logger);
};

/**
* Precompile translation functions
* @param {Object} translations
* @returns {Object}
*/
Translator.precompileTranslations = function (translations) {
const compiled = {};

Object.keys(translations).forEach(language => {
compiled[language] = {}
Object.keys(translations[language]).forEach(categoryKey => {
compiled[language][categoryKey] = translations[language][categoryKey];
if (categoryKey === 'translations') {
compiled[language].compiledTranslations = {};
Object.keys(translations[language][categoryKey]).forEach(key => {
compiled[language].compiledTranslations[key] = Translator.compileFormatterFunction(translations[language], key);
})
}
});
});

return compiled;
}

/**
* Precompile translation functions
Expand All @@ -112,23 +87,6 @@ Translator.compileFormatterFunction = function (language, key) {
}
}

Translator.prototype.areFormatterFunctionsGlobal = function() {
if (typeof global === "undefined") {
return true;
}

return global.plural;
}

Translator.prototype.enableFormatterFunctionsGlobalScope = function() {
global.plural = plural;
};

Translator.prototype.checkFormatterFunctionsAvailability = function() {
if (!this.areFormatterFunctionsGlobal()) {
this.enableFormatterFunctionsGlobalScope();
}
};

/**
* Get translated string
Expand All @@ -142,17 +100,11 @@ Translator.prototype.translate = function (key, parameters) {
return key;
}

if (!this.omitTransforming && typeof this._formatFunctions[key] === 'undefined') {
if (typeof this._formatFunctions[key] === 'undefined') {
this._formatFunctions[key] = this._compileTemplate(key);
}

try {
if (this.omitTransforming) {
this.checkFormatterFunctionsAvailability();
const fn = new Function(`return ${language.compiledTranslations[key]}`)()
return fn(parameters);
}

return this._formatFunctions[key](parameters);
} catch (err) {
this.logger.error(err);
Expand Down
12 changes: 6 additions & 6 deletions lib/translator/locale-parser.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
* @module paper/lib/translator/locale-parser
*/
const AcceptLanguageParser = require('accept-language-parser');
const MessageFormat = require('@messageformat/core');
const MessageFormat = require('messageformat');

/**
* Get preferred locale
Expand All @@ -15,13 +15,13 @@ const MessageFormat = require('@messageformat/core');
*/
function getPreferredLocale(acceptLanguage, languages, defaultLocale) {
const locale = getLocales(acceptLanguage).find(locale => languages[locale]) || defaultLocale;
const mf = new MessageFormat(locale);
const options = mf.resolvedOptions();
if (options.locale === MessageFormat.defaultLocale) {
try {
new MessageFormat(locale);

return locale;
} catch (err) {
return defaultLocale;
}

return locale;
}

/**
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@
"homepage": "https://github.com/bigcommerce/paper",
"dependencies": {
"@bigcommerce/stencil-paper-handlebars": "4.4.9",
"@messageformat/core": "^3.0.0",
"accept-language-parser": "~1.4.1"
"accept-language-parser": "~1.4.1",
"messageformat": "~0.2.2"
},
"devDependencies": {
"code": "~4.0.0",
Expand Down
28 changes: 0 additions & 28 deletions spec/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -187,32 +187,4 @@ describe('loadTranslations', () => {
done();
});
});

it('should load translations and omit trasnformation', done => {
const assembler = {
getTemplates: () => Promise.resolve({}),
getTranslations: () => {
return Promise.resolve({
en: {
locale: 'en',
locales: {
'hello': 'en',
'level1.level2': 'en'
},
translations: {
hello: 'Hello {name}',
'level1.level2': 'we are in the second level'
}
}
});
}
};
const paper = new Paper(null, null, assembler);
paper.loadTranslations('en', true).then(() => {
expect(paper.renderer.getTranslator().getLanguage().locales).to.equal({ hello: 'en', 'level1.level2': 'en' });
done();
}).catch(e => {
console.log(e);
});
})
});
107 changes: 11 additions & 96 deletions spec/lib/translator.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ const Code = require('code');
const Lab = require('lab');
const Sinon = require('sinon');
const Translator = require('../../lib/translator');
const Transformer = require('../../lib/translator/transformer');

const lab = exports.lab = Lab.script();
const beforeEach = lab.beforeEach;
Expand Down Expand Up @@ -269,56 +268,19 @@ describe('Translator', () => {
done();
});

describe('translations flattening', () => {
const flattenedLanguages = {
"en": {
"locale": "en",
"locales": {
"welcome": "en",
"hello": "en",
"bye": "en",
"items": "en",
"level1.level2": "en"
},
"translations": {
"welcome": "Welcome",
"hello": "Hello {name}",
"bye": "Bye bye",
"items": "{count, plural, one{1 Item} other{# Items}}",
"level1.level2": "we are on the second level"
}
}
it('should translate with single quotes left', done => {
translations = {
en: {
search: "{ count, plural, one {# product result} other {# product results} } for '{search_query}'",
},
};
const translator = Translator.create('en', translations);
const result = translator.translate('search', { search_query: 'basket', count: 0});
expect(result).to.equal("0 product results for 'basket'");
done();
})

it('should provide flattened translations object', done => {
const flattenedTranslator = Translator.create('en', flattenedLanguages, console, true);
const translator = Translator.create('en', translations);
expect(flattenedTranslator.getLanguage('en')).to.equal(translator.getLanguage('en'));

done();
});

it('should omit transforming languages, when flattened languages are provided', done => {
const stub = Sinon.stub(Transformer, 'transform');
Translator.create('en', flattenedLanguages, console, true);
expect(stub.called).to.equal(false);
stub.restore();

done();
});

it('should successfully translate en language without transforming translations', done => {
const locale = 'en';
const translator = Translator.create(locale, flattenedLanguages, console, true);
const precompiledTranslations = Translator.precompileTranslations(flattenedLanguages);
translator.setLanguage(precompiledTranslations)
expect(translator.translate('hello', {name: 'User'})).to.equal('Hello User');

const key = 'level1.level2';
expect(translator.translate(key)).to.equal(flattenedLanguages[locale].translations[key]);
done();
});

describe('translations flattening', () => {
it('should successfully translate fr language with transforming translations', done => {
const locale = 'fr-CA';
const translator = Translator.create(locale, translations);
Expand All @@ -328,53 +290,6 @@ describe('Translator', () => {
expect(translator.translate(key)).to.equal(translations.fr.level1.level2);
done();
})

it('should not throw an error on compiling translation (zero key is invalid for locale=en', done => {
const flattenedLanguages = {
"en": {
"locale": "en",
"locales": {
"items": "en",
},
"translations": {
"items": "{count, plural, zero{No results} one{# result} other{# results}} found for {term}",
}
}
};
const locale = 'en';
const translator = Translator.create(locale, flattenedLanguages, console, true);
const precompiledTranslations = Translator.precompileTranslations(flattenedLanguages);
translator.setLanguage(precompiledTranslations)
const result = translator.translate('items', {count: 0, term: 'product'});
expect(result).to.equal('{count, plural, zero{No results} one{# result} other{# results}} found for {term}');

done();
})

it('should log error and return key', done => {
const flattenedValue = "Calificado {rating, plural, one {# Star} otro {# Stars}} O Mas";
const flattenedLanguages = {
"es": {
"locale": "es",
"locales": {
"items": "es",
},
"translations": {
"items": flattenedValue,
}
}
};
const locale = 'es';
const translator = Translator.create(locale, flattenedLanguages, console, true);
const precompiledTranslations = Translator.precompileTranslations(flattenedLanguages);
translator.setLanguage(precompiledTranslations)
const result = translator.translate('items', {rating: 10});

expect(result).to.equal(flattenedValue);

done();

});
})

});

0 comments on commit 6fde818

Please sign in to comment.