@openrewrite/recipes-react 0.15.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 (80) hide show
  1. package/dist/migration/cra-to-vite/find-cra-config-blockers.js +20 -28
  2. package/dist/migration/cra-to-vite/find-cra-config-blockers.js.map +1 -1
  3. package/dist/migration/cra-to-vite/replace-react-scripts-dependency.d.ts.map +1 -1
  4. package/dist/migration/cra-to-vite/replace-react-scripts-dependency.js +13 -33
  5. package/dist/migration/cra-to-vite/replace-react-scripts-dependency.js.map +1 -1
  6. package/dist/migration/cra-to-vite/shared.d.ts +1 -14
  7. package/dist/migration/cra-to-vite/shared.d.ts.map +1 -1
  8. package/dist/migration/cra-to-vite/shared.js +13 -126
  9. package/dist/migration/cra-to-vite/shared.js.map +1 -1
  10. package/dist/migration/cra-to-vite/update-react-scripts-scripts.d.ts.map +1 -1
  11. package/dist/migration/cra-to-vite/update-react-scripts-scripts.js +16 -21
  12. package/dist/migration/cra-to-vite/update-react-scripts-scripts.js.map +1 -1
  13. package/dist/migration/cra-to-vite/update-tsconfig-for-vite.d.ts.map +1 -1
  14. package/dist/migration/cra-to-vite/update-tsconfig-for-vite.js +4 -13
  15. package/dist/migration/cra-to-vite/update-tsconfig-for-vite.js.map +1 -1
  16. package/dist/react17/migrate-deprecated-lifecycles.js +1 -1
  17. package/dist/react17/migrate-deprecated-lifecycles.js.map +1 -1
  18. package/dist/react17/use-new-jsx-transform.d.ts.map +1 -1
  19. package/dist/react17/use-new-jsx-transform.js +30 -78
  20. package/dist/react17/use-new-jsx-transform.js.map +1 -1
  21. package/dist/react18/replace-unmount-component-at-node.d.ts.map +1 -1
  22. package/dist/react18/replace-unmount-component-at-node.js +62 -20
  23. package/dist/react18/replace-unmount-component-at-node.js.map +1 -1
  24. package/dist/react19/replace-default-props.d.ts.map +1 -1
  25. package/dist/react19/replace-default-props.js +10 -13
  26. package/dist/react19/replace-default-props.js.map +1 -1
  27. package/dist/react19/replace-react-shallow-renderer.d.ts.map +1 -1
  28. package/dist/react19/replace-react-shallow-renderer.js +1 -6
  29. package/dist/react19/replace-react-shallow-renderer.js.map +1 -1
  30. package/dist/refactoring/create-class-to-es6.d.ts.map +1 -1
  31. package/dist/refactoring/create-class-to-es6.js +4 -7
  32. package/dist/refactoring/create-class-to-es6.js.map +1 -1
  33. package/dist/refactoring/create-element-to-jsx.d.ts.map +1 -1
  34. package/dist/refactoring/create-element-to-jsx.js +3 -4
  35. package/dist/refactoring/create-element-to-jsx.js.map +1 -1
  36. package/dist/refactoring/prop-types-to-typescript.js +2 -3
  37. package/dist/refactoring/prop-types-to-typescript.js.map +1 -1
  38. package/dist/refactoring/pure-render-mixin.d.ts.map +1 -1
  39. package/dist/refactoring/pure-render-mixin.js +3 -6
  40. package/dist/refactoring/pure-render-mixin.js.map +1 -1
  41. package/dist/testing/enzyme-host-components.d.ts +14 -0
  42. package/dist/testing/enzyme-host-components.d.ts.map +1 -0
  43. package/dist/testing/enzyme-host-components.js +245 -0
  44. package/dist/testing/enzyme-host-components.js.map +1 -0
  45. package/dist/testing/enzyme-to-react-testing-library.d.ts +10 -5
  46. package/dist/testing/enzyme-to-react-testing-library.d.ts.map +1 -1
  47. package/dist/testing/enzyme-to-react-testing-library.js +138 -113
  48. package/dist/testing/enzyme-to-react-testing-library.js.map +1 -1
  49. package/dist/testing/enzyme-wrapper-scope.d.ts +13 -4
  50. package/dist/testing/enzyme-wrapper-scope.d.ts.map +1 -1
  51. package/dist/testing/enzyme-wrapper-scope.js +161 -163
  52. package/dist/testing/enzyme-wrapper-scope.js.map +1 -1
  53. package/dist/util/module-imports.d.ts +12 -0
  54. package/dist/util/module-imports.d.ts.map +1 -0
  55. package/dist/util/module-imports.js +56 -0
  56. package/dist/util/module-imports.js.map +1 -0
  57. package/dist/util/react-class.d.ts +1 -0
  58. package/dist/util/react-class.d.ts.map +1 -1
  59. package/dist/util/react-class.js +3 -2
  60. package/dist/util/react-class.js.map +1 -1
  61. package/package.json +3 -3
  62. package/src/migration/cra-to-vite/find-cra-config-blockers.ts +21 -27
  63. package/src/migration/cra-to-vite/replace-react-scripts-dependency.ts +14 -39
  64. package/src/migration/cra-to-vite/shared.ts +15 -136
  65. package/src/migration/cra-to-vite/update-react-scripts-scripts.ts +16 -21
  66. package/src/migration/cra-to-vite/update-tsconfig-for-vite.ts +6 -13
  67. package/src/react17/migrate-deprecated-lifecycles.ts +2 -2
  68. package/src/react17/use-new-jsx-transform.ts +30 -72
  69. package/src/react18/replace-unmount-component-at-node.ts +78 -32
  70. package/src/react19/replace-default-props.ts +11 -15
  71. package/src/react19/replace-react-shallow-renderer.ts +2 -7
  72. package/src/refactoring/create-class-to-es6.ts +6 -9
  73. package/src/refactoring/create-element-to-jsx.ts +4 -6
  74. package/src/refactoring/prop-types-to-typescript.ts +4 -4
  75. package/src/refactoring/pure-render-mixin.ts +4 -7
  76. package/src/testing/enzyme-host-components.ts +283 -0
  77. package/src/testing/enzyme-to-react-testing-library.ts +176 -107
  78. package/src/testing/enzyme-wrapper-scope.ts +144 -137
  79. package/src/util/module-imports.ts +55 -0
  80. package/src/util/react-class.ts +2 -1
