Skip to content
Open
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 @@ -308,6 +308,36 @@ describe('unsafe positions', () => {
expect(output).toContain('delete Platform.OS');
});

test('does not replace a target nested in an assignment pattern', () => {
expectUnchanged(`
import {Platform} from 'react-native';
[Platform.OS] = values;
({os: Platform.OS} = value);
`);
});

test('replaces reads nested inside an assignment target', () => {
const output = transform(`
import {Platform} from 'react-native';
target[Platform.OS] = value;
[target[Platform.OS]] = values;
({[Platform.OS]: target} = value);
`);

expect(output).not.toContain('Platform.OS');
expect(output.match(/"ios"/g)).toHaveLength(3);
});

test('does not replace for-in or for-of assignment targets', () => {
expectUnchanged(`
import {Platform} from 'react-native';
for (Platform.OS in object) {}
for ([Platform.OS] in nestedObject) {}
for (Platform.OS of values) {}
for ([Platform.OS] of nestedValues) {}
`);
});

test('does not inline computed access', () => {
const output = transform(`
import {Platform} from 'react-native';
Expand Down
45 changes: 36 additions & 9 deletions packages/react-native-babel-preset/src/inline-platform-plugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -395,15 +395,42 @@ module.exports = function inlinePlatformPlugin(
function isWriteTarget(
path /*: NodePath<MemberExpression> */,
) /*: boolean */ {
const {parent, node} = path;
if (parent.type === 'AssignmentExpression' && parent.left === node) {
return true;
}
if (parent.type === 'UpdateExpression' && parent.argument === node) {
return true;
}
if (parent.type === 'UnaryExpression' && parent.operator === 'delete') {
return true;
let child /*: Node */ = path.node;
let parentPath = path.parentPath;

while (parentPath != null) {
const parent = parentPath.node;
if (
(parent.type === 'AssignmentExpression' ||
parent.type === 'ForInStatement' ||
parent.type === 'ForOfStatement') &&
parent.left === child
) {
return true;
}
if (parent.type === 'UpdateExpression' && parent.argument === child) {
return true;
}
if (
parent.type === 'UnaryExpression' &&
parent.operator === 'delete' &&
parent.argument === child
) {
return true;
}

const nestedWriteTarget =
parent.type === 'ArrayPattern' ||
parent.type === 'ObjectPattern' ||
(parent.type === 'ObjectProperty' && parent.value === child) ||
(parent.type === 'RestElement' && parent.argument === child) ||
(parent.type === 'AssignmentPattern' && parent.left === child);
if (!nestedWriteTarget) {
return false;
}

child = parent;
parentPath = parentPath.parentPath;
}
return false;
}
Expand Down
Loading