@openrewrite/recipes-react 0.14.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (204) hide show
  1. package/dist/index.d.ts +12 -4
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +70 -17
  4. package/dist/index.js.map +1 -1
  5. package/dist/migration/cra-to-vite/add-vite-config.d.ts +9 -0
  6. package/dist/migration/cra-to-vite/add-vite-config.d.ts.map +1 -0
  7. package/dist/migration/cra-to-vite/add-vite-config.js +49 -0
  8. package/dist/migration/cra-to-vite/add-vite-config.js.map +1 -0
  9. package/dist/migration/cra-to-vite/cra-blockers-table.d.ts +10 -0
  10. package/dist/migration/cra-to-vite/cra-blockers-table.d.ts.map +1 -0
  11. package/dist/migration/cra-to-vite/cra-blockers-table.js +31 -0
  12. package/dist/migration/cra-to-vite/cra-blockers-table.js.map +1 -0
  13. package/dist/migration/cra-to-vite/cra-to-vite.d.ts +14 -0
  14. package/dist/migration/cra-to-vite/cra-to-vite.d.ts.map +1 -0
  15. package/dist/migration/cra-to-vite/cra-to-vite.js +73 -0
  16. package/dist/migration/cra-to-vite/cra-to-vite.js.map +1 -0
  17. package/dist/migration/cra-to-vite/find-cra-config-blockers.d.ts +14 -0
  18. package/dist/migration/cra-to-vite/find-cra-config-blockers.d.ts.map +1 -0
  19. package/dist/migration/cra-to-vite/find-cra-config-blockers.js +185 -0
  20. package/dist/migration/cra-to-vite/find-cra-config-blockers.js.map +1 -0
  21. package/dist/migration/cra-to-vite/find-cra-env-file-blockers.d.ts +10 -0
  22. package/dist/migration/cra-to-vite/find-cra-env-file-blockers.d.ts.map +1 -0
  23. package/dist/migration/cra-to-vite/find-cra-env-file-blockers.js +67 -0
  24. package/dist/migration/cra-to-vite/find-cra-env-file-blockers.js.map +1 -0
  25. package/dist/migration/cra-to-vite/find-cra-source-blockers.d.ts +10 -0
  26. package/dist/migration/cra-to-vite/find-cra-source-blockers.d.ts.map +1 -0
  27. package/dist/migration/cra-to-vite/find-cra-source-blockers.js +168 -0
  28. package/dist/migration/cra-to-vite/find-cra-source-blockers.js.map +1 -0
  29. package/dist/migration/cra-to-vite/find-cra-to-vite-blockers.d.ts +8 -0
  30. package/dist/migration/cra-to-vite/find-cra-to-vite-blockers.d.ts.map +1 -0
  31. package/dist/migration/cra-to-vite/find-cra-to-vite-blockers.js +31 -0
  32. package/dist/migration/cra-to-vite/find-cra-to-vite-blockers.js.map +1 -0
  33. package/dist/migration/cra-to-vite/index.d.ts +16 -0
  34. package/dist/migration/cra-to-vite/index.d.ts.map +1 -0
  35. package/dist/migration/cra-to-vite/index.js +35 -0
  36. package/dist/migration/cra-to-vite/index.js.map +1 -0
  37. package/dist/migration/cra-to-vite/move-public-index-html.d.ts +11 -0
  38. package/dist/migration/cra-to-vite/move-public-index-html.d.ts.map +1 -0
  39. package/dist/migration/cra-to-vite/move-public-index-html.js +124 -0
  40. package/dist/migration/cra-to-vite/move-public-index-html.js.map +1 -0
  41. package/dist/migration/cra-to-vite/rename-process-env-react-app.d.ts +9 -0
  42. package/dist/migration/cra-to-vite/rename-process-env-react-app.d.ts.map +1 -0
  43. package/dist/migration/cra-to-vite/rename-process-env-react-app.js +92 -0
  44. package/dist/migration/cra-to-vite/rename-process-env-react-app.js.map +1 -0
  45. package/dist/migration/cra-to-vite/rename-react-app-env-vars-in-env-files.d.ts +9 -0
  46. package/dist/migration/cra-to-vite/rename-react-app-env-vars-in-env-files.d.ts.map +1 -0
  47. package/dist/migration/cra-to-vite/rename-react-app-env-vars-in-env-files.js +65 -0
  48. package/dist/migration/cra-to-vite/rename-react-app-env-vars-in-env-files.js.map +1 -0
  49. package/dist/migration/cra-to-vite/replace-react-scripts-dependency.d.ts +14 -0
  50. package/dist/migration/cra-to-vite/replace-react-scripts-dependency.d.ts.map +1 -0
  51. package/dist/migration/cra-to-vite/replace-react-scripts-dependency.js +98 -0
  52. package/dist/migration/cra-to-vite/replace-react-scripts-dependency.js.map +1 -0
  53. package/dist/migration/cra-to-vite/scan-cra-projects.d.ts +21 -0
  54. package/dist/migration/cra-to-vite/scan-cra-projects.d.ts.map +1 -0
  55. package/dist/migration/cra-to-vite/scan-cra-projects.js +87 -0
  56. package/dist/migration/cra-to-vite/scan-cra-projects.js.map +1 -0
  57. package/dist/migration/cra-to-vite/shared.d.ts +37 -0
  58. package/dist/migration/cra-to-vite/shared.d.ts.map +1 -0
  59. package/dist/migration/cra-to-vite/shared.js +218 -0
  60. package/dist/migration/cra-to-vite/shared.js.map +1 -0
  61. package/dist/migration/cra-to-vite/update-react-app-env-types.d.ts +9 -0
  62. package/dist/migration/cra-to-vite/update-react-app-env-types.d.ts.map +1 -0
  63. package/dist/migration/cra-to-vite/update-react-app-env-types.js +47 -0
  64. package/dist/migration/cra-to-vite/update-react-app-env-types.js.map +1 -0
  65. package/dist/migration/cra-to-vite/update-react-scripts-scripts.d.ts +9 -0
  66. package/dist/migration/cra-to-vite/update-react-scripts-scripts.d.ts.map +1 -0
  67. package/dist/migration/cra-to-vite/update-react-scripts-scripts.js +67 -0
  68. package/dist/migration/cra-to-vite/update-react-scripts-scripts.js.map +1 -0
  69. package/dist/migration/cra-to-vite/update-tsconfig-for-vite.d.ts +10 -0
  70. package/dist/migration/cra-to-vite/update-tsconfig-for-vite.d.ts.map +1 -0
  71. package/dist/migration/cra-to-vite/update-tsconfig-for-vite.js +53 -0
  72. package/dist/migration/cra-to-vite/update-tsconfig-for-vite.js.map +1 -0
  73. package/dist/react17/migrate-deprecated-lifecycles.d.ts +8 -0
  74. package/dist/react17/migrate-deprecated-lifecycles.d.ts.map +1 -0
  75. package/dist/react17/migrate-deprecated-lifecycles.js +258 -0
  76. package/dist/react17/migrate-deprecated-lifecycles.js.map +1 -0
  77. package/dist/react17/use-new-jsx-transform.d.ts +8 -0
  78. package/dist/react17/use-new-jsx-transform.d.ts.map +1 -0
  79. package/dist/react17/use-new-jsx-transform.js +169 -0
  80. package/dist/react17/use-new-jsx-transform.js.map +1 -0
  81. package/dist/react18/add-children-to-props.d.ts +8 -0
  82. package/dist/react18/add-children-to-props.d.ts.map +1 -0
  83. package/dist/react18/add-children-to-props.js +277 -0
  84. package/dist/react18/add-children-to-props.js.map +1 -0
  85. package/dist/react18/replace-reactdom-render.d.ts.map +1 -1
  86. package/dist/react18/replace-reactdom-render.js +109 -12
  87. package/dist/react18/replace-reactdom-render.js.map +1 -1
  88. package/dist/refactoring/class-to-functional.d.ts.map +1 -1
  89. package/dist/refactoring/class-to-functional.js +81 -7
  90. package/dist/refactoring/class-to-functional.js.map +1 -1
  91. package/dist/refactoring/fix-async-effect.d.ts +8 -0
  92. package/dist/refactoring/fix-async-effect.d.ts.map +1 -0
  93. package/dist/refactoring/fix-async-effect.js +71 -0
  94. package/dist/refactoring/fix-async-effect.js.map +1 -0
  95. package/dist/refactoring/prop-types-to-typescript.d.ts +8 -0
  96. package/dist/refactoring/prop-types-to-typescript.d.ts.map +1 -0
  97. package/dist/refactoring/prop-types-to-typescript.js +342 -0
  98. package/dist/refactoring/prop-types-to-typescript.js.map +1 -0
  99. package/dist/search/find-deprecated-lifecycles.d.ts +12 -0
  100. package/dist/search/find-deprecated-lifecycles.d.ts.map +1 -0
  101. package/dist/search/find-deprecated-lifecycles.js +86 -0
  102. package/dist/search/find-deprecated-lifecycles.js.map +1 -0
  103. package/dist/search/find-effects-without-cleanup.d.ts +9 -0
  104. package/dist/search/find-effects-without-cleanup.d.ts.map +1 -0
  105. package/dist/search/find-effects-without-cleanup.js +133 -0
  106. package/dist/search/find-effects-without-cleanup.js.map +1 -0
  107. package/dist/search/find-enzyme-usage.d.ts +9 -0
  108. package/dist/search/find-enzyme-usage.d.ts.map +1 -0
  109. package/dist/search/find-enzyme-usage.js +155 -0
  110. package/dist/search/find-enzyme-usage.js.map +1 -0
  111. package/dist/search/find-function-component-default-props.d.ts +11 -0
  112. package/dist/search/find-function-component-default-props.d.ts.map +1 -0
  113. package/dist/search/find-function-component-default-props.js +96 -0
  114. package/dist/search/find-function-component-default-props.js.map +1 -0
  115. package/dist/search/find-legacy-react-apis.d.ts +8 -0
  116. package/dist/search/find-legacy-react-apis.d.ts.map +1 -0
  117. package/dist/search/find-legacy-react-apis.js +41 -0
  118. package/dist/search/find-legacy-react-apis.js.map +1 -0
  119. package/dist/search/find-missing-use-client-directive.d.ts +9 -0
  120. package/dist/search/find-missing-use-client-directive.d.ts.map +1 -0
  121. package/dist/search/find-missing-use-client-directive.js +127 -0
  122. package/dist/search/find-missing-use-client-directive.js.map +1 -0
  123. package/dist/search/find-reactdom-root-apis.d.ts +14 -0
  124. package/dist/search/find-reactdom-root-apis.d.ts.map +1 -0
  125. package/dist/search/find-reactdom-root-apis.js +122 -0
  126. package/dist/search/find-reactdom-root-apis.js.map +1 -0
  127. package/dist/testing/enzyme-to-react-testing-library.d.ts +36 -0
  128. package/dist/testing/enzyme-to-react-testing-library.d.ts.map +1 -0
  129. package/dist/testing/enzyme-to-react-testing-library.js +547 -0
  130. package/dist/testing/enzyme-to-react-testing-library.js.map +1 -0
  131. package/dist/testing/enzyme-usage.d.ts +22 -0
  132. package/dist/testing/enzyme-usage.d.ts.map +1 -0
  133. package/dist/testing/enzyme-usage.js +107 -0
  134. package/dist/testing/enzyme-usage.js.map +1 -0
  135. package/dist/testing/enzyme-wrapper-scope.d.ts +42 -0
  136. package/dist/testing/enzyme-wrapper-scope.d.ts.map +1 -0
  137. package/dist/testing/enzyme-wrapper-scope.js +422 -0
  138. package/dist/testing/enzyme-wrapper-scope.js.map +1 -0
  139. package/dist/util/react-class.d.ts +6 -0
  140. package/dist/util/react-class.d.ts.map +1 -0
  141. package/dist/util/react-class.js +41 -0
  142. package/dist/util/react-class.js.map +1 -0
  143. package/dist/util/tree-search.d.ts +6 -0
  144. package/dist/util/tree-search.d.ts.map +1 -0
  145. package/dist/util/tree-search.js +51 -0
  146. package/dist/util/tree-search.js.map +1 -0
  147. package/package.json +7 -4
  148. package/src/index.ts +53 -12
  149. package/src/migration/cra-to-vite/add-vite-config.ts +47 -0
  150. package/src/migration/cra-to-vite/cra-blockers-table.ts +27 -0
  151. package/src/migration/cra-to-vite/cra-to-vite.ts +76 -0
  152. package/src/migration/cra-to-vite/find-cra-config-blockers.ts +179 -0
  153. package/src/migration/cra-to-vite/find-cra-env-file-blockers.ts +60 -0
  154. package/src/migration/cra-to-vite/find-cra-source-blockers.ts +138 -0
  155. package/src/migration/cra-to-vite/find-cra-to-vite-blockers.ts +21 -0
  156. package/src/migration/cra-to-vite/index.ts +26 -0
  157. package/src/migration/cra-to-vite/move-public-index-html.ts +132 -0
  158. package/src/migration/cra-to-vite/rename-process-env-react-app.ts +93 -0
  159. package/src/migration/cra-to-vite/rename-react-app-env-vars-in-env-files.ts +61 -0
  160. package/src/migration/cra-to-vite/replace-react-scripts-dependency.ts +96 -0
  161. package/src/migration/cra-to-vite/scan-cra-projects.ts +86 -0
  162. package/src/migration/cra-to-vite/shared.ts +244 -0
  163. package/src/migration/cra-to-vite/update-react-app-env-types.ts +40 -0
  164. package/src/migration/cra-to-vite/update-react-scripts-scripts.ts +69 -0
  165. package/src/migration/cra-to-vite/update-tsconfig-for-vite.ts +47 -0
  166. package/src/react17/migrate-deprecated-lifecycles.ts +265 -0
  167. package/src/react17/use-new-jsx-transform.ts +150 -0
  168. package/src/react18/add-children-to-props.ts +235 -0
  169. package/src/react18/replace-reactdom-render.ts +109 -20
  170. package/src/refactoring/class-to-functional.ts +101 -13
  171. package/src/refactoring/fix-async-effect.ts +88 -0
  172. package/src/refactoring/prop-types-to-typescript.ts +341 -0
  173. package/src/search/find-deprecated-lifecycles.ts +64 -0
  174. package/src/search/find-effects-without-cleanup.ts +109 -0
  175. package/src/search/find-enzyme-usage.ts +117 -0
  176. package/src/search/find-function-component-default-props.ts +68 -0
  177. package/src/search/find-legacy-react-apis.ts +41 -0
  178. package/src/search/find-missing-use-client-directive.ts +99 -0
  179. package/src/search/find-reactdom-root-apis.ts +99 -0
  180. package/src/testing/enzyme-to-react-testing-library.ts +553 -0
  181. package/src/testing/enzyme-usage.ts +94 -0
  182. package/src/testing/enzyme-wrapper-scope.ts +449 -0
  183. package/src/util/react-class.ts +34 -0
  184. package/src/util/tree-search.ts +32 -0
  185. package/dist/react16/upgrade-to-react-16.d.ts +0 -12
  186. package/dist/react16/upgrade-to-react-16.d.ts.map +0 -1
  187. package/dist/react16/upgrade-to-react-16.js +0 -66
  188. package/dist/react16/upgrade-to-react-16.js.map +0 -1
  189. package/dist/react17/upgrade-to-react-17.d.ts +0 -12
  190. package/dist/react17/upgrade-to-react-17.d.ts.map +0 -1
  191. package/dist/react17/upgrade-to-react-17.js +0 -62
  192. package/dist/react17/upgrade-to-react-17.js.map +0 -1
  193. package/dist/react18/upgrade-to-react-18.d.ts +0 -12
  194. package/dist/react18/upgrade-to-react-18.d.ts.map +0 -1
  195. package/dist/react18/upgrade-to-react-18.js +0 -64
  196. package/dist/react18/upgrade-to-react-18.js.map +0 -1
  197. package/dist/react19/upgrade-to-react-19.d.ts +0 -8
  198. package/dist/react19/upgrade-to-react-19.d.ts.map +0 -1
  199. package/dist/react19/upgrade-to-react-19.js +0 -68
  200. package/dist/react19/upgrade-to-react-19.js.map +0 -1
  201. package/src/react16/upgrade-to-react-16.ts +0 -59
  202. package/src/react17/upgrade-to-react-17.ts +0 -52
  203. package/src/react18/upgrade-to-react-18.ts +0 -55
  204. package/src/react19/upgrade-to-react-19.ts +0 -75