@@ -1,5 +1,5 @@
1
- import {and, check, Cursor, DataTable, ExecutionContext, findMarker, not, Option, ScanningRecipe, TreePrinters, TreeVisitor} from "@openrewrite/rewrite";
2
- import {addDependency, AddDependencyOptions, autoFormat, capture, PrettierStyle, deconflict, findNodeResolutionResult, isVendoredOrBundled, JavaScriptVisitor, JS, maybeRemoveImport, moduleBindings, namesUsedIn, pattern, rewrite, StyleKind, Template, template, usesMethod} from "@openrewrite/rewrite/javascript";
1
+ import {and, check, Cursor, DataTable, ExecutionContext, findMarker, not, Option, or, ScanningRecipe, Tree, TreePrinters, TreeVisitor} from "@openrewrite/rewrite";
2
+ import {addDependency, AddDependencyOptions, autoFormat, capture, PrettierStyle, deconflict, findNodeResolutionResult, isTypeScript, isVendoredOrBundled, JavaScriptVisitor, JS, maybeRemoveImport, moduleBindings, namesUsedIn, pattern, raw, rewrite, scopeOf, StyleKind, Template, template, usesMethod} from "@openrewrite/rewrite/javascript";
3
3
  import {Expression, J} from "@openrewrite/rewrite/java";
4
4
  import {create} from "mutative";
5
5
  import {Json, JsonVisitor} from "@openrewrite/rewrite/json";
@@ -7,8 +7,9 @@ import {readFileSync} from "fs";
7
7
  import {dirname, join} from "path";
8
8
  import {satisfies, validRange} from "semver";
9
9
  import {FindEnzymeUsage} from "../search/find-enzyme-usage";
10
- import {ENZYME, ENZYME_USAGE_TABLE, enclosingScope, EnzymeUsageRow} from "./enzyme-usage";
11
- import {analyzeWrapperScope, idsWithin, mountedElement, selectorLiteral, simpleChain, statementPosition, withoutEnzymeTypes, withRenderOptionsOnElementLine, wrapperDeclaration, WrapperRead} from "./enzyme-wrapper-scope";
10
+ import {ENZYME, ENZYME_USAGE_TABLE, enclosingScope, enzymeMethod, EnzymeUsageRow} from "./enzyme-usage";
11
+ import {HostComponents, hostComponentExports, ImportedExport, importedNames, propsRenderHostElements, relativeImports, rendersHostElements} from "./enzyme-host-components";
12
+ import {analyzeWrapperScope, idsWithin, innermostCall, mountedElement, selectorLiteral, simpleChain, statementPosition, variableCursor, withoutEnzymeTypes, withRenderOptionsOnElementLine, wrapperDeclaration, WrapperRead} from "./enzyme-wrapper-scope";
12
13
 
13
14
  const RTL = "@testing-library/react";
14
15
 
