|
| 1 | +/** |
| 2 | + * Copyright 2015-present, Facebook, Inc. |
| 3 | + * |
| 4 | + * This source code is licensed under the MIT license found in the |
| 5 | + * LICENSE file in the root directory of this source tree. |
| 6 | + * |
| 7 | + */ |
| 8 | + |
| 9 | +"use strict"; |
| 10 | + |
| 11 | +export default (file, api, options) => { |
| 12 | + const j = api.jscodeshift; |
| 13 | + |
| 14 | + const printOptions = options.printOptions || { |
| 15 | + quote: "single", |
| 16 | + trailingComma: true, |
| 17 | + }; |
| 18 | + |
| 19 | + const root = j(file.source); |
| 20 | + |
| 21 | + let hasModifications = false; |
| 22 | + |
| 23 | + root |
| 24 | + .find(j.JSXAttribute, (node) => { |
| 25 | + return node.name.name === "ref"; |
| 26 | + }) |
| 27 | + .forEach((jsxAttributePath) => { |
| 28 | + const valuePath = jsxAttributePath.get("value"); |
| 29 | + if ( |
| 30 | + // Flow parser |
| 31 | + valuePath.value.type === "Literal" || |
| 32 | + // TSX parser |
| 33 | + valuePath.value.type === "StringLiteral" |
| 34 | + ) { |
| 35 | + hasModifications = true; |
| 36 | + // This might shadow existing variables. |
| 37 | + // But this should be safe since we control what identifiers we're reading in this block. |
| 38 | + // It will trigger ESLint's `no-shadow` though. |
| 39 | + // Babel has a helper to get a identifier that doesn't shadow existing vars. |
| 40 | + // Maybe JSCodeShift has such a helper as well? |
| 41 | + const currentIdentifierName = "current"; |
| 42 | + valuePath.replace( |
| 43 | + // {(current) => { this.refs[valuePath.node.value] = current }} |
| 44 | + j.jsxExpressionContainer( |
| 45 | + j.arrowFunctionExpression( |
| 46 | + [j.identifier(currentIdentifierName)], |
| 47 | + j.blockStatement([ |
| 48 | + j.expressionStatement( |
| 49 | + j.assignmentExpression( |
| 50 | + "=", |
| 51 | + j.memberExpression( |
| 52 | + j.memberExpression( |
| 53 | + j.thisExpression(), |
| 54 | + j.identifier("refs") |
| 55 | + ), |
| 56 | + j.literal(valuePath.node.value) |
| 57 | + ), |
| 58 | + j.identifier(currentIdentifierName) |
| 59 | + ) |
| 60 | + ), |
| 61 | + ]) |
| 62 | + ) |
| 63 | + ) |
| 64 | + ); |
| 65 | + } |
| 66 | + }); |
| 67 | + |
| 68 | + return hasModifications ? root.toSource(printOptions) : file.source; |
| 69 | +}; |
0 commit comments