Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,19 @@ describe('inline constants', () => {
});
});

it('inlines Platform.select in the code to ios and mac if both are present and running on ios platform', () => {
const code = `
function a() {
var a = Platform.select({ios: 1, android: 2, mac: 3});
}
`;

compare([inlinePlugin], code, code.replace(' android: 2,', ''), {
inlinePlatform: 'true',
platform: 'ios',
});
});

it('does not inline Platform.select in the code when some of the properties are dynamic', () => {
const code = `
function a() {
Expand Down Expand Up @@ -337,6 +350,32 @@ describe('inline constants', () => {
});
});

it('does not inline Platform.select if the current platform is ios, and ios and mac are in the properties', () => {
const code = `
function a() {
var a = Platform.select({ios: 1, mac: 2});
}
`;

compare([inlinePlugin], code, code, {
inlinePlatform: true,
platform: 'ios',
});
});

it('does not inline Platform.select if the current platform is ios and mac is in the properties, but ios is not', () => {
const code = `
function a() {
var a = Platform.select({mac: 1, default: 2});
}
`;

compare([inlinePlugin], code, code, {
inlinePlatform: true,
platform: 'ios',
});
});

it('replaces Platform.select in the code if Platform is a top level import', () => {
const code = `
var Platform = require('Platform');
Expand Down
32 changes: 31 additions & 1 deletion packages/metro/src/JSTransformer/worker/inline-plugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,27 @@ function inlinePlugin(
});
}

function hasMacProperty(objectExpression): boolean {
return findProperty(objectExpression, 'mac', () => false);
}

function hasIOSProperty(objectExpression): boolean {
return findProperty(objectExpression, 'ios', () => false);
}

function removePlatformsOutsideOfIOSAndMac(objectExpression): boolean {
return objectExpression.properties.filter(p => {
if (
t.isIdentifier(p.key) &&
(p.key.name === 'ios' || p.key.name === 'mac')
) {
return true;
}

return false;
});
}

return {
visitor: {
Identifier(path: Path, state: State): void {
Expand Down Expand Up @@ -144,7 +165,16 @@ function inlinePlugin(
findProperty(arg, 'default', () => t.identifier('undefined')),
);

path.replaceWith(findProperty(arg, opts.platform, fallback));
if (opts.platform === 'ios' && hasMacProperty(arg)) {
if (hasIOSProperty(arg)) {
node.arguments[0] = t.objectExpression(
removePlatformsOutsideOfIOSAndMac(arg),
);
path.replaceWith(node);
}
} else {
path.replaceWith(findProperty(arg, opts.platform, fallback));
}
}
}
},
Expand Down