@@ -57,6 +58,19 @@ export function rewriteVersion(resolved: string, cache: Record<string, {filename
57
58
  return undefined;
58
59
  }
59
60
 
61
+ type DocumentReference = "document" | "globalThis.document";
62
+
63
+ /** How a render at `cursor` reaches the global `document` without a local binding capturing it. */
64
+ function documentAt(cursor: Cursor): DocumentReference | undefined {
65
+ const scope = scopeOf(cursor);
66
+ if (!scope.declares("document", "value")) return "document";
67
+ return scope.declares("globalThis", "value") ? undefined : "globalThis.document";
68
+ }
69
+
70
+ function renderOptions(document: DocumentReference): string {
71
+ return `{container: ${document}.createElement('div')}`;
72
+ }
73
+
60
74
  /** A wrapper's rendered element, declared ahead of the wrapper for `setProps` to clone. */
61
75
  interface HoistedElement {
62
76
  name: string;
@@ -88,6 +102,30 @@ interface PackageDeclarations {
88
102
  /** Package roots, such as `packages/ui/`, mapped to their declarations. */
89
103
  type Packages = Map<string, PackageDeclarations>;
90
104
 
105
+ interface Scanned {
106
+ packages: Packages;
107
+ components: HostComponents;
108
+ }
109
+
110
+ /** The Enzyme render a converted wrapper comes from. */
111
+ type Render = "mount" | "shallow";
112
+
113
+ /** A render that a converted wrapper is created by, and how its container reaches `document`. */
114
+ interface ConvertedRender {
115
+ document: DocumentReference;
116
+ api: Render;
117
+ }
118
+
119
+ /**
120
+ * What a converted wrapper of each Enzyme render may do. A shallow render calls a handler without
121
+ * bubbling or a DOM event, prints a found node as static markup, and shows a component element that
122
+ * `setProps` passes as a placeholder, where a full render shows its DOM.
123
+ */
124
+ const READS: Record<Render, {simulate: boolean, html: boolean, props: (props: Expression, testImports: ReadonlySet<string>) => boolean}> = {
125
+ mount: {simulate: true, html: true, props: () => true},
126
+ shallow: {simulate: false, html: false, props: propsRenderHostElements}
127
+ };
128
+
91
129
  /**
92
130
  * The React major version the tests of a source file run with, or 0 where they cannot migrate. A
93
131
  * dependency the owning package does not declare comes from the nearest enclosing package that
@@ -146,15 +184,30 @@ function declaredVersion(version: string | undefined): Declaration {
146
184
  * `mount(<Button />).find('button').length` and `const wrapper = mount(<Button />)` declarations
147
185
  * whose every reference is a supported DOM read become RTL renders into a detached container.
148
186
  *
187
+ * A `shallow` wrapper converts the same way where the full render cannot differ from the shallow
188
+ * one: its component, scanned from the source it is imported from, creates host elements only and
189
+ * runs no effects, and receives no component element from the test. `simulate` and `html()` stay
190
+ * excluded there, since a shallow render calls a handler without bubbling and prints static markup.
191
+ *
192
+ * ```tsx
193
+ * // before, where `Label` renders `<ul><li>{text}</li></ul>`
194
+ * const wrapper = shallow(<Label text="a" />);
195
+ * expect(wrapper.find('li').length).toBe(1);
196
+ * // after
197
+ * const wrapper = render(<Label text="a" />, {container: document.createElement('div')});
198
+ * expect(wrapper.container.querySelectorAll('li').length).toBe(1);
199
+ * ```
200
+ *
149
201
  * Existing compatible RTL installation and DOM test setup are prerequisites. More complex
150
202
  * wrapper flows remain in the inventory rather than being guessed at.
151
203
  *
152
204
  * @see https://testing-library.com/docs/react-testing-library/migrate-from-enzyme/#how-to-migrate-from-enzyme-to-react-testing-library
153
205
  */
154
- export class EnzymeToReactTestingLibrary extends ScanningRecipe<Packages> {
206
+
207
+ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
155
208
  readonly name = "org.openrewrite.react.migrate.enzyme-to-react-testing-library";
156
209
  readonly displayName = "Migrate Enzyme to React Testing Library";
157
- readonly description = "Migrates Enzyme `mount` wrappers whose every use is a supported DOM read or event (`find(selector).length`, `.exists()`, `.text()`, `.html()`, `.hasClass()`, positions through `.at(n)`, `.first()`, `.last()`, the wrapper's `text()` and `exists(selector)`, found nodes as a `toHaveLength` subject, `setProps` as a rerender of the cloned element, and on React 17 `simulate` with common mouse, keyboard, focus, form, and touch events, including `nativeEvent` mocks) and bare `mount` statements to React Testing Library container queries, `rerender`, and `fireEvent` in packages using React 16.9+/17 with RTL 10 to 12, adding RTL 12 where it is missing. Selectors are limited to HTML or SVG tag, class, ID, and pass-through attribute compounds and their descendant combinations. Reports remaining Enzyme usages for manual review. Requires an existing DOM test environment; shared wrappers, props, and snapshots are left for review.";
210
+ readonly description = "Migrates Enzyme `mount` wrappers whose every use is a supported DOM read or event (`find(selector).length`, `.exists()`, `.text()`, `.html()`, `.hasClass()`, positions through `.at(n)`, `.first()`, `.last()`, the wrapper's `text()` and `exists(selector)`, found nodes as a `toHaveLength` subject, `setProps` as a rerender of the cloned element, and on React 17 `simulate` with common mouse, keyboard, focus, form, and touch events, including `nativeEvent` mocks) and bare `mount` statements to React Testing Library container queries, `rerender`, and `fireEvent` in packages using React 16.9+/17 with RTL 10 to 12, adding RTL 12 where it is missing. Converts `shallow` wrappers the same way, without `simulate` or `html()`, where the component is imported from a source in the repository that creates host elements only and runs no effects, so a full render produces the DOM the shallow render does. Selectors are limited to HTML or SVG tag, class, ID, and pass-through attribute compounds and their descendant combinations. Reports remaining Enzyme usages for manual review. Requires an existing DOM test environment; shared wrappers, props, snapshots, and shallow rendering of other components are left for review.";
158
211
 
159
212
  @Option({
160
213
  displayName: "Convert positions into untagged selector matches",
@@ -173,12 +226,19 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Packages> {
173
226
  EnzymeUsageRow
174
227
  );
175
228
 
176
- initialValue(): Packages {
177
- return new Map();
229
+ initialValue(): Scanned {
230
+ return {packages: new Map(), components: new Map()};
178
231
  }
179
232
 
180
- async scanner(packages: Packages): Promise<TreeVisitor<any, ExecutionContext>> {
181
- return new class extends JsonVisitor<ExecutionContext> {
233
+ // The host may prepare the visitors before there is an accumulator, so it is read only while visiting
234
+ async scanner(scanned: Scanned): Promise<TreeVisitor<any, ExecutionContext>> {
235
+ const sources = new class extends JavaScriptVisitor<ExecutionContext> {
236
+ override async visitJsCompilationUnit(cu: JS.CompilationUnit): Promise<J | undefined> {
237
+ scanned.components.set(cu.sourcePath, hostComponentExports(cu));
238
+ return cu;
239
+ }
240
+ }();
241
+ const manifests = new class extends JsonVisitor<ExecutionContext> {
182
242
  override async visitDocument(doc: Json.Document, ctx: ExecutionContext): Promise<Json | undefined> {
183
243
  if (!/(^|\/)package\.json$/.test(doc.sourcePath)) return doc;
184
244
  const resolution = findNodeResolutionResult(doc);
@@ -195,7 +255,7 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Packages> {
195
255
  (!validRange(dependency!.versionConstraint) || satisfies(resolved.version, dependency!.versionConstraint))) return resolved.version;
196
256
  return dependencies.find(dep => dep.name === name)?.versionConstraint;
197
257
  };
198
- packages.set(doc.sourcePath.slice(0, -"package.json".length), {
258
+ scanned.packages.set(doc.sourcePath.slice(0, -"package.json".length), {
199
259
  react: declaredVersion(version("react")),
200
260
  reactDom: declaredVersion(version("react-dom")),
201
261
  rtl: declaredVersion(version(RTL)),
@@ -205,39 +265,60 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Packages> {
205
265
  return doc;
206
266
  }
207
267
  }();
268
+ return new class extends TreeVisitor<any, ExecutionContext> {
269
+ override async visit<R extends Tree>(tree: Tree, ctx: ExecutionContext, parent?: Cursor): Promise<R | undefined> {
270
+ if (tree.kind === Json.Kind.Document) return await manifests.visit(tree, ctx, parent) as R | undefined;
271
+ return tree.kind === JS.Kind.CompilationUnit ? await sources.visit(tree, ctx, parent) as R | undefined : tree as R;
272
+ }
273
+ }();
208
274
  }
209
275
 
210
- async editorWithData(packages: Packages): Promise<TreeVisitor<any, ExecutionContext>> {
276
+ async editorWithData(scanned: Scanned): Promise<TreeVisitor<any, ExecutionContext>> {
211
277
  const jsx = capture<Expression>({name: "element", constraint: node => node.kind !== JS.Kind.Spread});
212
278
  const selector = capture<J.Literal>({name: "selector", constraint: node => selectorLiteral(node)});
213
- const before = {lenientTypeMatching: false, context: ['import {mount} from "enzyme";'], dependencies: {"@types/enzyme": "3.10.19", "@types/react": "16.14.62"}};
214
279
  const after = {context: [`import {render} from "${RTL}";`], dependencies: {[RTL]: "12.1.5", "@types/react": "16.14.62"}};
215
- const lengthRule = rewrite(() => ({
216
- before: pattern`mount(${jsx}).find(${selector}).length`.configure(before),
217
- after: template`render(${jsx}, {container: globalThis.document.createElement('div')}).container.querySelectorAll(${selector}).length`.configure(after)
218
- }));
219
- const existsRule = rewrite(() => ({
220
- before: pattern`mount(${jsx}).find(${selector}).exists()`.configure(before),
221
- after: template`(render(${jsx}, {container: globalThis.document.createElement('div')}).container.querySelectorAll(${selector}).length > 0)`.configure(after)
222
- }));
223
- const existsArgumentRule = rewrite(() => ({
224
- before: pattern`mount(${jsx}).find(${selector}).exists()`.configure(before),
225
- after: template`render(${jsx}, {container: globalThis.document.createElement('div')}).container.querySelectorAll(${selector}).length > 0`.configure(after)
226
- }));
227
- const mountPattern = pattern`mount(${jsx})`.configure(before);
228
- const mountRule = rewrite(() => ({
229
- before: mountPattern,
230
- after: template`render(${jsx}, {container: globalThis.document.createElement('div')})`.configure(after)
231
- }));
280
+ const patterns = (api: Render) => {
281
+ const before = {lenientTypeMatching: false, context: [`import {${api}} from "enzyme";`], dependencies: {"@types/enzyme": "3.10.19", "@types/react": "16.14.62"}};
282
+ return {
283
+ render: pattern`${raw(api)}(${jsx})`.configure(before),
284
+ length: pattern`${raw(api)}(${jsx}).find(${selector}).length`.configure(before),
285
+ exists: pattern`${raw(api)}(${jsx}).find(${selector}).exists()`.configure(before)
286
+ };
287
+ };
288
+ const renderPatterns = {mount: patterns("mount"), shallow: patterns("shallow")};
289
+ const renderRules = (document: DocumentReference, api: Render) => {
290
+ const options = raw(renderOptions(document));
291
+ const from = renderPatterns[api];
292
+ return {
293
+ length: rewrite(() => ({
294
+ before: from.length,
295
+ after: template`render(${jsx}, ${options}).container.querySelectorAll(${selector}).length`.configure(after)
296
+ })),
297
+ exists: rewrite(() => ({
298
+ before: from.exists,
299
+ after: template`render(${jsx}, ${options}).container.querySelectorAll(${selector}).length > 0`.configure(after)
300
+ })),
301
+ mount: rewrite(() => ({
302
+ before: from.render,
303
+ after: template`render(${jsx}, ${options})`.configure(after)
304
+ }))
305
+ };
306
+ };
307
+ const rules = {
308
+ "document": {mount: renderRules("document", "mount"), shallow: renderRules("document", "shallow")},
309
+ "globalThis.document": {mount: renderRules("globalThis.document", "mount"), shallow: renderRules("globalThis.document", "shallow")}
310
+ };
232
311
  const usages = this.usages;
233
312
  const untaggedPositions = this.untaggedSelectorPositions !== false;
234
- return check(and(not(isVendoredOrBundled()), usesMethod("enzyme mount(..)")), new class extends JavaScriptVisitor<ExecutionContext> {
313
+ return check(and(not(isVendoredOrBundled()), or(usesMethod("enzyme mount(..)"), usesMethod("enzyme shallow(..)"))), new class extends JavaScriptVisitor<ExecutionContext> {
235
314
  private enabled = false;
236
315
  private reactMajor = 0;
237
316
  private events = false;
238
317
  private typescript = false;
239
318
  private sourcePath = "";
240
- private readonly mounts = new Set<string>();
319
+ private readonly mounts = new Map<string, ConvertedRender>();
320
+ private imports: ReadonlyMap<string, ImportedExport> = new Map();
321
+ private importedNames: ReadonlySet<string> = new Set();
241
322
  private readonly uses = new Map<string, WrapperRead>();
242
323
  private readonly removedStatements = new Set<string>();
243
324
  private readonly unmounts = new Set<string>();
@@ -261,11 +342,13 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Packages> {
261
342
  const prettierStyle = findMarker<PrettierStyle>(cu, StyleKind.PrettierStyle);
262
343
  this.prettier = prettierStyle !== undefined;
263
344
  this.printWidth = typeof prettierStyle?.config.printWidth === "number" ? prettierStyle.config.printWidth : 80;
264
- this.reactMajor = reactMajor(packages, cu.sourcePath, ADDS_RTL);
265
- this.events = simulatesEvents(packages, cu.sourcePath, ADDS_RTL);
266
- this.typescript = /\.[cm]?tsx?$/.test(cu.sourcePath);
345
+ this.reactMajor = reactMajor(scanned.packages, cu.sourcePath, ADDS_RTL);
346
+ this.events = simulatesEvents(scanned.packages, cu.sourcePath, ADDS_RTL);
347
+ this.typescript = isTypeScript(cu);
267
348
  this.enabled = this.reactMajor > 0 && moduleBindings(this).moduleSystem === "esm";
268
- if (!this.enabled || this.names.has("globalThis")) return cu;
349
+ if (!this.enabled) return cu;
350
+ this.imports = relativeImports(cu, scanned.components);
351
+ this.importedNames = importedNames(cu);
269
352
  const visited = await super.visitJsCompilationUnit(cu, ctx);
270
353
  this.rows.forEach(row => usages.insertRow(ctx, row));
271
354
  return visited;
@@ -273,13 +356,20 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Packages> {
273
356
 
274
357
  override async visitBlock(block: J.Block, ctx: ExecutionContext): Promise<J | undefined> {
275
358
  const planned: string[] = [];
276
- let scopes = 0;
359
+ const apis: Render[] = [];
277
360
  for (const statement of block.statements) {
278
- const candidate = wrapperDeclaration(statement.element);
361
+ const candidate = wrapperDeclaration(statement.element, render => this.renderOf(render));
279
362
  if (!candidate) continue;
280
- const scope = await analyzeWrapperScope(block, candidate.declaration, candidate.name, this.events, untaggedPositions, this.cursor.parent!, ctx);
281
- if (!scope || !await this.mountMatches(candidate.mount.id, block, ctx)) continue;
282
- this.mounts.add(candidate.mount.id);
363
+ const api = candidate.render;
364
+ const reads = READS[api];
365
+ const scope = analyzeWrapperScope(this.cursor, candidate, {events: this.events && reads.simulate, html: reads.html, untaggedPositions});
366
+ if (!scope) continue;
367
+ if ([...scope.uses.values()].some(use => use.use === "setProps" && !reads.props(use.props!, this.importedNames))) continue;
368
+ const mount = new Cursor(candidate.mount, variableCursor(this.cursor, candidate.declaration));
369
+ const document = documentAt(mount);
370
+ if (!document || !await renderPatterns[api].render.match(candidate.mount, mount)) continue;
371
+ this.mounts.set(candidate.mount.id, {document, api});
372
+ apis.push(api);
283
373
  this.declarations.add(candidate.declaration.id);
284
374
  scope.uses.forEach((use, id) => this.uses.set(id, use));
285
375
  scope.removedStatements.forEach(id => this.removedStatements.add(id));
@@ -293,7 +383,6 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Packages> {
293
383
  this.hoistedMounts.set(candidate.mount.id, name);
294
384
  }
295
385
  planned.push(candidate.mount.id, ...scope.uses.keys());
296
- scopes++;
297
386
  }
298
387
  planned.forEach(id => this.pending.add(id));
299
388
  const queued = this.afterVisit.length;
@@ -304,12 +393,12 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Packages> {
304
393
  if (planned.some(id => this.pending.has(id))) {
305
394
  this.afterVisit.length = queued;
306
395
  this.rows.length = rows;
307
- (await idsWithin(block, this.reformat, ctx)).forEach(id => this.reformat.delete(id));
396
+ idsWithin(block, this.reformat).forEach(id => this.reformat.delete(id));
308
397
  // Uses of a wrapper declared further out are rolled back too, which its block has to see
309
- (await idsWithin(block, new Set([...this.mounts, ...this.uses.keys()]), ctx)).forEach(id => this.pending.add(id));
398
+ idsWithin(block, new Set([...this.mounts.keys(), ...this.uses.keys()])).forEach(id => this.pending.add(id));
310
399
  return block;
311
400
  }
312
- for (let i = 0; i < scopes; i++) this.converted("mount", enclosingScope(this.cursor), "WRAPPER_SCOPE");
401
+ apis.forEach(api => this.converted(api, enclosingScope(this.cursor), "WRAPPER_SCOPE"));
313
402
  // Prettier lays out statements by their position in the block as it was parsed, before any is added or removed
314
403
  const laidOut = await this.withPrettierLayout(visited, ctx);
315
404
  const statements: J.Block["statements"][number][] = [];
@@ -356,7 +445,7 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Packages> {
356
445
  const statements: J.Block["statements"][number][] = [];
357
446
  let formatted = false;
358
447
  for (const statement of block.statements) {
359
- const ids = await idsWithin(statement.element, this.reformat, ctx);
448
+ const ids = idsWithin(statement.element, this.reformat);
360
449
  if (ids.length === 0) {
361
450
  statements.push(statement);
362
451
  continue;
@@ -379,15 +468,8 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Packages> {
379
468
  const use = this.uses.get(field.id);
380
469
  if (use) return await this.apply(use, field, ctx) ?? field;
381
470
  const visited = await super.visitFieldAccess(field, ctx) as J.FieldAccess;
382
- if (visited.name.element.simpleName === "length" && simpleChain(visited)) {
383
- const result = await lengthRule.tryOn(this.cursor, visited, {visitor: this});
384
- if (result) {
385
- this.converted("mount.find.length", "<inline expression>", "INLINE_DOM_QUERY");
386
- this.laidOutByPrettier(result);
387
- return withRenderOptionsOnElementLine(result, ctx);
388
- }
389
- }
390
- return visited;
471
+ const lengthOf = visited.name.element.simpleName === "length" && simpleChain(visited) ? this.renderOf(innermostCall(visited)) : undefined;
472
+ return lengthOf && await this.tryInline(lengthOf, "length", visited, `${lengthOf}.find.length`, "<inline expression>", "INLINE_DOM_QUERY", ctx) || visited;
391
473
  }
392
474
 
393
475
  override async visitMethodInvocation(method: J.MethodInvocation, ctx: ExecutionContext): Promise<J | undefined> {
@@ -395,47 +477,36 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Packages> {
395
477
  if (use) return await this.apply(use, method, ctx) ?? method;
396
478
  if (this.unmounts.has(method.id)) return withoutEnzymeTypes(method, ctx);
397
479
  const visited = await super.visitMethodInvocation(method, ctx) as J.MethodInvocation;
398
- if (this.mounts.has(method.id)) {
480
+ const mounted = this.mounts.get(method.id);
481
+ if (mounted) {
399
482
  const hoisted = this.hoistedMounts.get(method.id);
400
483
  const result = hoisted ?
401
- await this.applyTemplate(Template.builder().code(`render(${hoisted}, {container: globalThis.document.createElement('div')})`).build().configure(after), visited) :
402
- await mountRule.tryOn(this.cursor, visited, {visitor: this});
484
+ await this.applyTemplate(Template.builder().code(`render(${hoisted}, ${renderOptions(mounted.document)})`).build().configure(after), visited) :
485
+ await rules[mounted.document][mounted.api].mount.tryOn(this.cursor, visited, {visitor: this});
403
486
  if (!result) return visited;
404
487
  this.pending.delete(method.id);
405
488
  return withRenderOptionsOnElementLine(result, ctx);
406
489
  }
407
- if (visited.name.simpleName === "mount" && mountedElement(visited) && statementPosition(this.cursor)) {
408
- const result = await mountRule.tryOn(this.cursor, visited, {visitor: this});
409
- if (result) {
410
- this.converted("mount", enclosingScope(this.cursor), "MOUNT_STATEMENT");
411
- this.laidOutByPrettier(result);
412
- return withRenderOptionsOnElementLine(result, ctx);
413
- }
414
- }
415
- if (visited.name.simpleName === "exists" && simpleChain(visited)) {
416
- const result = await (this.callArgument(visited) ? existsArgumentRule : existsRule).tryOn(this.cursor, visited, {visitor: this});
417
- if (result) {
418
- this.converted("mount.find.exists", "<inline expression>", "INLINE_DOM_QUERY");
419
- this.laidOutByPrettier(result);
420
- return withRenderOptionsOnElementLine(result, ctx);
421
- }
422
- }
423
- return visited;
490
+ const statementOf = mountedElement(visited) && statementPosition(this.cursor) ? this.renderOf(visited) : undefined;
491
+ const statement = statementOf && await this.tryInline(statementOf, "mount", visited, statementOf, enclosingScope(this.cursor), "MOUNT_STATEMENT", ctx);
492
+ if (statement) return statement;
493
+ const existsOf = visited.name.simpleName === "exists" && simpleChain(visited) ? this.renderOf(innermostCall(visited)) : undefined;
494
+ return existsOf && await this.tryInline(existsOf, "exists", visited, `${existsOf}.find.exists`, "<inline expression>", "INLINE_DOM_QUERY", ctx) || visited;
424
495
  }
425
496
 
426
- private async mountMatches(mount: string, block: J.Block, ctx: ExecutionContext): Promise<boolean> {
427
- let mounted = false;
428
- await new class extends JavaScriptVisitor<ExecutionContext> {
429
- override async visitMethodInvocation(method: J.MethodInvocation, ctx: ExecutionContext): Promise<J | undefined> {
430
- if (method.id === mount && await mountPattern.match(method, this.cursor)) mounted = true;
431
- return super.visitMethodInvocation(method, ctx);
432
- }
433
- }().visit(block, ctx, this.cursor.parent);
434
- return mounted;
497
+ /** Converts an inline render, read, or bare render statement with one of the rules, recording it as `api` in `scope`. */
498
+ private async tryInline(render: Render, rule: "length" | "exists" | "mount", node: J, api: string, scope: string, reason: string,
499
+ ctx: ExecutionContext): Promise<J | undefined> {
500
+ const document = documentAt(this.cursor);
501
+ const result = document && await rules[document][render][rule].tryOn(this.cursor, node, {visitor: this});
502
+ if (!result) return undefined;
503
+ this.converted(api, scope, reason);
504
+ this.laidOutByPrettier(result);
505
+ return withRenderOptionsOnElementLine(result, ctx);
435
506
  }
436
507
 
437
508
  private async apply(read: WrapperRead, node: J, ctx: ExecutionContext): Promise<J | undefined> {
438
- const result = await this.applyTemplate(this.readTemplate(read, node), node);
509
+ const result = await this.applyTemplate(this.readTemplate(read), node);
439
510
  if (!result) return undefined;
440
511
  this.pending.delete(node.id);
441
512
  this.laidOutByPrettier(result);
@@ -450,7 +521,7 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Packages> {
450
521
  return replacement.apply(node, this.cursor, {bindings: await replacement.resolveBindings(this)});
451
522
  }
452
523
 
453
- private readTemplate(read: WrapperRead, node: J): Template {
524
+ private readTemplate(read: WrapperRead): Template {
454
525
  const code = Template.builder();
455
526
  const nodes = () => code.param(read.wrapper).code(".container.querySelectorAll(").param(read.selector!).code(")");
456
527
  // Enzyme throws where a single-node method finds no node; so does a non-null element here
@@ -463,30 +534,22 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Packages> {
463
534
  if (read.index !== undefined && read.index !== "first") return nodes().code("[").param(read.index).code("]");
464
535
  return code.param(read.wrapper).code(".container.querySelector(").param(read.selector!).code(")" + assertion);
465
536
  };
466
- const parenthesized = (build: () => void) => {
467
- const bare = this.callArgument(node);
468
- if (!bare) code.code("(");
469
- build();
470
- return code.code(bare ? "" : ")").build();
471
- };
472
537
  // Enzyme finds nothing within a position it has no element at
473
538
  const within = () => element(false).code("?.querySelectorAll(").param(read.within!).code(").length ?? 0");
474
539
  switch (read.use) {
475
540
  case "length":
476
- if (read.within) return parenthesized(within);
541
+ if (read.within) return within().build();
477
542
  return nodes().code(".length").build();
478
543
  case "exists":
479
- if (read.within) return parenthesized(() => {
544
+ if (read.within) {
480
545
  code.code("(");
481
- within().code(") > 0");
482
- });
483
- return parenthesized(() => nodes().code(".length > 0"));
546
+ return within().code(") > 0").build();
547
+ }
548
+ return nodes().code(".length > 0").build();
484
549
  case "positionExists":
485
- return parenthesized(() => {
486
- if (read.index === "first") code.param(read.wrapper).code(".container.querySelector(").param(read.selector!).code(") !== null");
487
- else if (read.index === "last") nodes().code(".length > 0");
488
- else nodes().code("[").param(read.index!).code("] !== undefined");
489
- });
550
+ if (read.index === "first") return code.param(read.wrapper).code(".container.querySelector(").param(read.selector!).code(") !== null").build();
551
+ if (read.index === "last") return nodes().code(".length > 0").build();
552
+ return nodes().code("[").param(read.index!).code("] !== undefined").build();
490
553
  case "nodes":
491
554
  return nodes().build();
492
555
  // An element's text content is never null, though its type allows it
@@ -528,11 +591,17 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Packages> {
528
591
  }
529
592
  }
530
593
 
531
- // A comparison needs no parentheses of its own as a call argument, and Prettier removes them there
532
- private callArgument(node: J): boolean {
533
- const parent = this.cursor.parentTree()?.value as J | undefined;
534
- return parent?.kind === J.Kind.MethodInvocation &&
535
- (parent as J.MethodInvocation).arguments.elements.some(argument => argument.element.id === node.id);
594
+ /**
595
+ * The Enzyme render a call is, where RTL's `render` renders the same DOM: any `mount`, and a
596
+ * `shallow` of a component that renders host elements only, as {@link rendersHostElements} decides.
597
+ */
598
+ private renderOf(node: J | undefined): Render | undefined {
599
+ if (node?.kind !== J.Kind.MethodInvocation) return undefined;
600
+ const call = node as J.MethodInvocation;
601
+ const api = enzymeMethod(call);
602
+ if (api === "mount") return api;
603
+ const element = call.arguments.elements[0]?.element;
604
+ return api === "shallow" && call.arguments.elements.length === 1 && rendersHostElements(element, this.imports, scanned.components, this.importedNames) ? api : undefined;
536
605
  }
537
606
 
538
607
  private laidOutByPrettier(node: J): void {