Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
81158 views
1
/**
2
* Copyright 2013-2014, Facebook, Inc.
3
* All rights reserved.
4
*
5
* This source code is licensed under the BSD-style license found in the
6
* LICENSE file in the root directory of this source tree. An additional grant
7
* of patent rights can be found in the PATENTS file in the same directory.
8
*/
9
/*global exports:true*/
10
"use strict";
11
12
var Syntax = require('jstransform').Syntax;
13
var utils = require('jstransform/src/utils');
14
15
function addDisplayName(displayName, object, state) {
16
if (object &&
17
object.type === Syntax.CallExpression &&
18
object.callee.type === Syntax.MemberExpression &&
19
object.callee.object.type === Syntax.Identifier &&
20
object.callee.object.name === 'React' &&
21
object.callee.property.type === Syntax.Identifier &&
22
object.callee.property.name === 'createClass' &&
23
object['arguments'].length === 1 &&
24
object['arguments'][0].type === Syntax.ObjectExpression) {
25
// Verify that the displayName property isn't already set
26
var properties = object['arguments'][0].properties;
27
var safe = properties.every(function(property) {
28
var value = property.key.type === Syntax.Identifier ?
29
property.key.name :
30
property.key.value;
31
return value !== 'displayName';
32
});
33
34
if (safe) {
35
utils.catchup(object['arguments'][0].range[0] + 1, state);
36
utils.append('displayName: "' + displayName + '",', state);
37
}
38
}
39
}
40
41
/**
42
* Transforms the following:
43
*
44
* var MyComponent = React.createClass({
45
* render: ...
46
* });
47
*
48
* into:
49
*
50
* var MyComponent = React.createClass({
51
* displayName: 'MyComponent',
52
* render: ...
53
* });
54
*
55
* Also catches:
56
*
57
* MyComponent = React.createClass(...);
58
* exports.MyComponent = React.createClass(...);
59
* module.exports = {MyComponent: React.createClass(...)};
60
*/
61
function visitReactDisplayName(traverse, object, path, state) {
62
var left, right;
63
64
if (object.type === Syntax.AssignmentExpression) {
65
left = object.left;
66
right = object.right;
67
} else if (object.type === Syntax.Property) {
68
left = object.key;
69
right = object.value;
70
} else if (object.type === Syntax.VariableDeclarator) {
71
left = object.id;
72
right = object.init;
73
}
74
75
if (left && left.type === Syntax.MemberExpression) {
76
left = left.property;
77
}
78
if (left && left.type === Syntax.Identifier) {
79
addDisplayName(left.name, right, state);
80
}
81
}
82
83
visitReactDisplayName.test = function(object, path, state) {
84
return (
85
object.type === Syntax.AssignmentExpression ||
86
object.type === Syntax.Property ||
87
object.type === Syntax.VariableDeclarator
88
);
89
};
90
91
exports.visitorList = [
92
visitReactDisplayName
93
];
94
95