react/vendor/fbtransform/transforms/reactDisplayName.js

94 lines
2.6 KiB
JavaScript
Raw Normal View History

2013-05-30 03:46:11 +08:00
/**
2014-10-09 08:27:59 +08:00
* Copyright 2013-2014, Facebook, Inc.
* All rights reserved.
2013-05-30 03:46:11 +08:00
*
2014-10-09 08:27:59 +08:00
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
2013-05-30 03:46:11 +08:00
*/
/*global exports:true*/
"use strict";
var Syntax = require('jstransform').Syntax;
2013-11-09 08:08:48 +08:00
var utils = require('jstransform/src/utils');
2013-05-30 03:46:11 +08:00
2014-01-04 08:25:50 +08:00
function addDisplayName(displayName, object, state) {
if (object &&
object.type === Syntax.CallExpression &&
object.callee.type === Syntax.MemberExpression &&
object.callee.object.type === Syntax.Identifier &&
object.callee.object.name === 'React' &&
object.callee.property.type === Syntax.Identifier &&
object.callee.property.name === 'createClass' &&
object['arguments'].length === 1 &&
object['arguments'][0].type === Syntax.ObjectExpression) {
// Verify that the displayName property isn't already set
var properties = object['arguments'][0].properties;
var safe = properties.every(function(property) {
var value = property.key.type === Syntax.Identifier ?
property.key.name :
property.key.value;
return value !== 'displayName';
});
if (safe) {
utils.catchup(object['arguments'][0].range[0] + 1, state);
utils.append('displayName: "' + displayName + '",', state);
2014-01-04 08:25:50 +08:00
}
}
}
2013-05-30 03:46:11 +08:00
/**
* Transforms the following:
*
* var MyComponent = React.createClass({
* render: ...
* });
*
* into:
*
* var MyComponent = React.createClass({
* displayName: 'MyComponent',
* render: ...
* });
2014-01-04 08:25:50 +08:00
*
* Also catches:
*
* MyComponent = React.createClass(...);
* exports.MyComponent = React.createClass(...);
* module.exports = {MyComponent: React.createClass(...)};
2013-05-30 03:46:11 +08:00
*/
function visitReactDisplayName(traverse, object, path, state) {
2014-01-04 08:25:50 +08:00
var left, right;
if (object.type === Syntax.AssignmentExpression) {
left = object.left;
right = object.right;
} else if (object.type === Syntax.Property) {
left = object.key;
right = object.value;
} else if (object.type === Syntax.VariableDeclarator) {
left = object.id;
right = object.init;
}
if (left && left.type === Syntax.MemberExpression) {
left = left.property;
}
if (left && left.type === Syntax.Identifier) {
addDisplayName(left.name, right, state);
}
}
visitReactDisplayName.test = function(object, path, state) {
return (
object.type === Syntax.AssignmentExpression ||
object.type === Syntax.Property ||
object.type === Syntax.VariableDeclarator
);
2013-05-30 03:46:11 +08:00
};
2014-02-16 04:13:01 +08:00
exports.visitorList = [
visitReactDisplayName
];