@openrewrite/recipes-react 0.14.0 → 0.16.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 (238) 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 +177 -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 +78 -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 +24 -0
  58. package/dist/migration/cra-to-vite/shared.d.ts.map +1 -0
  59. package/dist/migration/cra-to-vite/shared.js +105 -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 +62 -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 +44 -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 +121 -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/react18/replace-unmount-component-at-node.d.ts.map +1 -1
  89. package/dist/react18/replace-unmount-component-at-node.js +62 -20
  90. package/dist/react18/replace-unmount-component-at-node.js.map +1 -1
  91. package/dist/react19/replace-default-props.d.ts.map +1 -1
  92. package/dist/react19/replace-default-props.js +10 -13
  93. package/dist/react19/replace-default-props.js.map +1 -1
  94. package/dist/react19/replace-react-shallow-renderer.d.ts.map +1 -1
  95. package/dist/react19/replace-react-shallow-renderer.js +1 -6
  96. package/dist/react19/replace-react-shallow-renderer.js.map +1 -1
  97. package/dist/refactoring/class-to-functional.d.ts.map +1 -1
  98. package/dist/refactoring/class-to-functional.js +81 -7
  99. package/dist/refactoring/class-to-functional.js.map +1 -1
  100. package/dist/refactoring/create-class-to-es6.d.ts.map +1 -1
  101. package/dist/refactoring/create-class-to-es6.js +4 -7
  102. package/dist/refactoring/create-class-to-es6.js.map +1 -1
  103. package/dist/refactoring/create-element-to-jsx.d.ts.map +1 -1
  104. package/dist/refactoring/create-element-to-jsx.js +3 -4
  105. package/dist/refactoring/create-element-to-jsx.js.map +1 -1
  106. package/dist/refactoring/fix-async-effect.d.ts +8 -0
  107. package/dist/refactoring/fix-async-effect.d.ts.map +1 -0
  108. package/dist/refactoring/fix-async-effect.js +71 -0
  109. package/dist/refactoring/fix-async-effect.js.map +1 -0
  110. package/dist/refactoring/prop-types-to-typescript.d.ts +8 -0
  111. package/dist/refactoring/prop-types-to-typescript.d.ts.map +1 -0
  112. package/dist/refactoring/prop-types-to-typescript.js +341 -0
  113. package/dist/refactoring/prop-types-to-typescript.js.map +1 -0
  114. package/dist/refactoring/pure-render-mixin.d.ts.map +1 -1
  115. package/dist/refactoring/pure-render-mixin.js +3 -6
  116. package/dist/refactoring/pure-render-mixin.js.map +1 -1
  117. package/dist/search/find-deprecated-lifecycles.d.ts +12 -0
  118. package/dist/search/find-deprecated-lifecycles.d.ts.map +1 -0
  119. package/dist/search/find-deprecated-lifecycles.js +86 -0
  120. package/dist/search/find-deprecated-lifecycles.js.map +1 -0
  121. package/dist/search/find-effects-without-cleanup.d.ts +9 -0
  122. package/dist/search/find-effects-without-cleanup.d.ts.map +1 -0
  123. package/dist/search/find-effects-without-cleanup.js +133 -0
  124. package/dist/search/find-effects-without-cleanup.js.map +1 -0
  125. package/dist/search/find-enzyme-usage.d.ts +9 -0
  126. package/dist/search/find-enzyme-usage.d.ts.map +1 -0
  127. package/dist/search/find-enzyme-usage.js +155 -0
  128. package/dist/search/find-enzyme-usage.js.map +1 -0
  129. package/dist/search/find-function-component-default-props.d.ts +11 -0
  130. package/dist/search/find-function-component-default-props.d.ts.map +1 -0
  131. package/dist/search/find-function-component-default-props.js +96 -0
  132. package/dist/search/find-function-component-default-props.js.map +1 -0
  133. package/dist/search/find-legacy-react-apis.d.ts +8 -0
  134. package/dist/search/find-legacy-react-apis.d.ts.map +1 -0
  135. package/dist/search/find-legacy-react-apis.js +41 -0
  136. package/dist/search/find-legacy-react-apis.js.map +1 -0
  137. package/dist/search/find-missing-use-client-directive.d.ts +9 -0
  138. package/dist/search/find-missing-use-client-directive.d.ts.map +1 -0
  139. package/dist/search/find-missing-use-client-directive.js +127 -0
  140. package/dist/search/find-missing-use-client-directive.js.map +1 -0
  141. package/dist/search/find-reactdom-root-apis.d.ts +14 -0
  142. package/dist/search/find-reactdom-root-apis.d.ts.map +1 -0
  143. package/dist/search/find-reactdom-root-apis.js +122 -0
  144. package/dist/search/find-reactdom-root-apis.js.map +1 -0
  145. package/dist/testing/enzyme-host-components.d.ts +14 -0
  146. package/dist/testing/enzyme-host-components.d.ts.map +1 -0
  147. package/dist/testing/enzyme-host-components.js +245 -0
  148. package/dist/testing/enzyme-host-components.js.map +1 -0
  149. package/dist/testing/enzyme-to-react-testing-library.d.ts +41 -0
  150. package/dist/testing/enzyme-to-react-testing-library.d.ts.map +1 -0
  151. package/dist/testing/enzyme-to-react-testing-library.js +572 -0
  152. package/dist/testing/enzyme-to-react-testing-library.js.map +1 -0
  153. package/dist/testing/enzyme-usage.d.ts +22 -0
  154. package/dist/testing/enzyme-usage.d.ts.map +1 -0
  155. package/dist/testing/enzyme-usage.js +107 -0
  156. package/dist/testing/enzyme-usage.js.map +1 -0
  157. package/dist/testing/enzyme-wrapper-scope.d.ts +51 -0
  158. package/dist/testing/enzyme-wrapper-scope.d.ts.map +1 -0
  159. package/dist/testing/enzyme-wrapper-scope.js +420 -0
  160. package/dist/testing/enzyme-wrapper-scope.js.map +1 -0
  161. package/dist/util/module-imports.d.ts +12 -0
  162. package/dist/util/module-imports.d.ts.map +1 -0
  163. package/dist/util/module-imports.js +56 -0
  164. package/dist/util/module-imports.js.map +1 -0
  165. package/dist/util/react-class.d.ts +7 -0
  166. package/dist/util/react-class.d.ts.map +1 -0
  167. package/dist/util/react-class.js +42 -0
  168. package/dist/util/react-class.js.map +1 -0
  169. package/dist/util/tree-search.d.ts +6 -0
  170. package/dist/util/tree-search.d.ts.map +1 -0
  171. package/dist/util/tree-search.js +51 -0
  172. package/dist/util/tree-search.js.map +1 -0
  173. package/package.json +7 -4
  174. package/src/index.ts +53 -12
  175. package/src/migration/cra-to-vite/add-vite-config.ts +47 -0
  176. package/src/migration/cra-to-vite/cra-blockers-table.ts +27 -0
  177. package/src/migration/cra-to-vite/cra-to-vite.ts +76 -0
  178. package/src/migration/cra-to-vite/find-cra-config-blockers.ts +173 -0
  179. package/src/migration/cra-to-vite/find-cra-env-file-blockers.ts +60 -0
  180. package/src/migration/cra-to-vite/find-cra-source-blockers.ts +138 -0
  181. package/src/migration/cra-to-vite/find-cra-to-vite-blockers.ts +21 -0
  182. package/src/migration/cra-to-vite/index.ts +26 -0
  183. package/src/migration/cra-to-vite/move-public-index-html.ts +132 -0
  184. package/src/migration/cra-to-vite/rename-process-env-react-app.ts +93 -0
  185. package/src/migration/cra-to-vite/rename-react-app-env-vars-in-env-files.ts +61 -0
  186. package/src/migration/cra-to-vite/replace-react-scripts-dependency.ts +71 -0
  187. package/src/migration/cra-to-vite/scan-cra-projects.ts +86 -0
  188. package/src/migration/cra-to-vite/shared.ts +123 -0
  189. package/src/migration/cra-to-vite/update-react-app-env-types.ts +40 -0
  190. package/src/migration/cra-to-vite/update-react-scripts-scripts.ts +64 -0
  191. package/src/migration/cra-to-vite/update-tsconfig-for-vite.ts +40 -0
  192. package/src/react17/migrate-deprecated-lifecycles.ts +265 -0
  193. package/src/react17/use-new-jsx-transform.ts +108 -0
  194. package/src/react18/add-children-to-props.ts +235 -0
  195. package/src/react18/replace-reactdom-render.ts +109 -20
  196. package/src/react18/replace-unmount-component-at-node.ts +78 -32
  197. package/src/react19/replace-default-props.ts +11 -15
  198. package/src/react19/replace-react-shallow-renderer.ts +2 -7
  199. package/src/refactoring/class-to-functional.ts +101 -13
  200. package/src/refactoring/create-class-to-es6.ts +6 -9
  201. package/src/refactoring/create-element-to-jsx.ts +4 -6
  202. package/src/refactoring/fix-async-effect.ts +88 -0
  203. package/src/refactoring/prop-types-to-typescript.ts +341 -0
  204. package/src/refactoring/pure-render-mixin.ts +4 -7
  205. package/src/search/find-deprecated-lifecycles.ts +64 -0
  206. package/src/search/find-effects-without-cleanup.ts +109 -0
  207. package/src/search/find-enzyme-usage.ts +117 -0
  208. package/src/search/find-function-component-default-props.ts +68 -0
  209. package/src/search/find-legacy-react-apis.ts +41 -0
  210. package/src/search/find-missing-use-client-directive.ts +99 -0
  211. package/src/search/find-reactdom-root-apis.ts +99 -0
  212. package/src/testing/enzyme-host-components.ts +283 -0
  213. package/src/testing/enzyme-to-react-testing-library.ts +622 -0
  214. package/src/testing/enzyme-usage.ts +94 -0
  215. package/src/testing/enzyme-wrapper-scope.ts +456 -0
  216. package/src/util/module-imports.ts +55 -0
  217. package/src/util/react-class.ts +35 -0
  218. package/src/util/tree-search.ts +32 -0
  219. package/dist/react16/upgrade-to-react-16.d.ts +0 -12
  220. package/dist/react16/upgrade-to-react-16.d.ts.map +0 -1
  221. package/dist/react16/upgrade-to-react-16.js +0 -66
  222. package/dist/react16/upgrade-to-react-16.js.map +0 -1
  223. package/dist/react17/upgrade-to-react-17.d.ts +0 -12
  224. package/dist/react17/upgrade-to-react-17.d.ts.map +0 -1
  225. package/dist/react17/upgrade-to-react-17.js +0 -62
  226. package/dist/react17/upgrade-to-react-17.js.map +0 -1
  227. package/dist/react18/upgrade-to-react-18.d.ts +0 -12
  228. package/dist/react18/upgrade-to-react-18.d.ts.map +0 -1
  229. package/dist/react18/upgrade-to-react-18.js +0 -64
  230. package/dist/react18/upgrade-to-react-18.js.map +0 -1
  231. package/dist/react19/upgrade-to-react-19.d.ts +0 -8
  232. package/dist/react19/upgrade-to-react-19.d.ts.map +0 -1
  233. package/dist/react19/upgrade-to-react-19.js +0 -68
  234. package/dist/react19/upgrade-to-react-19.js.map +0 -1
  235. package/src/react16/upgrade-to-react-16.ts +0 -59
  236. package/src/react17/upgrade-to-react-17.ts +0 -52
  237. package/src/react18/upgrade-to-react-18.ts +0 -55
  238. 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,68 +1,114 @@
