@openrewrite/recipes-react 0.17.0 → 0.19.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 (109) hide show
  1. package/dist/index.d.ts +1 -1
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +9 -5
  4. package/dist/index.js.map +1 -1
  5. package/dist/migration/cra-to-vite/find-cra-config-blockers.d.ts.map +1 -1
  6. package/dist/migration/cra-to-vite/find-cra-config-blockers.js +3 -5
  7. package/dist/migration/cra-to-vite/find-cra-config-blockers.js.map +1 -1
  8. package/dist/migration/cra-to-vite/update-react-app-env-types.d.ts.map +1 -1
  9. package/dist/migration/cra-to-vite/update-react-app-env-types.js +5 -2
  10. package/dist/migration/cra-to-vite/update-react-app-env-types.js.map +1 -1
  11. package/dist/react18/replace-unmount-component-at-node.d.ts.map +1 -1
  12. package/dist/react18/replace-unmount-component-at-node.js +8 -1
  13. package/dist/react18/replace-unmount-component-at-node.js.map +1 -1
  14. package/dist/react19/find-legacy-context-api.d.ts.map +1 -1
  15. package/dist/react19/find-legacy-context-api.js +21 -38
  16. package/dist/react19/find-legacy-context-api.js.map +1 -1
  17. package/dist/react19/no-implicit-ref-callback-return.d.ts.map +1 -1
  18. package/dist/react19/no-implicit-ref-callback-return.js +25 -5
  19. package/dist/react19/no-implicit-ref-callback-return.js.map +1 -1
  20. package/dist/{react18 → react19}/remove-unstable-batched-updates.d.ts +2 -2
  21. package/dist/react19/remove-unstable-batched-updates.d.ts.map +1 -0
  22. package/dist/react19/remove-unstable-batched-updates.js +295 -0
  23. package/dist/react19/remove-unstable-batched-updates.js.map +1 -0
  24. package/dist/react19/replace-default-props.d.ts +1 -0
  25. package/dist/react19/replace-default-props.d.ts.map +1 -1
  26. package/dist/react19/replace-default-props.js +198 -151
  27. package/dist/react19/replace-default-props.js.map +1 -1
  28. package/dist/react19/replace-react-shallow-renderer.d.ts.map +1 -1
  29. package/dist/react19/replace-react-shallow-renderer.js +10 -25
  30. package/dist/react19/replace-react-shallow-renderer.js.map +1 -1
  31. package/dist/refactoring/class-to-functional.d.ts.map +1 -1
  32. package/dist/refactoring/class-to-functional.js +2 -0
  33. package/dist/refactoring/class-to-functional.js.map +1 -1
  34. package/dist/refactoring/create-class-to-es6.d.ts.map +1 -1
  35. package/dist/refactoring/create-class-to-es6.js +14 -49
  36. package/dist/refactoring/create-class-to-es6.js.map +1 -1
  37. package/dist/search/find-function-component-default-props.d.ts.map +1 -1
  38. package/dist/search/find-function-component-default-props.js +6 -15
  39. package/dist/search/find-function-component-default-props.js.map +1 -1
  40. package/dist/search/find-redux-stores.d.ts +12 -0
  41. package/dist/search/find-redux-stores.d.ts.map +1 -0
  42. package/dist/search/find-redux-stores.js +87 -0
  43. package/dist/search/find-redux-stores.js.map +1 -0
  44. package/dist/simplify-object-pattern-property.d.ts.map +1 -1
  45. package/dist/simplify-object-pattern-property.js +14 -21
  46. package/dist/simplify-object-pattern-property.js.map +1 -1
  47. package/dist/simplify-react-imports.d.ts.map +1 -1
  48. package/dist/simplify-react-imports.js +10 -59
  49. package/dist/simplify-react-imports.js.map +1 -1
  50. package/dist/testing/enzyme-host-components.d.ts +2 -1
  51. package/dist/testing/enzyme-host-components.d.ts.map +1 -1
  52. package/dist/testing/enzyme-host-components.js +33 -2
  53. package/dist/testing/enzyme-host-components.js.map +1 -1
  54. package/dist/testing/enzyme-to-react-testing-library.d.ts +10 -1
  55. package/dist/testing/enzyme-to-react-testing-library.d.ts.map +1 -1
  56. package/dist/testing/enzyme-to-react-testing-library.js +83 -24
  57. package/dist/testing/enzyme-to-react-testing-library.js.map +1 -1
  58. package/dist/testing/enzyme-wrapper-scope.d.ts +4 -1
  59. package/dist/testing/enzyme-wrapper-scope.d.ts.map +1 -1
  60. package/dist/testing/enzyme-wrapper-scope.js +36 -7
  61. package/dist/testing/enzyme-wrapper-scope.js.map +1 -1
  62. package/dist/util/java-recipe-proxy.d.ts +2 -0
  63. package/dist/util/java-recipe-proxy.d.ts.map +1 -1
  64. package/dist/util/java-recipe-proxy.js +14 -2
  65. package/dist/util/java-recipe-proxy.js.map +1 -1
  66. package/dist/util/reindent.d.ts +5 -0
  67. package/dist/util/reindent.d.ts.map +1 -0
  68. package/dist/util/reindent.js +44 -0
  69. package/dist/util/reindent.js.map +1 -0
  70. package/dist/zustand/redux-stores.d.ts +74 -0
  71. package/dist/zustand/redux-stores.d.ts.map +1 -0
  72. package/dist/zustand/redux-stores.js +439 -0
  73. package/dist/zustand/redux-stores.js.map +1 -0
  74. package/dist/zustand/redux-to-zustand.d.ts +76 -0
  75. package/dist/zustand/redux-to-zustand.d.ts.map +1 -0
  76. package/dist/zustand/redux-to-zustand.js +654 -0
  77. package/dist/zustand/redux-to-zustand.js.map +1 -0
  78. package/dist/zustand/zustand-plan.d.ts +97 -0
  79. package/dist/zustand/zustand-plan.d.ts.map +1 -0
  80. package/dist/zustand/zustand-plan.js +833 -0
  81. package/dist/zustand/zustand-plan.js.map +1 -0
  82. package/package.json +1 -1
  83. package/src/index.ts +7 -3
  84. package/src/migration/cra-to-vite/find-cra-config-blockers.ts +3 -5
  85. package/src/migration/cra-to-vite/update-react-app-env-types.ts +3 -3
  86. package/src/react18/replace-unmount-component-at-node.ts +13 -2
  87. package/src/react19/find-legacy-context-api.ts +21 -42
  88. package/src/react19/no-implicit-ref-callback-return.ts +34 -8
  89. package/src/react19/remove-unstable-batched-updates.ts +301 -0
  90. package/src/react19/replace-default-props.ts +212 -159
  91. package/src/react19/replace-react-shallow-renderer.ts +13 -36
  92. package/src/refactoring/class-to-functional.ts +3 -1
  93. package/src/refactoring/create-class-to-es6.ts +12 -63
  94. package/src/search/find-function-component-default-props.ts +8 -10
  95. package/src/search/find-redux-stores.ts +76 -0
  96. package/src/simplify-object-pattern-property.ts +22 -49
  97. package/src/simplify-react-imports.ts +12 -66
  98. package/src/testing/enzyme-host-components.ts +38 -3
  99. package/src/testing/enzyme-to-react-testing-library.ts +118 -31
  100. package/src/testing/enzyme-wrapper-scope.ts +39 -10
  101. package/src/util/java-recipe-proxy.ts +15 -2
  102. package/src/util/reindent.ts +35 -0
  103. package/src/zustand/redux-stores.ts +441 -0
  104. package/src/zustand/redux-to-zustand.ts +660 -0
  105. package/src/zustand/zustand-plan.ts +854 -0
  106. package/dist/react18/remove-unstable-batched-updates.d.ts.map +0 -1
  107. package/dist/react18/remove-unstable-batched-updates.js +0 -170
  108. package/dist/react18/remove-unstable-batched-updates.js.map +0 -1
  109. package/src/react18/remove-unstable-batched-updates.ts +0 -192
