Do not transform Platform.select() calls using dynamic properties

Reviewed By: davidaurelio

Differential Revision: D7085775

fbshipit-source-id: 348e43312ecb8298c14b202f209850b54d9b7b12
This commit is contained in:
Rafael Oleza 2018-02-28 04:06:30 -08:00 committed by Facebook Github Bot
parent 36cee35684
commit f5bb45ffdd
2 changed files with 45 additions and 6 deletions

View File

@ -231,6 +231,32 @@ describe('inline constants', () => {
);
});
it('does not inline Platform.select in the code when some of the properties are dynamic', () => {
const code = `function a() {
const COMPUTED_IOS = 'ios';
const COMPUTED_ANDROID = 'android';
var a = Platform.select({[COMPUTED_ANDROID]: 1, [COMPUTED_IOS]: 2, default: 3});
}`;
const {ast} = inline('arbitrary.js', {code}, {platform: 'android'});
expect(toString(ast)).toEqual(normalize(code));
});
it('does not inline Platform.select when all properties are dynamic', () => {
const code = `function a() {
var a = Platform.select({[COMPUTED_ANDROID]: 1, [COMPUTED_IOS]: 2});
}`;
const {ast} = inline('arbitrary.js', {code}, {platform: 'android'});
expect(toString(ast)).toEqual(normalize(code));
});
it('does not inline Platform.select if it receives a non-object', () => {
const code = `function a() {
var a = Platform.select(foo);
}`;
const {ast} = inline('arbitrary.js', {code}, {platform: 'android'});
expect(toString(ast)).toEqual(normalize(code));
});
it('replaces Platform.select in the code if Platform is a top level import', () => {
const code = `
var Platform = require('Platform');

View File

@ -70,6 +70,20 @@ function inlinePlugin(context: Context) {
return property ? property.value : fallback();
}
function hasStaticProperties(objectExpression) {
if (!t.isObjectExpression(objectExpression)) {
return false;
}
return objectExpression.properties.every(p => {
if (p.computed) {
return false;
}
return t.isIdentifier(p.key) || t.isStringLiteral(p.key);
});
}
return {
visitor: {
Identifier(path: Object, state: Object) {
@ -99,13 +113,12 @@ function inlinePlugin(context: Context) {
const opts = state.opts;
if (isPlatformSelectNode(node, scope, opts.isWrapped)) {
const fallback = () =>
findProperty(arg, 'default', () => t.identifier('undefined'));
const replacement = t.isObjectExpression(arg)
? findProperty(arg, opts.platform, fallback)
: node;
if (hasStaticProperties(arg)) {
const fallback = () =>
findProperty(arg, 'default', () => t.identifier('undefined'));
path.replaceWith(replacement);
path.replaceWith(findProperty(arg, opts.platform, fallback));
}
} else if (isPlatformOSSelect(node, scope, opts.isWrapped)) {
path.replaceWith(
getReplacementForPlatformOSSelect(node, opts.platform),