1
- import {ExecutionContext, Recipe, TreeVisitor, check, not} from "@openrewrite/rewrite";
1
+ import {and, check, Cursor, ExecutionContext, foundSearchResult, not, Recipe, TreeVisitor} from "@openrewrite/rewrite";
2
2
  import {
3
3
  capture,
4
+ isEqual,
4
5
  JavaScriptVisitor,
6
+ isVendoredOrBundled,
7
+ JS,
5
8
  maybeRemoveImport,
6
9
  pattern,
7
- rewrite,
10
+ raw,
8
11
  template,
9
- isVendoredOrBundled
12
+ usesMethod
10
13
  } from "@openrewrite/rewrite/javascript";
11
- import {Expression, J} from "@openrewrite/rewrite/java";
14
+ import {Expression, isIdentifier, J} from "@openrewrite/rewrite/java";
15
+
16
+ const GUIDE = "https://react.dev/blog/2022/03/08/react-18-upgrade-guide#updates-to-client-rendering-apis";
17
+ const NO_ROOT_MESSAGE = `No \`root\` for this container is in scope. Call \`unmount()\` on the root returned by \`createRoot\`: ${GUIDE}`;
18
+ const VALUE_USED_MESSAGE = `The result of \`unmountComponentAtNode\` is used, but \`root.unmount()\` returns \`void\`: ${GUIDE}`;
12
19
 
