Crawl up ancestry looking for possible candidates to infer displayName from rather than just checking the direct parent

This commit is contained in:
Sebastian McKenzie 2015-12-27 21:48:28 +00:00
parent 5ca1cf0506
commit 05896b834b
11 changed files with 55 additions and 17 deletions

View File

@ -53,26 +53,40 @@ export default function ({ types: t }) {
} }
}, },
"AssignmentExpression|ObjectProperty|VariableDeclarator"({ node }) { CallExpression(path) {
let left, right; let { node } = path;
if (!isCreateClass(node)) return;
if (t.isAssignmentExpression(node)) { let id;
left = node.left;
right = node.right; // crawl up the ancestry looking for possible candidates for displayName inference
} else if (t.isObjectProperty(node)) { path.find(function (path) {
left = node.key; if (path.isAssignmentExpression()) {
right = node.value; id = path.node.left;
} else if (t.isVariableDeclarator(node)) { } else if (path.isObjectProperty()) {
left = node.id; id = path.node.key;
right = node.init; } else if (path.isVariableDeclarator()) {
id = path.node.id;
} else if (path.isStatement()) {
// we've hit a statement, we should stop crawling up
return true;
} }
if (t.isMemberExpression(left)) { // we've got an id! no need to continue
left = left.property; if (id) return true;
});
// ensure that we have an identifier we can inherit from
if (!id) return;
// foo.bar -> bar
if (t.isMemberExpression(id)) {
id = id.property;
} }
if (t.isIdentifier(left) && isCreateClass(right)) { // identifiers are the only thing we can reliably get a name from
addDisplayName(left.name, right); if (t.isIdentifier(id)) {
addDisplayName(id.name, node);
} }
} }
} }

View File

@ -0,0 +1 @@
foo = React.createClass({});

View File

@ -0,0 +1,3 @@
foo = React.createClass({
displayName: "foo"
});

View File

@ -0,0 +1 @@
var foo = bar(React.createClass({}));

View File

@ -0,0 +1,3 @@
var foo = bar(React.createClass({
displayName: "foo"
}));

View File

@ -0,0 +1,3 @@
({
foo: React.createClass({})
});

View File

@ -0,0 +1,5 @@
({
foo: React.createClass({
displayName: "foo"
})
});

View File

@ -0,0 +1,3 @@
{
"plugins": ["transform-react-display-name"]
}

View File

@ -0,0 +1 @@
var foo = React.createClass({});

View File

@ -0,0 +1,3 @@
var foo = React.createClass({
displayName: "foo"
});

View File

@ -0,0 +1 @@
require("babel-helper-plugin-test-runner")(__dirname);