@openrewrite/recipes-react 0.13.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
@@ -0,0 +1,265 @@
1
+ import {ExecutionContext, Recipe, TreeVisitor, check, not, randomId} from "@openrewrite/rewrite";
2
+ import {isVendoredOrBundled, JavaScriptVisitor, JS, namesDeclaredWithin, namesUsedWithin, template} from "@openrewrite/rewrite/javascript";
3
+ import {J} from "@openrewrite/rewrite/java";
4
+ import {anyNode, isThis} from "../util/tree-search";
5
+ import {extendsReactComponentByName} from "../util/react-class";
6
+
7
+ /** The lifecycle name without the `UNSAFE_` prefix. */
8
+ function lifecycleName(method: J.MethodDeclaration): string {
9
+ return method.name.simpleName.replace(/^UNSAFE_/, '');
10
+ }
11
+
12
+ const isSetState = (n: J) => n.kind === J.Kind.MethodInvocation && isThis((n as J.MethodInvocation).select?.element)
13
+ && (n as J.MethodInvocation).name.simpleName === 'setState';
14
+ const readsThisState = (n: J) => n.kind === J.Kind.FieldAccess && isThis((n as J.FieldAccess).target)
15
+ && (n as J.FieldAccess).name.element.simpleName === 'state';
16
+ const isReturn = (n: J) => n.kind === J.Kind.Return;
17
+ /** `this.x = ...`, `this.x += ...`: a write to an instance member. */
18
+ const writesThisMember = (n: J) => (n.kind === J.Kind.Assignment && isThisMember((n as J.Assignment).variable))
19
+ || (n.kind === J.Kind.AssignmentOperation && isThisMember((n as J.AssignmentOperation).variable));
20
+ const isThisMember = (e: J | undefined) => e?.kind === J.Kind.FieldAccess && isThis((e as J.FieldAccess).target);
21
+ /** `this.method()`: may touch anything on the instance. */
22
+ const callsThisMethod = (n: J) => n.kind === J.Kind.MethodInvocation && isThis((n as J.MethodInvocation).select?.element);
23
+ /** `this.x` for anything but `props` and `context`, which exist before the class fields are initialized. */
24
+ const readsThisMember = (n: J) => isThisMember(n) && !['props', 'context'].includes((n as J.FieldAccess).name.element.simpleName);
25
+ const isAsync = (m: J.MethodDeclaration) => m.modifiers.some(mod => mod.keyword === 'async');
26
+
27
+ /**
28
+ * Whether every `this` in the tree is the target of a read of `this.props` or `this.context`, which exist before the
29
+ * class fields are initialized. Any other use (`this.x`, `this.method()`, `const self = this`, passing `this` on) may
30
+ * observe or change the instance, so moving the code around it changes what the component does.
31
+ */
32
+ async function usesThisOnlyForPropsAndContext(tree: J | undefined): Promise<boolean> {
33
+ if (!tree) return true;
34
+ let ok = true;
35
+ await new class extends JavaScriptVisitor<ExecutionContext> {
36
+ protected override async visitIdentifier(id: J.Identifier): Promise<J | undefined> {
37
+ if (isThis(id)) {
38
+ const parent = this.cursor.parentTree()?.value as J | undefined;
39
+ const field = parent?.kind === J.Kind.FieldAccess ? parent as J.FieldAccess : undefined;
40
+ if (!field || field.target !== id || !['props', 'context'].includes(field.name.element.simpleName)) ok = false;
41
+ }
42
+ return id;
43
+ }
44
+ }().visit(tree, {} as ExecutionContext);
45
+ return ok;
46
+ }
47
+
48
+ const isNotEqual = (e: J): boolean => (e.kind === JS.Kind.Binary && (e as JS.Binary).operator.element as string === 'IdentityNotEquals')
49
+ || (e.kind === J.Kind.Binary && (e as J.Binary).operator.element as string === 'NotEqual');
50
+
51
+ /**
52
+ * Whether the guard only holds when props changed: every `||` branch is a `!==` or `!=` comparison that has
53
+ * `next` on one side and `this.props` on the other. A branch that does not compare props (`this.state.page !== 1`)
54
+ * would be true after state-only updates, which `componentDidUpdate` also sees.
55
+ */
56
+ async function isChangeGuard(e: J | undefined, next: string): Promise<boolean> {
57
+ if (e?.kind === J.Kind.Parentheses) return isChangeGuard((e as J.Parentheses<J>).tree.element, next);
58
+ if (!e) return false;
59
+ if (e.kind === J.Kind.Binary && (e as J.Binary).operator.element as string === 'Or') {
60
+ const b = e as J.Binary;
61
+ return await isChangeGuard(b.left, next) && await isChangeGuard(b.right, next);
62
+ }
63
+ if (!isNotEqual(e)) return false;
64
+ const sides = e.kind === JS.Kind.Binary ? [(e as JS.Binary).left, (e as JS.Binary).right] : [(e as J.Binary).left, (e as J.Binary).right];
65
+ const mentionsNext = (n: J) => n.kind === J.Kind.Identifier && (n as J.Identifier).simpleName === next;
66
+ const hasNext = await Promise.all(sides.map(x => anyNode(x, mentionsNext)));
67
+ const hasProps = await Promise.all(sides.map(x => anyNode(x, readsThisProps)));
68
+ return (hasNext[0] && hasProps[1]) || (hasNext[1] && hasProps[0]);
69
+ }
70
+ const readsThisProps = (n: J) => n.kind === J.Kind.FieldAccess && isThis((n as J.FieldAccess).target)
71
+ && (n as J.FieldAccess).name.element.simpleName === 'props';
72
+
73
+ /**
74
+ * Migrates the deprecated `componentWillMount` and `componentWillReceiveProps` lifecycles where that
75
+ * is safe, and leaves everything else for the `UNSAFE_` prefix.
76
+ *
77
+ * - `componentWillMount() { this.setState({...}) }` becomes a `state = {...}` class field.
78
+ * - A `componentWillMount` that neither touches `this.state` nor calls `setState` or `return`s moves to
79
+ * `componentDidMount`, ahead of the existing body when there is one. It then runs after the first
80
+ * render instead of before it, which is the move React recommends for side effects.
81
+ * - A `componentWillReceiveProps(next)` whose whole body is one `if` comparing `next` with `this.props`
82
+ * and that never calls `setState` becomes `componentDidUpdate(prevProps)`, with `next` and `this.props`
83
+ * swapped. The guard keeps it from running on state-only updates, which `componentDidUpdate` also sees.
84
+ *
85
+ * A class that already has a constructor, a `state` field or a `componentDidUpdate` is not changed for the
86
+ * case that would collide with it.
87
+ *
88
+ * @see https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html
89
+ */
90
+ export class MigrateDeprecatedLifecycles extends Recipe {
91
+ readonly name = "org.openrewrite.react.17.migrate-deprecated-lifecycles";
92
+ readonly displayName = "Migrate deprecated lifecycles where it is safe";
93
+ readonly description = "Moves `componentWillMount` to a `state` field or `componentDidMount`, and a guarded `componentWillReceiveProps` to `componentDidUpdate`, when the move does not change what the component does. Everything else is left for the `UNSAFE_` prefix.";
94
+
95
+ async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
96
+ return check(not(isVendoredOrBundled()), new class extends JavaScriptVisitor<ExecutionContext> {
97
+ override async visitClassDeclaration(decl: J.ClassDeclaration, ctx: ExecutionContext): Promise<J | undefined> {
98
+ const cd = await super.visitClassDeclaration(decl, ctx) as J.ClassDeclaration;
99
+ if (!extendsReactComponentByName(cd)) return cd;
100
+ // React never calls the legacy lifecycles on a class with these, so moving them would make dead code live.
101
+ if (cd.body.statements.some(s => s.element.kind === J.Kind.MethodDeclaration
102
+ && ['getDerivedStateFromProps', 'getSnapshotBeforeUpdate'].includes((s.element as J.MethodDeclaration).name.simpleName))) return cd;
103
+
104
+ let statements = [...cd.body.statements];
105
+ const find = (name: string) => statements.findIndex(s =>
106
+ s.element.kind === J.Kind.MethodDeclaration && lifecycleName(s.element as J.MethodDeclaration) === name);
107
+ const method = (i: number) => statements[i].element as J.MethodDeclaration;
108
+ let changed = false;
109
+
110
+ const willMount = find('componentWillMount');
111
+ if (willMount >= 0 && method(willMount).body) {
112
+ const replaced = await this.migrateWillMount(cd, statements, willMount, find('componentDidMount'));
113
+ if (replaced) {
114
+ statements = replaced;
115
+ changed = true;
116
+ }
117
+ }
118
+
119
+ const willReceive = find('componentWillReceiveProps');
120
+ if (willReceive >= 0 && find('componentDidUpdate') < 0 && !this.declaresMemberIn(statements, 'componentDidUpdate')
121
+ && method(willReceive).body) {
122
+ const migrated = await this.migrateWillReceiveProps(method(willReceive));
123
+ if (migrated) {
124
+ statements[willReceive] = {...statements[willReceive], element: migrated};
125
+ changed = true;
126
+ }
127
+ }
128
+
129
+ return changed ? {...cd, body: {...cd.body, statements}} as J.ClassDeclaration : cd;
130
+ }
131
+
132
+ /** The class members after moving `componentWillMount`, or `undefined` if it cannot be moved safely. */
133
+ private async migrateWillMount(cd: J.ClassDeclaration, statements: J.RightPadded<any>[], index: number, didMount: number) {
134
+ const method = statements[index].element as J.MethodDeclaration;
135
+ const body = method.body!;
136
+
137
+ // `componentWillMount() { this.setState({...}); }` -> `state = {...};`
138
+ const only = body.statements.length === 1 ? body.statements[0].element : undefined;
139
+ const call = only?.kind === J.Kind.MethodInvocation ? only as J.MethodInvocation : undefined;
140
+ if (call && isSetState(call)) {
141
+ const args = call.arguments.elements.map(a => a.element);
142
+ const hasState = statements.some(s => this.declaresMember(s.element, 'state'));
143
+ const hasConstructor = statements.some(s => s.element.kind === J.Kind.MethodDeclaration
144
+ && (s.element as J.MethodDeclaration).name.simpleName === 'constructor');
145
+ if (args.length !== 1 || args[0].kind !== J.Kind.NewClass || hasState || hasConstructor) return undefined;
146
+ const sample = await template`class Sample { state = ${args[0]}; }`.apply(cd, this.cursor) as J.ClassDeclaration | undefined;
147
+ if (!await usesThisOnlyForPropsAndContext(args[0])) return undefined;
148
+ const field = sample?.body.statements[0];
149
+ if (!field) return undefined;
150
+ const out = [...statements];
151
+ out[index] = {...field, element: {...field.element, prefix: method.prefix}};
152
+ return out;
153
+ }
154
+
155
+ // Otherwise it must not read or write state, since that is what makes the later start observable.
156
+ if (await anyNode(body, n => isSetState(n) || readsThisState(n) || isReturn(n))
157
+ || !await usesThisOnlyForPropsAndContext(body)) return undefined;
158
+ // An arrow-function field of that name would shadow the method we create.
159
+ if (this.declaresMemberIn(statements, 'componentDidMount')) return undefined;
160
+
161
+ const out = [...statements];
162
+ if (didMount < 0) {
163
+ out[index] = {...out[index], element: {...method, name: {...method.name, simpleName: 'componentDidMount'}}};
164
+ return out;
165
+ }
166
+ const target = out[didMount].element as J.MethodDeclaration;
167
+ if (!target.body) return undefined;
168
+ // Joining the bodies must not redeclare a name, and `await` needs an async method to sit in.
169
+ if (isAsync(method) || isAsync(target)) return undefined;
170
+ // Nor may a name declared by one body be used by the other: the moved local would capture an outer
171
+ // name the other reads, or sit in its temporal dead zone.
172
+ const [mineDeclared, mineUsed] = [namesDeclaredWithin(body), namesUsedWithin(body)];
173
+ const [theirsDeclared, theirsUsed] = [namesDeclaredWithin(target.body), namesUsedWithin(target.body)];
174
+ const clash = (declared: ReadonlySet<string>, ...others: ReadonlySet<string>[]) =>
175
+ [...declared].some(n => others.some(o => o.has(n)));
176
+ if (clash(mineDeclared, theirsDeclared, theirsUsed) || clash(theirsDeclared, mineUsed)) return undefined;
177
+ // A pattern declaration (`const {a} = x`) or a function declaration may bind names the sets do not list.
178
+ if (await anyNode(body, n => n.kind === J.Kind.MethodDeclaration || n.kind === JS.Kind.ArrowFunction)) return undefined;
179
+ // The merged method takes the removed one's place, so it also takes its spacing.
180
+ const prefix = index < didMount ? method.prefix : target.prefix;
181
+ out[didMount] = {...out[didMount], element: {...target, prefix, body: {...target.body, statements: [...body.statements, ...target.body.statements]}}};
182
+ out.splice(index, 1);
183
+ return out;
184
+ }
185
+
186
+ private declaresMemberIn(statements: J.RightPadded<any>[], name: string): boolean {
187
+ return statements.some(s => this.declaresMember(s.element, name));
188
+ }
189
+
190
+ private declaresMember(member: J, name: string): boolean {
191
+ return member.kind === J.Kind.VariableDeclarations
192
+ && (member as J.VariableDeclarations).variables.some(v => (v.element.name as J.Identifier).simpleName === name);
193
+ }
194
+
195
+ /** `componentDidUpdate(prevProps)` for a guarded `componentWillReceiveProps(next)`, if it qualifies. */
196
+ private async migrateWillReceiveProps(method: J.MethodDeclaration): Promise<J.MethodDeclaration | undefined> {
197
+ const param = method.parameters.elements[0]?.element;
198
+ if (method.parameters.elements.length !== 1 || param?.kind !== J.Kind.VariableDeclarations) return undefined;
199
+ const variable = (param as J.VariableDeclarations).variables[0]?.element;
200
+ if (!variable || variable.name.kind !== J.Kind.Identifier) return undefined;
201
+ const next = (variable.name as J.Identifier).simpleName;
202
+ const body = method.body!;
203
+
204
+ if (body.statements.length !== 1 || body.statements[0].element.kind !== J.Kind.If) return undefined;
205
+ const guard = body.statements[0].element as J.If;
206
+ // `componentDidUpdate` also runs after the component's own updates, when the props did not change,
207
+ // so only a guard that holds when they did change keeps the body from running more often.
208
+ if (guard.elsePart || !await isChangeGuard(guard.ifCondition.tree.element, next)) return undefined;
209
+ if (await anyNode(body, writesThisMember)) return undefined;
210
+ const mentionsNext = (n: J) => n.kind === J.Kind.Identifier && (n as J.Identifier).simpleName === next;
211
+ if (!await anyNode(guard.ifCondition, mentionsNext) || !await anyNode(guard.ifCondition, readsThisProps)) return undefined;
212
+ if (await anyNode(body, n => isSetState(n) || isReturn(n) || (n.kind === J.Kind.Identifier && (n as J.Identifier).simpleName === 'prevProps'))) return undefined;
213
+
214
+ const thisProps = await template`this.props`.apply(method, this.cursor) as J.FieldAccess | undefined;
215
+ if (!thisProps) return undefined;
216
+ // `next` may only appear as `next.x` outside any nested function. Any other spelling is a method
217
+ // name, an attribute, a shadowing binding or an alias, and a read inside a callback would see the
218
+ // props at the time it runs rather than the ones that were just received.
219
+ let unsafe = false;
220
+ const swapped = await new class extends JavaScriptVisitor<ExecutionContext> {
221
+ protected override async visitFieldAccess(fa: J.FieldAccess, c: ExecutionContext): Promise<J | undefined> {
222
+ if (isThis(fa.target) && fa.name.element.simpleName === 'props') {
223
+ return {...(fa.name.element), simpleName: 'prevProps', prefix: fa.prefix} as J.Identifier;
224
+ }
225
+ return super.visitFieldAccess(fa, c);
226
+ }
227
+
228
+ protected override async visitIdentifier(id: J.Identifier): Promise<J | undefined> {
229
+ if (id.simpleName !== next) return id;
230
+ const parent = this.cursor.parentTree()?.value as J | undefined;
231
+ const isTarget = parent?.kind === J.Kind.FieldAccess && (parent as J.FieldAccess).target === id;
232
+ if (!isTarget || this.insideNestedScope()) {
233
+ unsafe = true;
234
+ return id;
235
+ }
236
+ return {...thisProps, id: randomId(), prefix: id.prefix} as J.FieldAccess;
237
+ }
238
+
239
+ private insideNestedScope(): boolean {
240
+ for (let c: any = this.cursor.parent; c; c = c.parent) {
241
+ const k = c.value?.kind;
242
+ if (k === J.Kind.Lambda || k === J.Kind.MethodDeclaration || k === JS.Kind.ArrowFunction
243
+ || k === J.Kind.ClassDeclaration || k === J.Kind.NewClass) return true;
244
+ }
245
+ return false;
246
+ }
247
+ }().visit(body, {} as ExecutionContext) as J.Block;
248
+ if (unsafe) return undefined;
249
+
250
+ const renamedParam = {
251
+ ...(param as J.VariableDeclarations),
252
+ variables: (param as J.VariableDeclarations).variables.map(v => ({
253
+ ...v, element: {...v.element, name: {...(v.element.name as J.Identifier), simpleName: 'prevProps'}},
254
+ })),
255
+ };
256
+ return {
257
+ ...method,
258
+ name: {...method.name, simpleName: 'componentDidUpdate'},
259
+ parameters: {...method.parameters, elements: [{...method.parameters.elements[0], element: renamedParam}]},
260
+ body: swapped,
261
+ } as J.MethodDeclaration;
262
+ }
263
+ }());
264
+ }
265
+ }
@@ -0,0 +1,150 @@
1
+ import {ExecutionContext, Recipe, TreeVisitor} from "@openrewrite/rewrite";
2
+ import {getMemberKeyName, isArray, isLiteral, isMember, isObject, Json, JsonVisitor} from "@openrewrite/rewrite/json";
3
+ import {create} from "mutative";
4
+
5
+ type ConfigKind = 'tsconfig' | 'babel' | 'eslint';
6
+
7
+ const BABEL_JSX_PRESETS = new Set([
8
+ '@babel/preset-react',
9
+ '@babel/react',
10
+ '@babel/plugin-transform-react-jsx',
11
+ ]);
12
+ const ESLINT_RULES = new Set(['react/react-in-jsx-scope', 'react/jsx-uses-react']);
13
+
14
+ function configKind(sourcePath: string): ConfigKind | undefined {
15
+ const name = sourcePath.split('/').pop()!;
16
+ if (/^(ts|js)config(\.[\w-]+)?\.json$/.test(name)) return 'tsconfig';
17
+ if (name === '.babelrc' || name === '.babelrc.json' || name === 'babel.config.json') return 'babel';
18
+ if (name === '.eslintrc' || name === '.eslintrc.json') return 'eslint';
19
+ return undefined;
20
+ }
21
+
22
+ function withString(literal: Json.Literal, value: string): Json.Literal {
23
+ const quote = literal.source.startsWith("'") ? "'" : '"';
24
+ return create(literal, draft => {
25
+ draft.source = `${quote}${value}${quote}`;
26
+ draft.value = value;
27
+ });
28
+ }
29
+
30
+ function mapMembers(object: Json.Object, fn: (member: Json.Member) => Json.Member): Json.Object {
31
+ let changed = false;
32
+ const members = object.members.map(padded => {
33
+ const element = padded.element;
34
+ if (!isMember(element)) return padded;
35
+ const updated = fn(element);
36
+ if (updated === element) return padded;
37
+ changed = true;
38
+ return create(padded, draft => {
39
+ draft.element = updated as any;
40
+ });
41
+ });
42
+ return changed ? create(object, draft => {
43
+ draft.members = members as any;
44
+ }) : object;
45
+ }
46
+
47
+ function withValue(member: Json.Member, value: Json.Value): Json.Member {
48
+ return create(member, draft => {
49
+ draft.value = value as any;
50
+ });
51
+ }
52
+
53
+ /**
54
+ * Moves JSX configuration to the new JSX transform introduced with React 17 (and backported
55
+ * to 16.14), which compiles JSX without `React` in scope.
56
+ *
57
+ * - `tsconfig.json`/`jsconfig.json`: `"jsx": "react"` becomes `"react-jsx"` and
58
+ * `"react-dev"` becomes `"react-jsxdev"`.
59
+ * It is skipped when `jsxFactory` or `jsxFragmentFactory` is set, which TypeScript rejects
60
+ * with `react-jsx` (TS5089).
61
+ * - Babel JSON config: `"runtime": "classic"` on `@babel/preset-react` becomes `"automatic"`,
62
+ * unless `pragma` or `pragmaFrag` is set, which the automatic runtime rejects.
63
+ * - ESLint JSON config: `react/react-in-jsx-scope` and `react/jsx-uses-react` are turned off.
64
+ *
65
+ * Only values that are explicitly configured are changed. Configuration that is absent, or
66
+ * written in JavaScript, is left alone.
67
+ *
68
+ * @see https://legacy.reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html
69
+ */
70
+ export class UseNewJsxTransform extends Recipe {
71
+ readonly name = "org.openrewrite.react.17.use-new-jsx-transform";
72
+ readonly displayName = "Use the new JSX transform";
73
+ readonly description = "Switch `tsconfig.json`, Babel and ESLint JSON configuration to the new JSX transform introduced in React 17, so JSX no longer needs `React` in scope.";
74
+
75
+ async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
76
+ return new class extends JsonVisitor<ExecutionContext> {
77
+ private kind?: ConfigKind;
78
+
79
+ protected override async visitDocument(document: Json.Document, ctx: ExecutionContext): Promise<Json | undefined> {
80
+ this.kind = configKind(document.sourcePath);
81
+ if (!this.kind) return document;
82
+ return super.visitDocument(document, ctx);
83
+ }
84
+
85
+ protected override async visitMember(member: Json.Member, ctx: ExecutionContext): Promise<Json | undefined> {
86
+ const visited = await super.visitMember(member, ctx) as Json.Member;
87
+ if (!isObject(visited.value)) return visited;
88
+ const key = getMemberKeyName(visited);
89
+ if (this.kind === 'tsconfig' && key === 'compilerOptions') {
90
+ const names = visited.value.members.map(m => isMember(m.element) ? getMemberKeyName(m.element) : undefined);
91
+ // TS5089: `jsxFactory`/`jsxFragmentFactory` cannot be combined with `react-jsx`
92
+ if (names.includes('jsxFactory') || names.includes('jsxFragmentFactory')) return visited;
93
+ return withValue(visited, mapMembers(visited.value, m => this.updateJsx(m)));
94
+ }
95
+ if (this.kind === 'eslint' && key === 'rules') {
96
+ return withValue(visited, mapMembers(visited.value, m => this.turnRuleOff(m)));
97
+ }
98
+ return visited;
99
+ }
100
+
101
+ protected override async visitArray(array: Json.Array, ctx: ExecutionContext): Promise<Json | undefined> {
102
+ const visited = await super.visitArray(array, ctx) as Json.Array;
103
+ if (this.kind !== 'babel') return visited;
104
+ const [name, options] = visited.values.map(v => v.element);
105
+ if (!name || !options || !isLiteral(name) || !BABEL_JSX_PRESETS.has(name.value) || !isObject(options)) return visited;
106
+ const keys = options.members.map(m => isMember(m.element) ? getMemberKeyName(m.element) : undefined);
107
+ if (keys.includes('pragma') || keys.includes('pragmaFrag')) return visited;
108
+ const updated = mapMembers(options, m => {
109
+ const value = m.value;
110
+ return getMemberKeyName(m) === 'runtime' && isLiteral(value) && value.value === 'classic'
111
+ ? withValue(m, withString(value, 'automatic')) : m;
112
+ });
113
+ if (updated === options) return visited;
114
+ return create(visited, draft => {
115
+ draft.values[1] = create(visited.values[1], d => {
116
+ d.element = updated as any;
117
+ }) as any;
118
+ });
119
+ }
120
+
121
+ private updateJsx(member: Json.Member): Json.Member {
122
+ const value = member.value;
123
+ if (getMemberKeyName(member) !== 'jsx' || !isLiteral(value)) return member;
124
+ if (value.value === 'react') return withValue(member, withString(value, 'react-jsx'));
125
+ if (value.value === 'react-dev') return withValue(member, withString(value, 'react-jsxdev'));
126
+ return member;
127
+ }
128
+
129
+ private turnRuleOff(member: Json.Member): Json.Member {
130
+ const key = getMemberKeyName(member);
131
+ if (!key || !ESLINT_RULES.has(key)) return member;
132
+ const value = member.value;
133
+ const isOff = (v: any) => v === 'off' || v === 0;
134
+ if (isLiteral(value)) {
135
+ return isOff(value.value) ? member : withValue(member, withString(value, 'off'));
136
+ }
137
+ if (isArray(value)) {
138
+ const first = value.values[0]?.element;
139
+ if (!first || !isLiteral(first) || isOff(first.value)) return member;
140
+ return withValue(member, create(value, draft => {
141
+ draft.values[0] = create(value.values[0], d => {
142
+ d.element = withString(first, 'off') as any;
143
+ }) as any;
144
+ }));
145
+ }
146
+ return member;
147
+ }
148
+ };
149
+ }
150
+ }
@@ -0,0 +1,235 @@
1
+ import {ExecutionContext, Recipe, TreeVisitor, check, not, randomId} from "@openrewrite/rewrite";
2
+ import {isVendoredOrBundled, JavaScriptVisitor, JS, maybeAddImport, template} from "@openrewrite/rewrite/javascript";
3
+ import {J, Statement} from "@openrewrite/rewrite/java";
4
+ import {create} from "mutative";
5
+ import {baseTypeArguments, extendsReactComponentByName} from "../util/react-class";
6
+ import {anyNode, isIdentifierNamed, isThis} from "../util/tree-search";
7
+
8
+ const FC_NAMES = new Set(['FC', 'FunctionComponent']);
9
+
10
+ /** The name of the type a parameter is annotated with, when it is a plain identifier. */
11
+ function annotatedTypeName(param: J.VariableDeclarations): string | undefined {
12
+ const type = (param.typeExpression as JS.TypeInfo | undefined)?.typeIdentifier;
13
+ return type?.kind === J.Kind.Identifier ? (type as J.Identifier).simpleName : undefined;
14
+ }
15
+
16
+ /** The props type argument of `FC<Props>` / `React.FC<Props>`, when it is a plain identifier. */
17
+ function fcPropsTypeName(decl: J.VariableDeclarations): string | undefined {
18
+ const type = (decl.typeExpression as JS.TypeInfo | undefined)?.typeIdentifier;
19
+ if (type?.kind !== J.Kind.ParameterizedType) return undefined;
20
+ const parameterized = type as J.ParameterizedType;
21
+ const base = parameterized.class;
22
+ const baseName = base.kind === J.Kind.Identifier ? (base as J.Identifier).simpleName
23
+ : base.kind === J.Kind.FieldAccess ? (base as J.FieldAccess).name.element.simpleName : undefined;
24
+ if (!baseName || !FC_NAMES.has(baseName)) return undefined;
25
+ const arg = parameterized.typeParameters?.elements[0]?.element;
26
+ return arg?.kind === J.Kind.Identifier ? (arg as J.Identifier).simpleName : undefined;
27
+ }
28
+
29
+ /** The property name a member declares, whether written as `children` or `'children'`. */
30
+ function memberName(name: J): string | undefined {
31
+ if (name.kind === J.Kind.Identifier) return (name as J.Identifier).simpleName;
32
+ if (name.kind === J.Kind.Literal) return String((name as J.Literal).value);
33
+ return undefined;
34
+ }
35
+
36
+ /** The props type argument of `Component<Props>` / `React.PureComponent<Props>`, when it is a plain identifier. */
37
+ function classPropsTypeName(decl: J.ClassDeclaration): string | undefined {
38
+ if (!extendsReactComponentByName(decl)) return undefined;
39
+ const arg = baseTypeArguments(decl.extends?.element)?.elements[0]?.element;
40
+ return arg?.kind === J.Kind.Identifier ? (arg as J.Identifier).simpleName : undefined;
41
+ }
42
+
43
+ /** Whether a class component reads `this.props.children` or destructures `children` from `this.props`. */
44
+ async function classReadsChildren(body: J): Promise<boolean> {
45
+ const patterns: J[] = [];
46
+ const direct = await anyNode(body, n => {
47
+ if (n.kind === J.Kind.FieldAccess) {
48
+ const fa = n as J.FieldAccess;
49
+ const t = fa.target;
50
+ return fa.name.element.simpleName === 'children' && t.kind === J.Kind.FieldAccess
51
+ && isThis((t as J.FieldAccess).target) && (t as J.FieldAccess).name.element.simpleName === 'props';
52
+ }
53
+ if (n.kind === J.Kind.VariableDeclarations) {
54
+ const v = (n as J.VariableDeclarations).variables[0]?.element;
55
+ const init = v?.initializer?.element;
56
+ if (v && init?.kind === J.Kind.FieldAccess && isThis((init as J.FieldAccess).target)
57
+ && (init as J.FieldAccess).name.element.simpleName === 'props' && v.name.kind !== J.Kind.Identifier) {
58
+ patterns.push(v.name as unknown as J);
59
+ }
60
+ }
61
+ return false;
62
+ });
63
+ if (direct) return true;
64
+ for (const pattern of patterns) if (await anyNode(pattern, n => isIdentifierNamed(n, 'children'))) return true;
65
+ return false;
66
+ }
67
+
68
+ /** Whether a component reads `children`, by destructuring its first parameter or through `props.children`. */
69
+ async function readsChildren(param: J.VariableDeclarations | undefined, body: J | undefined): Promise<boolean> {
70
+ const name = param?.variables[0]?.element.name;
71
+ if (!name) return false;
72
+ if (name.kind === J.Kind.Identifier) {
73
+ const props = (name as J.Identifier).simpleName;
74
+ return anyNode(body, n => n.kind === J.Kind.FieldAccess
75
+ && isIdentifierNamed((n as J.FieldAccess).target, props) && (n as J.FieldAccess).name.element.simpleName === 'children');
76
+ }
77
+ return anyNode(name as unknown as J, n => isIdentifierNamed(n, 'children'));
78
+ }
79
+
80
+ /** Names of locally declared props types that a component reads `children` from but does not declare. */
81
+ async function findPropsNeedingChildren(cu: JS.CompilationUnit): Promise<Set<string>> {
82
+ const names = new Set<string>();
83
+ /** Records `type` when the component's first parameter is a declaration that reads `children` from `body`. */
84
+ const consider = async (param: J | undefined, type: string | undefined, body: J | undefined) => {
85
+ if (type && param?.kind === J.Kind.VariableDeclarations && await readsChildren(param as J.VariableDeclarations, body)) names.add(type);
86
+ };
87
+ const annotated = (param: J | undefined) =>
88
+ param?.kind === J.Kind.VariableDeclarations ? annotatedTypeName(param as J.VariableDeclarations) : undefined;
89
+
90
+ await new class extends JavaScriptVisitor<ExecutionContext> {
91
+ protected override async visitMethodDeclaration(method: J.MethodDeclaration, ctx: ExecutionContext): Promise<J | undefined> {
92
+ const param = method.parameters.elements[0]?.element;
93
+ await consider(param, annotated(param), method.body);
94
+ return super.visitMethodDeclaration(method, ctx);
95
+ }
96
+
97
+ protected override async visitArrowFunction(arrow: JS.ArrowFunction, ctx: ExecutionContext): Promise<J | undefined> {
98
+ const param = arrow.lambda.parameters.parameters[0]?.element;
99
+ await consider(param, annotated(param), arrow.lambda.body as J);
100
+ return super.visitArrowFunction(arrow, ctx);
101
+ }
102
+
103
+ protected override async visitClassDeclaration(decl: J.ClassDeclaration, ctx: ExecutionContext): Promise<J | undefined> {
104
+ const type = classPropsTypeName(decl);
105
+ if (type && await classReadsChildren(decl.body)) names.add(type);
106
+ return super.visitClassDeclaration(decl, ctx);
107
+ }
108
+
109
+ protected override async visitVariableDeclarations(decl: J.VariableDeclarations, ctx: ExecutionContext): Promise<J | undefined> {
110
+ const init = decl.variables[0]?.element.initializer?.element;
111
+ if (init?.kind === JS.Kind.ArrowFunction) {
112
+ const arrow = init as JS.ArrowFunction;
113
+ await consider(arrow.lambda.parameters.parameters[0]?.element, fcPropsTypeName(decl), arrow.lambda.body as J);
114
+ }
115
+ return super.visitVariableDeclarations(decl, ctx);
116
+ }
117
+ }().visit(cu, {} as ExecutionContext);
118
+ return names;
119
+ }
120
+
121
+ /**
122
+ * Adds `children?: ReactNode` to props types that components read `children` from.
123
+ *
124
+ * `@types/react` 18 removed the implicit `children` prop from `React.FC` and `VoidFunctionComponent`
125
+ * was folded away with it, so components that use `children` without declaring it stop compiling.
126
+ *
127
+ * Only props types declared in the same file as an `interface` (without `extends`) or an object
128
+ * type alias are changed. Props types that are imported, composed or extended are left alone,
129
+ * since they may already provide `children`.
130
+ *
131
+ * @see https://react.dev/blog/2022/03/08/react-18-upgrade-guide#updates-to-typescript-definitions
132
+ */
133
+ export class AddChildrenToProps extends Recipe {
134
+ readonly name = "org.openrewrite.react.18.add-children-to-props";
135
+ readonly displayName = "Declare `children` on props types";
136
+ readonly description = "Adds `children?: ReactNode` to locally declared props types of components that read `children`, which `@types/react` 18 no longer provides implicitly.";
137
+
138
+ async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
139
+ return check(not(isVendoredOrBundled()), new class extends JavaScriptVisitor<ExecutionContext> {
140
+ private needing = new Set<string>();
141
+ private reactNode?: string;
142
+ private sample?: { first: J.RightPadded<Statement>; member: J.RightPadded<Statement> };
143
+
144
+ override async visitJsCompilationUnit(cu: JS.CompilationUnit, ctx: ExecutionContext): Promise<J | undefined> {
145
+ this.needing = await findPropsNeedingChildren(cu);
146
+ this.reactNode = undefined;
147
+ this.sample = undefined;
148
+ if (this.needing.size === 0) return cu;
149
+ return super.visitJsCompilationUnit(cu, ctx);
150
+ }
151
+
152
+ protected override async visitClassDeclaration(decl: J.ClassDeclaration, ctx: ExecutionContext): Promise<J | undefined> {
153
+ const visited = await super.visitClassDeclaration(decl, ctx) as J.ClassDeclaration;
154
+ if (visited.classKind.type !== 'Interface' || !this.needing.has(visited.name.simpleName)
155
+ || visited.extends || visited.implements) return visited;
156
+ const body = await this.withChildren(visited.body);
157
+ return body === visited.body ? visited : create(visited, draft => {
158
+ draft.body = body as any;
159
+ });
160
+ }
161
+
162
+ protected override async visitTypeDeclaration(decl: JS.TypeDeclaration, ctx: ExecutionContext): Promise<J | undefined> {
163
+ const visited = await super.visitTypeDeclaration(decl, ctx) as JS.TypeDeclaration;
164
+ const init = visited.initializer.element;
165
+ if (!this.needing.has(visited.name.element.simpleName) || init.kind !== JS.Kind.TypeLiteral) return visited;
166
+ const literal = init as JS.TypeLiteral;
167
+ const members = await this.withChildren(literal.members);
168
+ return members === literal.members ? visited : create(visited, draft => {
169
+ (draft.initializer.element as any).members = members;
170
+ });
171
+ }
172
+
173
+ /** Appends `children?: ReactNode` to a members block, matching how its members are separated. */
174
+ private async withChildren(block: J.Block): Promise<J.Block> {
175
+ const statements = block.statements;
176
+ const declares = statements.some(s => s.element.kind === J.Kind.VariableDeclarations
177
+ && (s.element as J.VariableDeclarations).variables.some(v => memberName(v.element.name as J) === 'children'));
178
+ if (declares) return block;
179
+
180
+ // Import `ReactNode` and use the name the import ends up with, which differs when `ReactNode` is already taken locally.
181
+ this.reactNode ??= maybeAddImport(this, {module: 'react', member: 'ReactNode', onlyIfReferenced: false}) ?? 'ReactNode';
182
+ // `template` yields real, parsed members: the first carries the separator marker (`;`) and the second is `children`.
183
+ this.sample ??= await this.sampleMembers(block, this.reactNode);
184
+ if (statements.length === 0) return this.intoEmpty(block, this.sample.member);
185
+ const last = statements[statements.length - 1];
186
+ const separated = (rp: J.RightPadded<any>) => rp.markers.markers.length > 0;
187
+ const fresh = (markers: typeof last.markers) => ({
188
+ ...markers, id: randomId(), markers: markers.markers.map(m => ({...m, id: randomId()})),
189
+ });
190
+
191
+ // The separator style in use: the last member's own, else any member's, else `;` for a one-line block.
192
+ const lastSeparated = separated(last);
193
+ const style = lastSeparated ? last.markers
194
+ : statements.find(separated)?.markers ?? (last.element.prefix.whitespace.includes('\n') ? undefined : this.sample.first.markers);
195
+
196
+ // `children` ends the list: it takes the separator the old last member had, or else the old last member gains one.
197
+ const child = create(this.sample.member.element, draft => {
198
+ draft.prefix = {...last.element.prefix, comments: []} as any;
199
+ });
200
+ const added: J.RightPadded<Statement> = {...this.sample.member, element: child, markers: lastSeparated ? fresh(style!) : this.sample.member.markers};
201
+ const previous = lastSeparated || !style ? last : {...last, markers: fresh(style)};
202
+ return create(block, draft => {
203
+ draft.statements = [...statements.slice(0, -1), previous, added] as any;
204
+ });
205
+ }
206
+
207
+ /** `children` as the only member: on its own indented line when the block spans lines, else inside the braces on one line. */
208
+ private intoEmpty(block: J.Block, member: J.RightPadded<Statement>): J.Block {
209
+ const multiline = block.end.whitespace.includes('\n');
210
+ const indent = multiline ? block.end.whitespace.slice(block.end.whitespace.lastIndexOf('\n')) + ' ' : ' ';
211
+ const child = create(member.element, draft => {
212
+ draft.prefix = {...member.element.prefix, whitespace: indent, comments: []} as any;
213
+ });
214
+ return create(block, draft => {
215
+ draft.statements = [{...member, element: child}] as any;
216
+ if (!multiline) draft.end = {...block.end, whitespace: ' '} as any;
217
+ });
218
+ }
219
+
220
+ private async sampleMembers(anchor: J.Block, reactNode: string) {
221
+ const parsed = await template`interface Sample { first: string; children?: ReactNode }`.apply(anchor, this.cursor) as J.ClassDeclaration;
222
+ const [first, member] = parsed.body.statements;
223
+ if (reactNode === 'ReactNode') return {first, member};
224
+ const renamed = await new class extends JavaScriptVisitor<ExecutionContext> {
225
+ protected override async visitIdentifier(id: J.Identifier, ctx: ExecutionContext): Promise<J | undefined> {
226
+ return id.simpleName === 'ReactNode' ? create(id, draft => {
227
+ draft.simpleName = reactNode;
228
+ }) : id;
229
+ }
230
+ }().visit(member.element, {} as ExecutionContext) as Statement;
231
+ return {first, member: {...member, element: renamed}};
232
+ }
233
+ }());
234
+ }
235
+ }