-
Notifications
You must be signed in to change notification settings - Fork 61
/
isStatelessComponent.js
83 lines (65 loc) · 1.75 KB
/
isStatelessComponent.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// @flow weak
function isJSXElementOrReactCreateElement(path) {
let visited = false
path.traverse({
CallExpression(path2) {
const callee = path2.get('callee')
if (
callee.matchesPattern('React.createElement') ||
callee.matchesPattern('React.cloneElement')
) {
visited = true
}
},
JSXElement() {
visited = true
},
})
return visited
}
function isReturningJSXElement(path) {
// Early exit for ArrowFunctionExpressions, there is no ReturnStatement node.
if (path.node.init && path.node.init.body && isJSXElementOrReactCreateElement(path)) {
return true
}
let visited = false
path.traverse({
ReturnStatement(path2) {
// We have already found what we are looking for.
if (visited) {
return
}
const argument = path2.get('argument')
// Nothing is returned
if (!argument.node) {
return
}
if (isJSXElementOrReactCreateElement(path2)) {
visited = true
return
}
if (argument.node.type === 'CallExpression') {
const name = argument.get('callee').node.name
const binding = path.scope.getBinding(name)
if (!binding) {
return
}
if (isReturningJSXElement(binding.path)) {
visited = true
}
}
},
})
return visited
}
const VALID_POSSIBLE_STATELESS_COMPONENT_TYPES = ['VariableDeclarator', 'FunctionDeclaration']
// Returns `true` if the path represents a function which returns a JSXElement
export default function isStatelessComponent(path) {
if (VALID_POSSIBLE_STATELESS_COMPONENT_TYPES.indexOf(path.node.type) === -1) {
return false
}
if (isReturningJSXElement(path)) {
return true
}
return false
}