13
20
  /**
14
- * Replaces `ReactDOM.unmountComponentAtNode()` with `createRoot().unmount()`.
21
+ * Replaces `unmountComponentAtNode(container)` with `root.unmount()` when the
22
+ * `root` returned by `createRoot(container)` for the same container is in scope.
15
23
  *
16
- * In React 18, `ReactDOM.unmountComponentAtNode()` is deprecated in favor of
17
- * `createRoot().unmount()` from `react-dom/client`.
24
+ * `createRoot(container).unmount()` would unmount a new, empty root and leave the
25
+ * mounted tree alive, so without a root in scope the call is kept and marked.
26
+ * It is also kept and marked when its `boolean` result is used, because
27
+ * `unmount()` returns `void`.
18
28
  *
19
29
  * Before:
20
30
  * ```tsx
21
- * import { unmountComponentAtNode } from 'react-dom';
22
- * unmountComponentAtNode(document.getElementById('root'));
31
+ * const root = createRoot(container);
32
+ * unmountComponentAtNode(container);
23
33
  * ```
24
34
  *
25
35
  * After:
26
36
  * ```tsx
27
- * import { createRoot } from 'react-dom/client';
28
- * createRoot(document.getElementById('root')).unmount();
37
+ * const root = createRoot(container);
38
+ * root.unmount();
29
39
  * ```
30
40
  *
31
41
  * @see https://react.dev/blog/2022/03/08/react-18-upgrade-guide#updates-to-client-rendering-apis
32
42
  */
