-
Notifications
You must be signed in to change notification settings - Fork 298
Expand file tree
/
Copy pathstring-refs.js
More file actions
69 lines (62 loc) · 2.04 KB
/
string-refs.js
File metadata and controls
69 lines (62 loc) · 2.04 KB
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
/**
* Copyright 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
"use strict";
export default (file, api, options) => {
const j = api.jscodeshift;
const printOptions = options.printOptions || {
quote: "single",
trailingComma: true,
};
const root = j(file.source);
let hasModifications = false;
root
.find(j.JSXAttribute, (node) => {
return node.name.name === "ref";
})
.forEach((jsxAttributePath) => {
const valuePath = jsxAttributePath.get("value");
if (
// Flow parser
valuePath.value.type === "Literal" ||
// TSX parser
valuePath.value.type === "StringLiteral"
) {
hasModifications = true;
// This might shadow existing variables.
// But this should be safe since we control what identifiers we're reading in this block.
// It will trigger ESLint's `no-shadow` though.
// Babel has a helper to get a identifier that doesn't shadow existing vars.
// Maybe JSCodeShift has such a helper as well?
const currentIdentifierName = "current";
valuePath.replace(
// {(current) => { this.refs[valuePath.node.value] = current }}
j.jsxExpressionContainer(
j.arrowFunctionExpression(
[j.identifier(currentIdentifierName)],
j.blockStatement([
j.expressionStatement(
j.assignmentExpression(
"=",
j.memberExpression(
j.memberExpression(
j.thisExpression(),
j.identifier("refs")
),
j.literal(valuePath.node.value)
),
j.identifier(currentIdentifierName)
)
),
])
)
)
);
}
});
return hasModifications ? root.toSource(printOptions) : file.source;
};