@@ -1,20 +1,32 @@
1
- import {ExecutionContext, Recipe, TreeVisitor, check, not} from "@openrewrite/rewrite";
1
+ import {check, ExecutionContext, foundSearchResult, not, printer, Recipe, TreeVisitor} from "@openrewrite/rewrite";
2
2
  import {
3
3
  capture,
4
+ isVendoredOrBundled,
4
5
  JavaScriptVisitor,
6
+ JS,
5
7
  maybeRemoveImport,
6
8
  pattern,
9
+ raw,
7
10
  rewrite,
8
- template,
9
- isVendoredOrBundled
11
+ template
10
12
  } from "@openrewrite/rewrite/javascript";
11
13
  import {Expression, J} from "@openrewrite/rewrite/java";
14
+ import {create} from "mutative";
15
+
16
+ const ROOT_VARIABLE = "root";
17
+ const GUIDE = "https://react.dev/blog/2022/03/08/react-18-upgrade-guide#updates-to-client-rendering-apis";
18
+
19
+ const ONE_ROOT_PER_CONTAINER = `Create the root once per container and call \`root.render()\` on it. See ${GUIDE}`;
20
+ const RESULT_IS_USED = `\`root.render()\` returns \`void\`, not the component instance. See ${GUIDE}`;
12
21
 