33
43
  export class ReplaceUnmountComponentAtNode extends Recipe {
34
44
  readonly name = "org.openrewrite.react.18.replace-unmount-component-at-node";
35
- readonly displayName: string = "Replace `unmountComponentAtNode` with `createRoot().unmount()`";
36
- readonly description: string = "Replaces `ReactDOM.unmountComponentAtNode(container)` with `createRoot(container).unmount()` from `react-dom/client`.";
45
+ readonly displayName: string = "Replace `unmountComponentAtNode` with `root.unmount()`";
46
+ readonly description: string = "Replaces `ReactDOM.unmountComponentAtNode(container)` with `root.unmount()` when the `root` created by `createRoot(container)` is in scope. Otherwise, and when the call's result is used, the call is kept and marked.";
37
47
 
38
48
  async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
39
- const reactDomOptions = {
49
+ const container = capture<Expression>();
50
+ const unmountCall = pattern`unmountComponentAtNode(${container})`.configure({
40
51
  context: ['import { unmountComponentAtNode } from "react-dom";'],
41
52
  dependencies: {'@types/react-dom': '^17.0.0'}
42
- };
53
+ });
54
+ const rootContainer = capture<Expression>();
55
+ const createRootCall = pattern`createRoot(${rootContainer})`.configure({
56
+ context: ['import { createRoot } from "react-dom/client";'],
57
+ dependencies: {'@types/react-dom': '^18.0.0'}
58
+ });
43
59
 
44
- const container = capture<Expression>();
60
+ const visitor = new class extends JavaScriptVisitor<ExecutionContext> {
61
+ override async visitMethodInvocation(method: J.MethodInvocation, p: ExecutionContext): Promise<J | undefined> {
62
+ const m = await super.visitMethodInvocation(method, p) as J.MethodInvocation;
45
63
 
46
- const rule = rewrite(() => ({
47
- before: pattern`unmountComponentAtNode(${container})`.configure(reactDomOptions),
48
- after: template`createRoot(${container}).unmount()`.configure({
49
- context: ['import { createRoot } from "react-dom/client";'],
50
- dependencies: {'@types/react-dom': '^18.0.0'}
51
- })
52
- }));
64
+ const match = await unmountCall.match(m, this.cursor);
65
+ const containerArg = match?.get(container);
66
+ if (!containerArg) return m;
53
67
 
54
- return check(not(isVendoredOrBundled()), new class extends JavaScriptVisitor<ExecutionContext> {
55
- override async visitMethodInvocation(method: J.MethodInvocation, p: ExecutionContext): Promise<J | undefined> {
56
- let m = await super.visitMethodInvocation(method, p) as J.MethodInvocation;
68
+ if (!isStatement(this.cursor)) {
69
+ return foundSearchResult(m, VALUE_USED_MESSAGE);
70
+ }
57
71
 
58
- const result = await rule.tryOn(this.cursor, m!, {visitor: this});
59
- if (result) {
60
- maybeRemoveImport(this, "react-dom", "unmountComponentAtNode");
61
- return result;
72
+ const root = await this.findRoot(containerArg);
73
+ if (!root) {
74
+ return foundSearchResult(m, NO_ROOT_MESSAGE);
62
75
  }
63
76
 
64
- return m;
77
+ maybeRemoveImport(this, "react-dom", "unmountComponentAtNode");
78
+ return await template`${raw(root)}.unmount()`.apply(m, this.cursor);
65
79
  }
66
- }());
80
+
81
+ /** The name of a `const root = createRoot(<container>)` in an enclosing scope. */
82
+ private async findRoot(containerArg: Expression): Promise<string | undefined> {
83
+ for (let c: Cursor | undefined = this.cursor; c; c = c.parent) {
84
+ const statements: any[] | undefined = c.value?.kind === J.Kind.Block || c.value?.kind === JS.Kind.CompilationUnit
85
+ ? c.value.statements
86
+ : undefined;
87
+ for (const statement of statements ?? []) {
88
+ const decl = statement.element ?? statement;
89
+ if (decl.kind !== J.Kind.VariableDeclarations) continue;
90
+ for (const v of decl.variables) {
91
+ const named = v.element;
92
+ const init = named.initializer?.element;
93
+ if (!init || !isIdentifier(named.name)) continue;
94
+ const rootArg = (await createRootCall.match(init, this.cursor))?.get(rootContainer);
95
+ if (rootArg && await isEqual(rootArg, containerArg)) {
96
+ return named.name.simpleName;
97
+ }
98
+ }
99
+ }
100
+ }
101
+ return undefined;
102
+ }
103
+ }();
104
+
105
+ return check(and(usesMethod("react-dom unmountComponentAtNode(..)"), not(isVendoredOrBundled())), visitor);
67
106
  }
68
107
  }
108
+
109
+ /** Whether the invocation at the cursor is an expression statement, so its value is unused. */
110
+ function isStatement(cursor: Cursor): boolean {
111
+ const parent = cursor.parent?.value;
112
+ const grand = cursor.parent?.parent?.value;
113
+ return parent?.kind === J.Kind.RightPadded && (grand?.kind === J.Kind.Block || grand?.kind === JS.Kind.CompilationUnit);
114
+ }
@@ -1,5 +1,5 @@
1
1
  import {ExecutionContext, Recipe, TreeVisitor, check, not} from "@openrewrite/rewrite";
2
- import {JavaScriptVisitor, JS, isVendoredOrBundled} from "@openrewrite/rewrite/javascript";
2
+ import {isObjectLiteral, JavaScriptVisitor, JS, isVendoredOrBundled} from "@openrewrite/rewrite/javascript";
3
3
  import {Expression, isIdentifier, J} from "@openrewrite/rewrite/java";
4
4
  import {create} from "mutative";
5
5
 
@@ -111,20 +111,16 @@ export class ReplaceDefaultProps extends Recipe {
111
111
  private extractObjectLiteralDefaults(expr: Expression): Map<string, Expression> {
112
112
  const defaults = new Map<string, Expression>();
113
113
 
114
- // Object literals are represented as J.NewClass in the AST
115
- if (expr.kind === J.Kind.NewClass) {
116
- const newClass = expr as J.NewClass;
117
- if (newClass.body) {
118
- for (const stmt of newClass.body.statements) {
119
- const s = stmt.element;
120
- if (!s) continue;
121
-
122
- if (s.kind === JS.Kind.PropertyAssignment) {
123
- const prop = s as JS.PropertyAssignment;
124
- const nameExpr = prop.name.element;
125
- if (isIdentifier(nameExpr) && prop.initializer) {
126
- defaults.set(nameExpr.simpleName, prop.initializer);
127
- }
114
+ if (isObjectLiteral(expr) && expr.body) {
115
+ for (const stmt of expr.body.statements) {
116
+ const s = stmt.element;
117
+ if (!s) continue;
118
+
119
+ if (s.kind === JS.Kind.PropertyAssignment) {
120
+ const prop = s as JS.PropertyAssignment;
121
+ const nameExpr = prop.name.element;
122
+ if (isIdentifier(nameExpr) && prop.initializer) {
123
+ defaults.set(nameExpr.simpleName, prop.initializer);
128
124
  }
129
125
  }
130
126
  }
@@ -1,5 +1,5 @@
1
1
  import {ExecutionContext, Recipe, TreeVisitor, check, not} from "@openrewrite/rewrite";
2
- import {JavaScriptVisitor, JS, isVendoredOrBundled} from "@openrewrite/rewrite/javascript";
2
+ import {JavaScriptVisitor, JS, isVendoredOrBundled, withStringValue} from "@openrewrite/rewrite/javascript";
3
3
  import {J} from "@openrewrite/rewrite/java";
4
4
  import {create} from "mutative";
5
5
 
@@ -43,12 +43,7 @@ export class ReplaceReactShallowRenderer extends Recipe {
43
43
  const literal = modSpec as J.Literal;
44
44
  if (literal.value !== 'react-test-renderer/shallow') return paddedStmt;
45
45
 
46
- const newLiteral = create(literal, draft => {
47
- draft.value = 'react-shallow-renderer';
48
- if (draft.valueSource) {
49
- draft.valueSource = draft.valueSource.replace('react-test-renderer/shallow', 'react-shallow-renderer');
50
- }
51
- });
46
+ const newLiteral = withStringValue(literal, 'react-shallow-renderer');
52
47
 
53
48
  const newModSpec = (imp.moduleSpecifier as any).element
54
49
  ? {...(imp.moduleSpecifier as any), element: newLiteral}
@@ -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;
@@ -1,6 +1,6 @@
1
1
  import {Cursor, emptyMarkers, ExecutionContext, findMarker, Marker, printer, randomId, Recipe, Tree, TreeVisitor, check, not} from "@openrewrite/rewrite";
2
- import {compilationUnitOf, JavaScriptVisitor, JS, maybeBind, maybeUnbind, moduleBindings, raw, template, isVendoredOrBundled} from "@openrewrite/rewrite/javascript";
3
- import {Comment, J, TextComment} from "@openrewrite/rewrite/java";
2
+ import {compilationUnitOf, isObjectLiteral, JavaScriptVisitor, JS, maybeBind, maybeUnbind, moduleBindings, raw, template, isVendoredOrBundled} from "@openrewrite/rewrite/javascript";
3
+ import {Comment, isTextComment, J, TextComment} from "@openrewrite/rewrite/java";
4
4
 
5
5
  const LIFECYCLE_METHODS = new Set([
6
6
  'render',
@@ -110,11 +110,8 @@ export class CreateClassToES6 extends Recipe {
110
110
  const args = methodInv.arguments.elements;
111
111
  if (args.length === 0) return vd;
112
112
 
113
- const specArg = args[0].element;
114
- if (specArg.kind !== J.Kind.NewClass) return vd;
115
-
116
- const specObj = specArg as J.NewClass;
117
- if (!specObj.body) return vd;
113
+ const specObj = args[0].element;
114
+ if (!isObjectLiteral(specObj) || !specObj.body) return vd;
118
115
 
119
116
  // Check for mixins — skip conversion if present
120
117
  if (this.hasMixins(specObj.body)) return vd;
@@ -434,7 +431,7 @@ async function inPlaceOf(member: J.RightPadded<J>, field: J, value: J, lineFollo
434
431
  const next = j < space.comments.length - 1 ? '' : around.after[i + 1]?.whitespace;
435
432
  // The last one ends the line where a line comment would take in what follows
436
433
  const suffix = next !== undefined ? shift(c.suffix + next) :
437
- ((c as TextComment).multiline || lineFollows ? '' : lineStart ?? '\n') + member.after.whitespace;
434
+ (isTextComment(c) && c.multiline || lineFollows ? '' : lineStart ?? '\n') + member.after.whitespace;
438
435
  return {...shiftComment(c, shift), suffix};
439
436
  }));
440
437
  return {
@@ -530,7 +527,7 @@ function shiftLines(text: string, from: string, to: string): string {
530
527
 
531
528
  /** The comment with `shift` applied to the lines its text spans, as only a block comment's can. */
532
529
  function shiftComment(comment: Comment, shift: (text: string) => string): Comment {
533
- return (comment as TextComment).multiline ? {...comment, text: shift((comment as TextComment).text)} as TextComment : comment;
530
+ return isTextComment(comment) && comment.multiline ? {...comment, text: shift(comment.text)} as TextComment : comment;
534
531
  }
535
532
 
536
533
  /** Whether the file binds `name` with an `import type`, as its default or namespace import. */
@@ -1,5 +1,5 @@
1
1
  import {ExecutionContext, printer, Recipe, TreeVisitor, check, not} from "@openrewrite/rewrite";
2
- import {JavaScriptVisitor, JS, raw, template, isVendoredOrBundled} from "@openrewrite/rewrite/javascript";
2
+ import {isObjectLiteral, JavaScriptVisitor, JS, raw, template, isVendoredOrBundled} from "@openrewrite/rewrite/javascript";
3
3
  import {J} from "@openrewrite/rewrite/java";
4
4
 
5
5
  /**
@@ -116,13 +116,11 @@ export class CreateElementToJsx extends Recipe {
116
116
  if ((propsExpr as J.Identifier).simpleName === 'undefined') return '';
117
117
  }
118
118
 
119
- // Object literal (represented as J.NewClass with body)
120
- if (propsExpr.kind === J.Kind.NewClass) {
121
- const obj = propsExpr as J.NewClass;
122
- if (!obj.body) return '';
119
+ if (isObjectLiteral(propsExpr)) {
120
+ if (!propsExpr.body) return '';
123
121
 
124
122
  const attrs: string[] = [];
125
- for (const stmt of obj.body.statements) {
123
+ for (const stmt of propsExpr.body.statements) {
126
124
  const s = stmt.element;
127
125
 
128
126
  if (s.kind === JS.Kind.PropertyAssignment) {