@@ -0,0 +1,301 @@
1
+ import {Cursor, ExecutionContext, Recipe, TreeVisitor, check, not} from "@openrewrite/rewrite";
2
+ import {JavaScriptVisitor, JS, maybeRemoveImport, isVendoredOrBundled, moduleBindings, declarationsOf, bindingNames, resolve} from "@openrewrite/rewrite/javascript";
3
+ import {isIdentifier, J, Statement} from "@openrewrite/rewrite/java";
4
+ import {create} from "mutative";
5
+ import {reindent} from "../util/reindent";
6
+
7
+ const REACT_DOM = "react-dom";
8
+ const BATCHED_UPDATES = "unstable_batchedUpdates";
9
+
10
+ /**
11
+ * Removes `unstable_batchedUpdates` wrappers from `react-dom`.
12
+ *
13
+ * In React 18, all state updates are automatically batched,
14
+ * making `unstable_batchedUpdates` unnecessary. This recipe
15
+ * unwraps the callback body and removes the wrapping call.
16
+ *
17
+ * Automatic batching only applies to roots created with `createRoot` or
18
+ * `hydrateRoot`; a legacy `ReactDOM.render` or `hydrate` root still needs the
19
+ * wrapper. React 19 removes the legacy APIs, so this recipe runs in the
20
+ * React 18 to 19 migration rather than the 17 to 18 one.
21
+ *
22
+ * Before:
23
+ * ```tsx
24
+ * import { unstable_batchedUpdates } from 'react-dom';
25
+ *
26
+ * unstable_batchedUpdates(() => {
27
+ * setCount(1);
28
+ * setFlag(true);
29
+ * });
30
+ * ```
31
+ *
32
+ * After:
33
+ * ```tsx
34
+ * setCount(1);
35
+ * setFlag(true);
36
+ * ```
37
+ *
38
+ * Only calls that resolve to `react-dom` through an import or `require` are
39
+ * unwrapped, so a local helper of the same name and the `react-native` export
40
+ * are left alone. A call is also left in place, which is harmless in React 18,
41
+ * when the body would mean something else in the enclosing scope: it uses
42
+ * `return`, `this` or `arguments`, the callback is `async`, or the body declares
43
+ * a variable, function or class.
44
+ *
45
+ * @see https://react.dev/blog/2022/03/29/react-v18#new-feature-automatic-batching
46
+ */
47
+ export class RemoveUnstableBatchedUpdates extends Recipe {
48
+ readonly name = "org.openrewrite.react.19.remove-unstable-batched-updates";
49
+ readonly displayName = "Remove `unstable_batchedUpdates`";
50
+ readonly description = "Removes `unstable_batchedUpdates` wrappers from `react-dom`. React 18 automatically batches all state updates on roots created with `createRoot` or `hydrateRoot`, the only roots React 19 supports, making this function unnecessary.";
51
+
52
+ async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
53
+ return check(not(isVendoredOrBundled()), new class extends JavaScriptVisitor<ExecutionContext> {
54
+ private changed = false;
55
+ private names: ReadonlySet<string> = new Set();
56
+
57
+ override async visitJsCompilationUnit(cu: JS.CompilationUnit, ctx: ExecutionContext): Promise<J | undefined> {
58
+ this.changed = false;
59
+ this.names = batchedUpdatesNames(cu);
60
+ if (this.names.size === 0 && moduleBindings(this).moduleSystem === "none") return cu;
61
+
62
+ let result = await super.visitJsCompilationUnit(cu, ctx) as JS.CompilationUnit;
63
+
64
+ const statements = await this.spliceStatements(result.statements);
65
+ if (statements) {
66
+ result = create(result, draft => {
67
+ draft.statements = statements as typeof draft.statements;
68
+ });
69
+ }
70
+
71
+ if (this.changed) {
72
+ maybeRemoveImport(this, REACT_DOM, BATCHED_UPDATES);
73
+ }
74
+
75
+ return result;
76
+ }
77
+
78
+ override async visitBlock(block: J.Block, ctx: ExecutionContext): Promise<J | undefined> {
79
+ const b = await super.visitBlock(block, ctx) as J.Block;
80
+ const statements = await this.spliceStatements(b.statements);
81
+ if (!statements) return b;
82
+ return create(b, draft => {
83
+ draft.statements = statements as typeof draft.statements;
84
+ });
85
+ }
86
+
87
+ private async spliceStatements(statements: J.RightPadded<Statement>[]): Promise<J.RightPadded<Statement>[] | null> {
88
+ const newStatements: J.RightPadded<Statement>[] = [];
89
+ let changed = false;
90
+
91
+ for (const paddedStmt of statements) {
92
+ const stmt = paddedStmt.element;
93
+ const bodyStatements = stmt ? await this.extractBatchedUpdatesBody(stmt) : null;
94
+ if (bodyStatements === null || bodyStatements.length === 0) {
95
+ newStatements.push(paddedStmt);
96
+ continue;
97
+ }
98
+
99
+ const outerIndent = indentation(stmt.prefix);
100
+ const innerIndent = indentation(bodyStatements[0].element.prefix);
101
+ for (const [i, bodyStmt] of bodyStatements.entries()) {
102
+ const element = await reindent(bodyStmt.element, innerIndent, outerIndent);
103
+ newStatements.push({...bodyStmt, element: i === 0 ? {...element, prefix: joinPrefixes(stmt.prefix, element.prefix)} : element});
104
+ }
105
+ changed = true;
106
+ this.changed = true;
107
+ }
108
+
109
+ return changed ? newStatements : null;
110
+ }
111
+
112
+ private async extractBatchedUpdatesBody(stmt: Statement): Promise<J.RightPadded<Statement>[] | null> {
113
+ let expr: J | undefined;
114
+
115
+ if (stmt.kind === JS.Kind.ExpressionStatement) {
116
+ expr = (stmt as JS.ExpressionStatement).expression as J;
117
+ } else if (stmt.kind === J.Kind.MethodInvocation) {
118
+ expr = stmt;
119
+ }
120
+
121
+ if (!expr || expr.kind !== J.Kind.MethodInvocation) return null;
122
+
123
+ const method = expr as J.MethodInvocation;
124
+ if (!isBatchedUpdatesCall(this, this.names, new Cursor(stmt, this.cursor), method)) return null;
125
+
126
+ const callback = method.arguments?.elements[0]?.element as J | undefined;
127
+ if (callback?.kind !== JS.Kind.ArrowFunction) return null;
128
+
129
+ const arrow = callback as JS.ArrowFunction;
130
+ if (arrow.modifiers.some(m => m.keyword === "async")) return null;
131
+
132
+ const body = arrow.lambda.body;
133
+ if (body?.kind !== J.Kind.Block) return null;
134
+
135
+ const statements = (body as J.Block).statements;
136
+ return await staysSameInOuterScope(statements) ? statements : null;
137
+ }
138
+ }());
139
+ }
140
+ }
141
+
142
+ /** Declarations scoped to the callback, which inlining would move into the enclosing scope. */
143
+ const DECLARATION_KINDS: ReadonlySet<string> = new Set([
144
+ J.Kind.VariableDeclarations,
145
+ JS.Kind.ScopedVariableDeclarations,
146
+ J.Kind.ClassDeclaration,
147
+ J.Kind.MethodDeclaration
148
+ ]);
149
+
150
+ // Bailing out on declarations rather than keeping a bare `{ ... }` block leaves
151
+ // the call as is, which still works in React 18; a bare block would be odd code
152
+ // that someone has to look at anyway.
153
+ async function staysSameInOuterScope(statements: J.RightPadded<Statement>[]): Promise<boolean> {
154
+ if (statements.some(s => DECLARATION_KINDS.has(s.element.kind))) return false;
155
+
156
+ const finder = new ScopeEscapeFinder();
157
+ for (const s of statements) {
158
+ await finder.visit(s.element, new ExecutionContext());
159
+ }
160
+ return !finder.found;
161
+ }
162
+
163
+ /**
164
+ * Finds `return`, `this` and `arguments` that would bind to a different
165
+ * function once the callback's body is inlined. Nested arrow functions share
166
+ * `this` and `arguments` with the callback; other nested functions and classes
167
+ * have their own. Every nested function has its own `return`.
168
+ */
169
+ class ScopeEscapeFinder extends JavaScriptVisitor<ExecutionContext> {
170
+ found = false;
171
+ private functionDepth = 0;
172
+ private nonArrowDepth = 0;
173
+
174
+ protected override async visitReturn(ret: J.Return, p: ExecutionContext): Promise<J | undefined> {
175
+ if (this.functionDepth === 0) this.found = true;
176
+ return super.visitReturn(ret, p);
177
+ }
178
+
179
+ protected override async visitIdentifier(ident: J.Identifier, p: ExecutionContext): Promise<J | undefined> {
180
+ if (this.nonArrowDepth === 0 && (ident.simpleName === "this" || ident.simpleName === "arguments")) {
181
+ this.found = true;
182
+ }
183
+ return super.visitIdentifier(ident, p);
184
+ }
185
+
186
+ protected override async visitLambda(lambda: J.Lambda, p: ExecutionContext): Promise<J | undefined> {
187
+ this.functionDepth++;
188
+ try {
189
+ return await super.visitLambda(lambda, p);
190
+ } finally {
191
+ this.functionDepth--;
192
+ }
193
+ }
194
+
195
+ protected override async visitMethodDeclaration(method: J.MethodDeclaration, p: ExecutionContext): Promise<J | undefined> {
196
+ this.functionDepth++;
197
+ this.nonArrowDepth++;
198
+ try {
199
+ return await super.visitMethodDeclaration(method, p);
200
+ } finally {
201
+ this.functionDepth--;
202
+ this.nonArrowDepth--;
203
+ }
204
+ }
205
+
206
+ protected override async visitClassDeclaration(classDecl: J.ClassDeclaration, p: ExecutionContext): Promise<J | undefined> {
207
+ this.nonArrowDepth++;
208
+ try {
209
+ return await super.visitClassDeclaration(classDecl, p);
210
+ } finally {
211
+ this.nonArrowDepth--;
212
+ }
213
+ }
214
+ }
215
+
216
+ /**
217
+ * Local names of `unstable_batchedUpdates` that `react-dom` binds at the top level of the file:
218
+ * `import {unstable_batchedUpdates as batch}` and `const {unstable_batchedUpdates: batch} = require(...)`.
219
+ * Whole-module bindings (`import X`, `import * as X`, `const X = require(...)`) are
220
+ * `moduleBindings(...).moduleOf`'s to answer.
221
+ */
222
+ function batchedUpdatesNames(cu: JS.CompilationUnit): Set<string> {
223
+ const names = new Set<string>();
224
+ for (const padded of cu.statements) {
225
+ const stmt = padded.element as J;
226
+ if (stmt.kind === JS.Kind.Import) {
227
+ const imp = stmt as JS.Import;
228
+ const named = imp.importClause?.namedBindings as J | undefined;
229
+ if (!isReactDomLiteral(unwrap(imp.moduleSpecifier)) || named?.kind !== JS.Kind.NamedImports) continue;
230
+ for (const el of (named as JS.NamedImports).elements.elements) {
231
+ const specifier = el.element.specifier as J;
232
+ if (isIdentifier(specifier)) {
233
+ if (specifier.simpleName === BATCHED_UPDATES) names.add(BATCHED_UPDATES);
234
+ } else if (specifier.kind === JS.Kind.Alias) {
235
+ const alias = specifier as JS.Alias;
236
+ const imported = alias.propertyName.element;
237
+ if (isIdentifier(imported) && imported.simpleName === BATCHED_UPDATES && isIdentifier(alias.alias)) {
238
+ names.add(alias.alias.simpleName);
239
+ }
240
+ }
241
+ }
242
+ } else {
243
+ for (const decl of declarationsOf(stmt)) {
244
+ for (const v of decl.variables) {
245
+ if (!isRequireOfReactDom(unwrap(v.element.initializer as J | { element: J } | undefined))) continue;
246
+ for (const {name, member} of bindingNames(v.element.name as J)) {
247
+ if (member === BATCHED_UPDATES) names.add(name);
248
+ }
249
+ }
250
+ }
251
+ }
252
+ }
253
+ return names;
254
+ }
255
+
256
+ /**
257
+ * Whether the call is `react-dom`'s `unstable_batchedUpdates`: its callee resolves to the
258
+ * compilation unit, so a parameter or local of the same name does not count.
259
+ */
260
+ function isBatchedUpdatesCall(visitor: JavaScriptVisitor<ExecutionContext>, names: ReadonlySet<string>, cursor: Cursor, method: J.MethodInvocation): boolean {
261
+ const select = method.select ? unwrap(method.select as J | { element: J }) : undefined;
262
+ if (!select) {
263
+ return names.has(method.name.simpleName) && resolvesToFile(cursor, method.name);
264
+ }
265
+ return method.name.simpleName === BATCHED_UPDATES
266
+ && isIdentifier(select)
267
+ && moduleBindings(visitor).moduleOf(select.simpleName) === REACT_DOM
268
+ && resolvesToFile(cursor, select);
269
+ }
270
+
271
+ function resolvesToFile(cursor: Cursor, identifier: J.Identifier): boolean {
272
+ return resolve(new Cursor(identifier, cursor), identifier)?.kind === JS.Kind.CompilationUnit;
273
+ }
274
+
275
+ function isReactDomLiteral(expr: unknown): boolean {
276
+ const literal = expr as J.Literal | undefined;
277
+ return literal?.kind === J.Kind.Literal && literal.value === REACT_DOM;
278
+ }
279
+
280
+ function isRequireOfReactDom(expr: J | undefined): boolean {
281
+ if (expr?.kind !== J.Kind.MethodInvocation) return false;
282
+ const call = expr as J.MethodInvocation;
283
+ return !call.select
284
+ && call.name.simpleName === "require"
285
+ && isReactDomLiteral(call.arguments.elements[0]?.element);
286
+ }
287
+
288
+ /** LST fields are sometimes wrapped in a `LeftPadded`/`RightPadded`; reads the node either way. */
289
+ function unwrap<T>(value: T | { element: T } | undefined): T | undefined {
290
+ return value && typeof value === "object" && "element" in value ? value.element : value as T | undefined;
291
+ }
292
+
293
+ /** The call's line break and comments, then those of the first statement that replaces it. */
294
+ function joinPrefixes(call: J.Space, first: J.Space): J.Space {
295
+ return {...call, comments: [...call.comments, ...first.comments]};
296
+ }
297
+
298
+ function indentation(prefix: J.Space): string {
299
+ const ws = prefix.whitespace ?? '';
300
+ return ws.substring(ws.lastIndexOf('\n') + 1);
301
+ }