13
22
  /**
14
- * Replaces `ReactDOM.render()` with `createRoot().render()`.
23
+ * Replaces `ReactDOM.render()` with `createRoot()` and `root.render()`.
15
24
  *
16
- * In React 18, `ReactDOM.render()` is deprecated in favor of
17
- * `createRoot()` from `react-dom/client`.
25
+ * In React 18, `ReactDOM.render()` is deprecated in favor of `createRoot()` from `react-dom/client`.
26
+ * A root must be created once per container and reused for every render, so only a top-level
27
+ * statement that renders a container once is rewritten. A call inside a function (it may run again
28
+ * and would create a second root), a call whose result is used (`root.render()` returns `void`),
29
+ * a container rendered twice, and a file that already uses the name `root` are marked instead.
18
30
  *
19
31
  * Before:
20
32
  * ```tsx
@@ -34,36 +46,113 @@ import {Expression, J} from "@openrewrite/rewrite/java";
34
46
  export class ReplaceReactDomRender extends Recipe {
35
47
  readonly name = "org.openrewrite.react.18.replace-reactdom-render";
36
48
  readonly displayName: string = "Replace `ReactDOM.render` with `createRoot`";
37
- readonly description: string = "Migrates from the legacy `ReactDOM.render()` API to the `createRoot()` API from `react-dom/client` introduced in React 18.";
49
+ readonly description: string = "Migrates a top-level `ReactDOM.render()` call to the `createRoot()` API from `react-dom/client` introduced in React 18, creating the root once. Calls inside functions, calls whose result is used and containers that are rendered more than once are marked for manual migration.";
38
50
 
39
51
  async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
40
- const reactDomOptions = {
41
- context: ['import { render } from "react-dom";'],
42
- dependencies: {'@types/react-dom': '^17.0.0'}
43
- };
44
-
45
52
  const element = capture<Expression>();
46
53
  const container = capture<Expression>();
47
54
 
55
+ const renderPattern = pattern`render(${element}, ${container})`.configure({
56
+ context: ['import { render } from "react-dom";'],
57
+ dependencies: {'@types/react-dom': '^17.0.0'}
58
+ });
59
+
48
60
  const rule = rewrite(() => ({
49
- before: pattern`render(${element}, ${container})`.configure(reactDomOptions),
50
- after: template`createRoot(${container}).render(${element})`.configure({
61
+ before: renderPattern,
62
+ after: template`{
63
+ const ${raw(ROOT_VARIABLE)} = createRoot(${container});
64
+ ${raw(ROOT_VARIABLE)}.render(${element});
65
+ }`.configure({
51
66
  context: ['import { createRoot } from "react-dom/client";'],
52
67
  dependencies: {'@types/react-dom': '^18.0.0'}
53
68
  })
54
69
  }));
55
70
 
56
71
  return check(not(isVendoredOrBundled()), new class extends JavaScriptVisitor<ExecutionContext> {
72
+ private containerCounts = new Map<string, number>();
73
+ private rootNameTaken = false;
74
+ private inlinedBlocks = new Set<string>();
75
+
76
+ override async visitJsCompilationUnit(cu: JS.CompilationUnit, p: ExecutionContext): Promise<J | undefined> {
77
+ this.containerCounts = new Map();
78
+ this.rootNameTaken = false;
79
+ this.inlinedBlocks = new Set();
80
+ await this.survey(cu);
81
+ const result = await super.visitJsCompilationUnit(cu, p) as JS.CompilationUnit;
82
+ return this.inlinedBlocks.size === 0 ? result : this.inlineBlocks(result);
83
+ }
84
+
57
85
  override async visitMethodInvocation(method: J.MethodInvocation, p: ExecutionContext): Promise<J | undefined> {
58
- let m = await super.visitMethodInvocation(method, p) as J.MethodInvocation;
86
+ const m = await super.visitMethodInvocation(method, p) as J.MethodInvocation;
59
87
 
60
- const result = await rule.tryOn(this.cursor, m!, {visitor: this});
61
- if (result) {
62
- maybeRemoveImport(this, "react-dom", "render");
63
- return result;
88
+ const match = await renderPattern.match(m, this.cursor);
89
+ if (!match) {
90
+ return m;
64
91
  }
65
92
 
66
- return m;
93
+ const position = this.position();
94
+ if (position === "used") {
95
+ return foundSearchResult(m, RESULT_IS_USED);
96
+ }
97
+ const containerSource = (await printer(this.cursor).print(match.get(container)!)).trim();
98
+ if (position === "nested" || this.rootNameTaken || this.containerCounts.get(containerSource)! > 1) {
99
+ return foundSearchResult(m, ONE_ROOT_PER_CONTAINER);
100
+ }
101
+
102
+ const result = await rule.tryOn(this.cursor, m, {visitor: this});
103
+ if (!result) {
104
+ return m;
105
+ }
106
+ maybeRemoveImport(this, "react-dom", "render");
107
+ this.inlinedBlocks.add(result.id);
108
+ return result;
109
+ }
110
+
111
+ /** Splices the statements of the blocks the template produced into the file, in place of the call. */
112
+ private inlineBlocks(cu: JS.CompilationUnit): JS.CompilationUnit {
113
+ return create(cu, draft => {
114
+ draft.statements = cu.statements.flatMap(padded => {
115
+ const block = padded.element as J.Block;
116
+ if (!this.inlinedBlocks.has(block.id)) return [padded];
117
+ return block.statements.map((s, i) => i === 0
118
+ ? {...s, element: {...s.element, prefix: block.prefix}}
119
+ : {...s, element: {...s.element, prefix: {...s.element.prefix, whitespace: "\n"}}});
120
+ }) as any;
121
+ });
122
+ }
123
+
124
+ /** Where the call sits: a top-level statement, a statement in a nested block, or inside another expression. */
125
+ private position(): "top-level" | "nested" | "used" {
126
+ for (let c = this.cursor.parent; c; c = c.parent) {
127
+ const kind = c.value?.kind;
128
+ if (kind === J.Kind.RightPadded || kind === JS.Kind.ExpressionStatement) {
129
+ continue;
130
+ }
131
+ if (kind === JS.Kind.CompilationUnit) return "top-level";
132
+ return kind === J.Kind.Block ? "nested" : "used";
133
+ }
134
+ return "used";
135
+ }
136
+
137
+ private async survey(cu: JS.CompilationUnit): Promise<void> {
138
+ const outer = this;
139
+ await new class extends JavaScriptVisitor<void> {
140
+ override async visitIdentifier(identifier: J.Identifier, q: void): Promise<J | undefined> {
141
+ if (identifier.simpleName === ROOT_VARIABLE) {
142
+ outer.rootNameTaken = true;
143
+ }
144
+ return super.visitIdentifier(identifier, q);
145
+ }
146
+
147
+ override async visitMethodInvocation(m: J.MethodInvocation, q: void): Promise<J | undefined> {
148
+ const match = await renderPattern.match(m, this.cursor);
149
+ if (match) {
150
+ const source = (await printer(this.cursor).print(match.get(container)!)).trim();
151
+ outer.containerCounts.set(source, (outer.containerCounts.get(source) ?? 0) + 1);
152
+ }
153
+ return super.visitMethodInvocation(m, q);
154
+ }
155
+ }().visit(cu, undefined);
67
156
  }
68
157
  }());
69
158
  }
@@ -1,6 +1,7 @@
1
- import {ExecutionContext, Recipe, TreeVisitor, check, not} from "@openrewrite/rewrite";
2
- import {capture, JavaScriptVisitor, pattern, raw, rewrite, template, isVendoredOrBundled} from "@openrewrite/rewrite/javascript";
3
- import {J} from "@openrewrite/rewrite/java";
1
+ import {ExecutionContext, Recipe, TreeVisitor, check, not, randomId} from "@openrewrite/rewrite";
2
+ import {capture, JavaScriptVisitor, pattern, raw, rewrite, template, isVendoredOrBundled, maybeAddImport, maybeRemoveImport} from "@openrewrite/rewrite/javascript";
3
+ import {J, singleSpace} from "@openrewrite/rewrite/java";
4
+ import {baseTypeArguments, unwrapBaseType} from "../util/react-class";
4
5
 
5
6
  const LIFECYCLE_METHODS = new Set([
6
7
  'componentWillMount', 'UNSAFE_componentWillMount',
@@ -38,12 +39,16 @@ const LIFECYCLE_METHODS = new Set([
38
39
  * }
39
40
  * ```
40
41
  *
42
+ * A `PureComponent` becomes `memo(function X(props) {...})` so it still skips renders for shallowly equal
43
+ * props, and `export` is kept. A `PureComponent` that is the `export default` of its file is left as a
44
+ * class, since the memo form needs a second statement.
45
+ *
41
46
  * @see https://github.com/reactjs/react-codemod#pure-component
42
47
  */
43
48
  export class ClassToFunctional extends Recipe {
44
49
  readonly name = "org.openrewrite.react.refactoring.class-to-functional";
45
50
  readonly displayName: string = "Convert class components to functional components";
46
- readonly description: string = "Converts simple render-only class components to functional components.";
51
+ readonly description: string = "Converts simple render-only class components to functional components. A `PureComponent` becomes a `memo`-wrapped function so it keeps skipping renders for equal props, and `export` is preserved.";
47
52
 
48
53
  async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
49
54
  // Rewrite rules for replacing this.props references
@@ -58,6 +63,23 @@ export class ClassToFunctional extends Recipe {
58
63
  }));
59
64
 
60
65
  return check(not(isVendoredOrBundled()), new class extends JavaScriptVisitor<ExecutionContext> {
66
+ /** Ids of the `const X = memo(...)` statements this recipe wrote, which still need their `;`. */
67
+ private memoDeclarations = new Set<string>();
68
+
69
+ override async visitRightPadded<T extends J | boolean>(right: J.RightPadded<T>, ctx: ExecutionContext): Promise<J.RightPadded<T> | undefined> {
70
+ const visited = await super.visitRightPadded(right, ctx);
71
+ const element = visited?.element as any;
72
+ if (!visited || !element?.id || !this.memoDeclarations.has(element.id)) return visited;
73
+ if (visited.markers.markers.some(m => m.kind === "org.openrewrite.java.marker.Semicolon")) return visited;
74
+ return {
75
+ ...visited,
76
+ markers: {
77
+ ...visited.markers,
78
+ markers: [...visited.markers.markers, {kind: "org.openrewrite.java.marker.Semicolon", id: randomId()}],
79
+ },
80
+ } as J.RightPadded<T>;
81
+ }
82
+
61
83
  override async visitClassDeclaration(classDecl: J.ClassDeclaration, ctx: ExecutionContext): Promise<J | undefined> {
62
84
  let cd = await super.visitClassDeclaration(classDecl, ctx) as J.ClassDeclaration;
63
85
 
@@ -75,26 +97,92 @@ export class ClassToFunctional extends Recipe {
75
97
  return cd;
76
98
  }
77
99
 
100
+ const className = cd.name.simpleName;
101
+ if (!className) return cd;
102
+
103
+ // A class expression (`connect(map)(class X extends ...)`, `const Y = class X ...`) cannot become a
104
+ // declaration, so only classes in statement position are converted.
105
+ const parent = this.cursor.parentTree()?.value;
106
+ if (parent?.kind !== J.Kind.Block && parent?.kind !== "org.openrewrite.javascript.tree.JS$CompilationUnit") return cd;
107
+
108
+ const propsParam = this.propsParameter(cd);
109
+ if (propsParam === undefined) return cd;
110
+
111
+ // Keep `export` (and `export default`) so importers still resolve the component.
112
+ const modifiers = cd.modifiers;
113
+
114
+ // A PureComponent skips renders when its props are shallowly equal, which a bare function
115
+ // does not, so it becomes `memo(function X(props) {...})` to keep that behavior.
116
+ const pure = this.pureComponentKind(cd);
117
+ // `export default memo(...)` would need a second statement; leave such classes alone.
118
+ if (pure && modifiers.some(m => m.keyword === 'default')) return cd;
119
+
78
120
  // Replace this.props references with props in the render body
79
121
  const transformedBody = await this.replaceThisProps(renderMethod.body, ctx);
80
122
 
81
- // Use template to construct the function declaration
82
- const className = cd.name.simpleName;
83
- const funcDecl = await template`function ${raw(className)}(props) {}`.apply(cd, this.cursor);
84
- if (!funcDecl) return cd;
85
-
86
123
  // Adjust render body indentation to match function (not class) nesting
87
124
  const classBodyIndent = this.getIndent(renderMethod.prefix);
88
125
  const adjustedBody = this.adjustIndentation(transformedBody as J.Block, classBodyIndent);
89
126
 
90
- // Splice the transformed render body into the template-constructed function
91
- const func = funcDecl as J.MethodDeclaration;
92
- return {...func, body: adjustedBody} as any as J.MethodDeclaration;
127
+ if (pure) {
128
+ let memo = 'React.memo';
129
+ if (pure === 'bare') {
130
+ // Print the name the import resolves to, which differs when `memo` is already bound locally.
131
+ const local = maybeAddImport(this, {module: 'react', member: 'memo', onlyIfReferenced: false});
132
+ if (!local) return cd;
133
+ memo = local;
134
+ maybeRemoveImport(this, 'react', 'PureComponent');
135
+ }
136
+ const wrapped = await template`const ${raw(className)} = ${raw(memo)}(function ${raw(className)}(${raw(propsParam)}) {});`.apply(cd, this.cursor) as J.VariableDeclarations | undefined;
137
+ if (!wrapped || !wrapped.modifiers) return cd;
138
+ const withBody = await new class extends JavaScriptVisitor<ExecutionContext> {
139
+ override async visitMethodDeclaration(method: J.MethodDeclaration): Promise<J | undefined> {
140
+ return {...method, body: adjustedBody} as J.MethodDeclaration;
141
+ }
142
+ }().visit(wrapped, ctx) as J.VariableDeclarations;
143
+ const exported = modifiers.filter(m => m.keyword === 'export');
144
+ this.memoDeclarations.add(withBody.id);
145
+ return {
146
+ ...withBody,
147
+ modifiers: [...exported, ...withBody.modifiers.map(m => exported.length > 0 ? {...m, prefix: singleSpace} : m)],
148
+ } as any;
149
+ }
150
+
151
+ // Use template to construct the function declaration, then splice the transformed render body into it
152
+ const func = await template`function ${raw(className)}(${raw(propsParam)}) {}`.apply(cd, this.cursor) as J.MethodDeclaration | undefined;
153
+ if (!func) return cd;
154
+ // The `function` keyword needs a space after any modifier in front of it.
155
+ const markers = modifiers.length === 0 ? func.markers : {
156
+ ...func.markers,
157
+ markers: func.markers.markers.map((m: any) =>
158
+ m.kind === "org.openrewrite.javascript.marker.FunctionDeclaration" ? {...m, prefix: singleSpace} : m),
159
+ };
160
+ return {...func, modifiers, markers, body: adjustedBody} as any as J.MethodDeclaration;
161
+ }
162
+
163
+ /**
164
+ * The parameter list text for the generated function: `props`, or `props: P` when the base class names
165
+ * its props type (`Component<P>`). `undefined` when the type arguments are too complex to carry over.
166
+ */
167
+ private propsParameter(cd: J.ClassDeclaration): string | undefined {
168
+ const typeArgs = baseTypeArguments(cd.extends?.element);
169
+ if (!typeArgs) return 'props';
170
+ const first = typeArgs.elements[0]?.element;
171
+ if (first?.kind !== J.Kind.Identifier) return undefined;
172
+ return `props: ${(first as J.Identifier).simpleName}`;
173
+ }
174
+
175
+ /** `React.PureComponent` is `qualified`, a bare `PureComponent` import is `bare`, anything else is not pure. */
176
+ private pureComponentKind(cd: J.ClassDeclaration): 'qualified' | 'bare' | undefined {
177
+ const base = unwrapBaseType(cd.extends?.element);
178
+ if (base?.kind === J.Kind.FieldAccess && (base as J.FieldAccess).name.element.simpleName === 'PureComponent') return 'qualified';
179
+ if (base?.kind === J.Kind.Identifier && (base as J.Identifier).simpleName === 'PureComponent') return 'bare';
180
+ return undefined;
93
181
  }
94
182
 
95
183
  private extendsReactComponent(cd: J.ClassDeclaration): boolean {
96
184
  if (!cd.extends) return false;
97
- const extendsType = cd.extends.element;
185
+ const extendsType = unwrapBaseType(cd.extends.element)!;
98
186
 
99
187
  if (extendsType.kind === J.Kind.FieldAccess) {
100
188
  const fa = extendsType as J.FieldAccess;
@@ -0,0 +1,88 @@
1
+ import {ExecutionContext, Recipe, TreeVisitor, check, not} from "@openrewrite/rewrite";
2
+ import {
3
+ capture,
4
+ isVendoredOrBundled,
5
+ JavaScriptVisitor,
6
+ pattern,
7
+ raw,
8
+ rewrite,
9
+ template
10
+ } from "@openrewrite/rewrite/javascript";
11
+ import {Expression, J} from "@openrewrite/rewrite/java";
12
+
13
+ const EFFECT_HOOKS = ['useEffect', 'useLayoutEffect'];
14
+
15
+ /**
16
+ * Wraps the body of an `async` effect callback in an immediately invoked async function.
17
+ *
18
+ * `useEffect` expects its callback to return nothing or a cleanup function. An `async` callback
19
+ * returns a promise, which React warns about and never uses as a cleanup. The effect still runs
20
+ * the same code in the same order; only the returned promise goes away.
21
+ *
22
+ * Before:
23
+ * ```tsx
24
+ * useEffect(async () => {
25
+ * const data = await load();
26
+ * setData(data);
27
+ * }, []);
28
+ * ```
29
+ *
30
+ * After:
31
+ * ```tsx
32
+ * useEffect(() => {
33
+ * (async () => {
34
+ * const data = await load();
35
+ * setData(data);
36
+ * })();
37
+ * }, []);
38
+ * ```
39
+ *
40
+ * Only `async` arrow functions passed directly to `useEffect` or `useLayoutEffect` (bare or as `React.useEffect`) are changed,
41
+ * with a block or an expression body. A `return` inside the body now returns from the inner
42
+ * function, as it effectively did before, since the outer promise was never a usable cleanup.
43
+ *
44
+ * @see https://react.dev/reference/react/useEffect#fetching-data-with-effects
45
+ */
46
+ export class FixAsyncEffect extends Recipe {
47
+ readonly name = "org.openrewrite.react.refactoring.fix-async-effect";
48
+ readonly displayName = "Fix `async` effect callbacks";
49
+ readonly description = "Wraps the body of an `async` callback passed to `useEffect` or `useLayoutEffect` in an immediately invoked async function, so the effect no longer returns a promise.";
50
+
51
+ async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
52
+ const context = {
53
+ context: ['import { useEffect, useLayoutEffect } from "react";'],
54
+ dependencies: {'@types/react': '^18.0.0'}
55
+ };
56
+ const body = capture();
57
+ const deps = capture<Expression>();
58
+
59
+ const rulesFor = (callee: string) => [
60
+ rewrite(() => ({
61
+ before: pattern`${raw(callee)}(async () => ${body}, ${deps})`.configure(context),
62
+ after: template`${raw(callee)}(() => {(async () => ${body})();}, ${deps})`.configure(context),
63
+ })),
64
+ rewrite(() => ({
65
+ before: pattern`${raw(callee)}(async () => ${body})`.configure(context),
66
+ after: template`${raw(callee)}(() => {(async () => ${body})();})`.configure(context),
67
+ })),
68
+ ];
69
+ const bareRules = EFFECT_HOOKS.flatMap(hook => rulesFor(hook));
70
+ const reactRules = EFFECT_HOOKS.flatMap(hook => rulesFor(`React.${hook}`));
71
+
72
+ return check(not(isVendoredOrBundled()), new class extends JavaScriptVisitor<ExecutionContext> {
73
+ override async visitMethodInvocation(method: J.MethodInvocation, ctx: ExecutionContext): Promise<J | undefined> {
74
+ const m = await super.visitMethodInvocation(method, ctx) as J.MethodInvocation;
75
+ // Only a direct call of an effect hook can match, so skip the structural matching for every other call.
76
+ if (!EFFECT_HOOKS.includes(m.name.simpleName)) return m;
77
+ const select = m.select?.element;
78
+ const qualified = select?.kind === J.Kind.Identifier && (select as J.Identifier).simpleName === 'React';
79
+ if (select && !qualified) return m;
80
+ for (const rule of qualified ? reactRules : bareRules) {
81
+ const result = await rule.tryOn(this.cursor, m, {visitor: this});
82
+ if (result) return result;
83
+ }
84
+ return m;
85
+ }
86
+ }());
87
+ }
88
+ }