@openrewrite/recipes-react 0.20.0 → 0.22.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 (276) hide show
  1. package/dist/i18n/translate-hard-coded-strings.d.ts +67 -0
  2. package/dist/i18n/translate-hard-coded-strings.d.ts.map +1 -0
  3. package/dist/i18n/translate-hard-coded-strings.js +439 -0
  4. package/dist/i18n/translate-hard-coded-strings.js.map +1 -0
  5. package/dist/index.d.ts +3 -0
  6. package/dist/index.d.ts.map +1 -1
  7. package/dist/index.js +37 -1
  8. package/dist/index.js.map +1 -1
  9. package/dist/mui/adapt-v4-theme.d.ts +8 -0
  10. package/dist/mui/adapt-v4-theme.d.ts.map +1 -0
  11. package/dist/mui/adapt-v4-theme.js +65 -0
  12. package/dist/mui/adapt-v4-theme.js.map +1 -0
  13. package/dist/mui/add-component-prop.d.ts +18 -0
  14. package/dist/mui/add-component-prop.d.ts.map +1 -0
  15. package/dist/mui/add-component-prop.js +53 -0
  16. package/dist/mui/add-component-prop.js.map +1 -0
  17. package/dist/mui/add-emotion-prepend.d.ts +8 -0
  18. package/dist/mui/add-emotion-prepend.d.ts.map +1 -0
  19. package/dist/mui/add-emotion-prepend.js +71 -0
  20. package/dist/mui/add-emotion-prepend.js.map +1 -0
  21. package/dist/mui/change-module-specifier.d.ts +14 -0
  22. package/dist/mui/change-module-specifier.d.ts.map +1 -0
  23. package/dist/mui/change-module-specifier.js +95 -0
  24. package/dist/mui/change-module-specifier.js.map +1 -0
  25. package/dist/mui/convert-mui-imports.d.ts +14 -0
  26. package/dist/mui/convert-mui-imports.d.ts.map +1 -0
  27. package/dist/mui/convert-mui-imports.js +195 -0
  28. package/dist/mui/convert-mui-imports.js.map +1 -0
  29. package/dist/mui/convert-prop-to-sx.d.ts +22 -0
  30. package/dist/mui/convert-prop-to-sx.d.ts.map +1 -0
  31. package/dist/mui/convert-prop-to-sx.js +99 -0
  32. package/dist/mui/convert-prop-to-sx.js.map +1 -0
  33. package/dist/mui/index.d.ts +32 -0
  34. package/dist/mui/index.d.ts.map +1 -0
  35. package/dist/mui/index.js +67 -0
  36. package/dist/mui/index.js.map +1 -0
  37. package/dist/mui/jsx-attributes.d.ts +27 -0
  38. package/dist/mui/jsx-attributes.d.ts.map +1 -0
  39. package/dist/mui/jsx-attributes.js +140 -0
  40. package/dist/mui/jsx-attributes.js.map +1 -0
  41. package/dist/mui/mark-manual-migration.d.ts +16 -0
  42. package/dist/mui/mark-manual-migration.d.ts.map +1 -0
  43. package/dist/mui/mark-manual-migration.js +73 -0
  44. package/dist/mui/mark-manual-migration.js.map +1 -0
  45. package/dist/mui/mark-palette-mode-usage.d.ts +12 -0
  46. package/dist/mui/mark-palette-mode-usage.d.ts.map +1 -0
  47. package/dist/mui/mark-palette-mode-usage.js +50 -0
  48. package/dist/mui/mark-palette-mode-usage.js.map +1 -0
  49. package/dist/mui/move-component-prop-to-slot.d.ts +22 -0
  50. package/dist/mui/move-component-prop-to-slot.d.ts.map +1 -0
  51. package/dist/mui/move-component-prop-to-slot.js +87 -0
  52. package/dist/mui/move-component-prop-to-slot.js.map +1 -0
  53. package/dist/mui/move-primary-text-to-children.d.ts +12 -0
  54. package/dist/mui/move-primary-text-to-children.d.ts.map +1 -0
  55. package/dist/mui/move-primary-text-to-children.js +52 -0
  56. package/dist/mui/move-primary-text-to-children.js.map +1 -0
  57. package/dist/mui/move-system-props-to-sx.d.ts +16 -0
  58. package/dist/mui/move-system-props-to-sx.d.ts.map +1 -0
  59. package/dist/mui/move-system-props-to-sx.js +122 -0
  60. package/dist/mui/move-system-props-to-sx.js.map +1 -0
  61. package/dist/mui/mui-components.d.ts +8 -0
  62. package/dist/mui/mui-components.d.ts.map +1 -0
  63. package/dist/mui/mui-components.js +41 -0
  64. package/dist/mui/mui-components.js.map +1 -0
  65. package/dist/mui/mui-tag-visitor.d.ts +5 -0
  66. package/dist/mui/mui-tag-visitor.d.ts.map +1 -0
  67. package/dist/mui/mui-tag-visitor.js +54 -0
  68. package/dist/mui/mui-tag-visitor.js.map +1 -0
  69. package/dist/mui/pre-v5-recipe.d.ts +14 -0
  70. package/dist/mui/pre-v5-recipe.d.ts.map +1 -0
  71. package/dist/mui/pre-v5-recipe.js +88 -0
  72. package/dist/mui/pre-v5-recipe.js.map +1 -0
  73. package/dist/mui/remove-component-prop.d.ts +18 -0
  74. package/dist/mui/remove-component-prop.d.ts.map +1 -0
  75. package/dist/mui/remove-component-prop.js +55 -0
  76. package/dist/mui/remove-component-prop.js.map +1 -0
  77. package/dist/mui/remove-root-ref.d.ts +8 -0
  78. package/dist/mui/remove-root-ref.d.ts.map +1 -0
  79. package/dist/mui/remove-root-ref.js +61 -0
  80. package/dist/mui/remove-root-ref.js.map +1 -0
  81. package/dist/mui/remove-spacing-px-suffix.d.ts +8 -0
  82. package/dist/mui/remove-spacing-px-suffix.d.ts.map +1 -0
  83. package/dist/mui/remove-spacing-px-suffix.js +62 -0
  84. package/dist/mui/remove-spacing-px-suffix.js.map +1 -0
  85. package/dist/mui/rename-component-prop.d.ts +20 -0
  86. package/dist/mui/rename-component-prop.d.ts.map +1 -0
  87. package/dist/mui/rename-component-prop.js +66 -0
  88. package/dist/mui/rename-component-prop.js.map +1 -0
  89. package/dist/mui/rename-joy-css-variables.d.ts +8 -0
  90. package/dist/mui/rename-joy-css-variables.d.ts.map +1 -0
  91. package/dist/mui/rename-joy-css-variables.js +51 -0
  92. package/dist/mui/rename-joy-css-variables.js.map +1 -0
  93. package/dist/mui/rename-theme-palette-type.d.ts +8 -0
  94. package/dist/mui/rename-theme-palette-type.d.ts.map +1 -0
  95. package/dist/mui/rename-theme-palette-type.js +61 -0
  96. package/dist/mui/rename-theme-palette-type.js.map +1 -0
  97. package/dist/mui/replace-box-border-radius.d.ts +10 -0
  98. package/dist/mui/replace-box-border-radius.d.ts.map +1 -0
  99. package/dist/mui/replace-box-border-radius.js +50 -0
  100. package/dist/mui/replace-box-border-radius.js.map +1 -0
  101. package/dist/mui/replace-breakpoints-width.d.ts +8 -0
  102. package/dist/mui/replace-breakpoints-width.d.ts.map +1 -0
  103. package/dist/mui/replace-breakpoints-width.js +46 -0
  104. package/dist/mui/replace-breakpoints-width.js.map +1 -0
  105. package/dist/mui/replace-component-class.d.ts +18 -0
  106. package/dist/mui/replace-component-class.d.ts.map +1 -0
  107. package/dist/mui/replace-component-class.js +126 -0
  108. package/dist/mui/replace-component-class.js.map +1 -0
  109. package/dist/mui/replace-components-with-slots.d.ts +14 -0
  110. package/dist/mui/replace-components-with-slots.d.ts.map +1 -0
  111. package/dist/mui/replace-components-with-slots.js +69 -0
  112. package/dist/mui/replace-components-with-slots.js.map +1 -0
  113. package/dist/mui/replace-import-paths.d.ts +14 -0
  114. package/dist/mui/replace-import-paths.d.ts.map +1 -0
  115. package/dist/mui/replace-import-paths.js +101 -0
  116. package/dist/mui/replace-import-paths.js.map +1 -0
  117. package/dist/mui/replace-in-string-literals.d.ts +15 -0
  118. package/dist/mui/replace-in-string-literals.d.ts.map +1 -0
  119. package/dist/mui/replace-in-string-literals.js +62 -0
  120. package/dist/mui/replace-in-string-literals.js.map +1 -0
  121. package/dist/mui/replace-list-item-button-prop.d.ts +12 -0
  122. package/dist/mui/replace-list-item-button-prop.d.ts.map +1 -0
  123. package/dist/mui/replace-list-item-button-prop.js +80 -0
  124. package/dist/mui/replace-list-item-button-prop.js.map +1 -0
  125. package/dist/mui/replace-tabs-scroll-buttons.d.ts +8 -0
  126. package/dist/mui/replace-tabs-scroll-buttons.d.ts.map +1 -0
  127. package/dist/mui/replace-tabs-scroll-buttons.js +41 -0
  128. package/dist/mui/replace-tabs-scroll-buttons.js.map +1 -0
  129. package/dist/mui/replace-theme-color-functions.d.ts +8 -0
  130. package/dist/mui/replace-theme-color-functions.d.ts.map +1 -0
  131. package/dist/mui/replace-theme-color-functions.js +72 -0
  132. package/dist/mui/replace-theme-color-functions.js.map +1 -0
  133. package/dist/mui/replace-theme-spacing-unit.d.ts +8 -0
  134. package/dist/mui/replace-theme-spacing-unit.d.ts.map +1 -0
  135. package/dist/mui/replace-theme-spacing-unit.js +77 -0
  136. package/dist/mui/replace-theme-spacing-unit.js.map +1 -0
  137. package/dist/mui/replace-typography-round.d.ts +8 -0
  138. package/dist/mui/replace-typography-round.d.ts.map +1 -0
  139. package/dist/mui/replace-typography-round.js +44 -0
  140. package/dist/mui/replace-typography-round.js.map +1 -0
  141. package/dist/mui/shift-hidden-down-props.d.ts +10 -0
  142. package/dist/mui/shift-hidden-down-props.d.ts.map +1 -0
  143. package/dist/mui/shift-hidden-down-props.js +49 -0
  144. package/dist/mui/shift-hidden-down-props.js.map +1 -0
  145. package/dist/mui/theme-access.d.ts +5 -0
  146. package/dist/mui/theme-access.d.ts.map +1 -0
  147. package/dist/mui/theme-access.js +21 -0
  148. package/dist/mui/theme-access.js.map +1 -0
  149. package/dist/mui/update-theme-breakpoints.d.ts +10 -0
  150. package/dist/mui/update-theme-breakpoints.d.ts.map +1 -0
  151. package/dist/mui/update-theme-breakpoints.js +58 -0
  152. package/dist/mui/update-theme-breakpoints.js.map +1 -0
  153. package/dist/mui/upgrade-grid-props.d.ts +16 -0
  154. package/dist/mui/upgrade-grid-props.d.ts.map +1 -0
  155. package/dist/mui/upgrade-grid-props.js +90 -0
  156. package/dist/mui/upgrade-grid-props.js.map +1 -0
  157. package/dist/search/find-enzyme-usage.d.ts +8 -0
  158. package/dist/search/find-enzyme-usage.d.ts.map +1 -1
  159. package/dist/search/find-enzyme-usage.js +119 -8
  160. package/dist/search/find-enzyme-usage.js.map +1 -1
  161. package/dist/search/find-hard-coded-strings.d.ts +110 -0
  162. package/dist/search/find-hard-coded-strings.d.ts.map +1 -0
  163. package/dist/search/find-hard-coded-strings.js +987 -0
  164. package/dist/search/find-hard-coded-strings.js.map +1 -0
  165. package/dist/search/find-missing-use-client-directive.d.ts +2 -0
  166. package/dist/search/find-missing-use-client-directive.d.ts.map +1 -1
  167. package/dist/search/find-missing-use-client-directive.js +1 -0
  168. package/dist/search/find-missing-use-client-directive.js.map +1 -1
  169. package/dist/testing/enzyme-host-components.d.ts +12 -0
  170. package/dist/testing/enzyme-host-components.d.ts.map +1 -1
  171. package/dist/testing/enzyme-host-components.js +100 -0
  172. package/dist/testing/enzyme-host-components.js.map +1 -1
  173. package/dist/testing/enzyme-portals.d.ts +3 -5
  174. package/dist/testing/enzyme-portals.d.ts.map +1 -1
  175. package/dist/testing/enzyme-portals.js +8 -39
  176. package/dist/testing/enzyme-portals.js.map +1 -1
  177. package/dist/testing/enzyme-render-blockers.d.ts +19 -0
  178. package/dist/testing/enzyme-render-blockers.d.ts.map +1 -0
  179. package/dist/testing/enzyme-render-blockers.js +275 -0
  180. package/dist/testing/enzyme-render-blockers.js.map +1 -0
  181. package/dist/testing/enzyme-to-react-testing-library.d.ts +17 -3
  182. package/dist/testing/enzyme-to-react-testing-library.d.ts.map +1 -1
  183. package/dist/testing/enzyme-to-react-testing-library.js +237 -27
  184. package/dist/testing/enzyme-to-react-testing-library.js.map +1 -1
  185. package/dist/testing/enzyme-usage.d.ts +9 -0
  186. package/dist/testing/enzyme-usage.d.ts.map +1 -1
  187. package/dist/testing/enzyme-usage.js +36 -3
  188. package/dist/testing/enzyme-usage.js.map +1 -1
  189. package/dist/testing/enzyme-wrapper-scope.d.ts +8 -1
  190. package/dist/testing/enzyme-wrapper-scope.d.ts.map +1 -1
  191. package/dist/testing/enzyme-wrapper-scope.js +26 -5
  192. package/dist/testing/enzyme-wrapper-scope.js.map +1 -1
  193. package/dist/util/json-and-javascript.d.ts +4 -0
  194. package/dist/util/json-and-javascript.d.ts.map +1 -0
  195. package/dist/util/json-and-javascript.js +37 -0
  196. package/dist/util/json-and-javascript.js.map +1 -0
  197. package/dist/util/module-imports.d.ts +36 -0
  198. package/dist/util/module-imports.d.ts.map +1 -1
  199. package/dist/util/module-imports.js +216 -0
  200. package/dist/util/module-imports.js.map +1 -1
  201. package/dist/util/test-source.d.ts +2 -0
  202. package/dist/util/test-source.d.ts.map +1 -0
  203. package/dist/util/test-source.js +5 -0
  204. package/dist/util/test-source.js.map +1 -0
  205. package/dist/zustand/entry-store.d.ts +9 -0
  206. package/dist/zustand/entry-store.d.ts.map +1 -0
  207. package/dist/zustand/entry-store.js +136 -0
  208. package/dist/zustand/entry-store.js.map +1 -0
  209. package/dist/zustand/redux-stores.d.ts +7 -4
  210. package/dist/zustand/redux-stores.d.ts.map +1 -1
  211. package/dist/zustand/redux-stores.js +128 -11
  212. package/dist/zustand/redux-stores.js.map +1 -1
  213. package/dist/zustand/redux-to-zustand.d.ts +11 -2
  214. package/dist/zustand/redux-to-zustand.d.ts.map +1 -1
  215. package/dist/zustand/redux-to-zustand.js +147 -46
  216. package/dist/zustand/redux-to-zustand.js.map +1 -1
  217. package/dist/zustand/zustand-plan.d.ts +14 -5
  218. package/dist/zustand/zustand-plan.d.ts.map +1 -1
  219. package/dist/zustand/zustand-plan.js +226 -52
  220. package/dist/zustand/zustand-plan.js.map +1 -1
  221. package/package.json +1 -1
  222. package/src/i18n/translate-hard-coded-strings.ts +442 -0
  223. package/src/index.ts +17 -0
  224. package/src/mui/adapt-v4-theme.ts +43 -0
  225. package/src/mui/add-component-prop.ts +43 -0
  226. package/src/mui/add-emotion-prepend.ts +48 -0
  227. package/src/mui/change-module-specifier.ts +71 -0
  228. package/src/mui/convert-mui-imports.ts +184 -0
  229. package/src/mui/convert-prop-to-sx.ts +89 -0
  230. package/src/mui/index.ts +31 -0
  231. package/src/mui/jsx-attributes.ts +133 -0
  232. package/src/mui/mark-manual-migration.ts +53 -0
  233. package/src/mui/mark-palette-mode-usage.ts +36 -0
  234. package/src/mui/move-component-prop-to-slot.ts +84 -0
  235. package/src/mui/move-primary-text-to-children.ts +41 -0
  236. package/src/mui/move-system-props-to-sx.ts +118 -0
  237. package/src/mui/mui-components.ts +40 -0
  238. package/src/mui/mui-tag-visitor.ts +36 -0
  239. package/src/mui/pre-v5-recipe.ts +82 -0
  240. package/src/mui/remove-component-prop.ts +43 -0
  241. package/src/mui/remove-root-ref.ts +41 -0
  242. package/src/mui/remove-spacing-px-suffix.ts +43 -0
  243. package/src/mui/rename-component-prop.ts +55 -0
  244. package/src/mui/rename-joy-css-variables.ts +41 -0
  245. package/src/mui/rename-theme-palette-type.ts +42 -0
  246. package/src/mui/replace-box-border-radius.ts +42 -0
  247. package/src/mui/replace-breakpoints-width.ts +28 -0
  248. package/src/mui/replace-component-class.ts +97 -0
  249. package/src/mui/replace-components-with-slots.ts +61 -0
  250. package/src/mui/replace-import-paths.ts +100 -0
  251. package/src/mui/replace-in-string-literals.ts +44 -0
  252. package/src/mui/replace-list-item-button-prop.ts +59 -0
  253. package/src/mui/replace-tabs-scroll-buttons.ts +31 -0
  254. package/src/mui/replace-theme-color-functions.ts +55 -0
  255. package/src/mui/replace-theme-spacing-unit.ts +59 -0
  256. package/src/mui/replace-typography-round.ts +29 -0
  257. package/src/mui/shift-hidden-down-props.ts +44 -0
  258. package/src/mui/theme-access.ts +18 -0
  259. package/src/mui/update-theme-breakpoints.ts +47 -0
  260. package/src/mui/upgrade-grid-props.ts +82 -0
  261. package/src/search/find-enzyme-usage.ts +109 -12
  262. package/src/search/find-hard-coded-strings.ts +1006 -0
  263. package/src/search/find-missing-use-client-directive.ts +1 -1
  264. package/src/testing/enzyme-host-components.ts +110 -0
  265. package/src/testing/enzyme-portals.ts +4 -44
  266. package/src/testing/enzyme-render-blockers.ts +278 -0
  267. package/src/testing/enzyme-to-react-testing-library.ts +240 -34
  268. package/src/testing/enzyme-usage.ts +48 -2
  269. package/src/testing/enzyme-wrapper-scope.ts +35 -3
  270. package/src/util/json-and-javascript.ts +26 -0
  271. package/src/util/module-imports.ts +223 -0
  272. package/src/util/test-source.ts +2 -0
  273. package/src/zustand/entry-store.ts +131 -0
  274. package/src/zustand/redux-stores.ts +131 -12
  275. package/src/zustand/redux-to-zustand.ts +179 -52
  276. package/src/zustand/zustand-plan.ts +256 -49
@@ -19,7 +19,7 @@ const CLIENT_HOOKS = new Set([
19
19
  const BROWSER_GLOBALS = new Set(['window', 'document', 'localStorage', 'sessionStorage', 'navigator']);
20
20
 
21
21
  /** Directives are the string-literal statements at the top of a file. */
22
- function hasDirective(cu: JS.CompilationUnit, directive: string): boolean {
22
+ export function hasDirective(cu: JS.CompilationUnit, directive: string): boolean {
23
23
  for (const statement of cu.statements) {
24
24
  let node: any = statement.element;
25
25
  if (node.kind === JS.Kind.ExpressionStatement) node = node.expression;
@@ -31,6 +31,9 @@ const SAME_IN_SHALLOW = new Set(["useState", "useReducer", "useMemo", "useCallba
31
31
 
32
32
  const HOOK = /^use[A-Z0-9]/;
33
33
 
34
+ // Of RENDERS_OTHERWISE, what runs only in a full render rather than creating elements a JSX tag doesn't show
35
+ const RUNS_OTHERWISE = new Set(["useEffect", "useLayoutEffect", "useInsertionEffect", "ref"]);
36
+
34
37
  const FRAGMENT = new Set(["Fragment"]);
35
38
 
36
39
  /** A lowercase tag is an intrinsic element and an empty one a fragment, which renders its children. */
@@ -320,3 +323,110 @@ export function rendersHostElements(element: J, imports: ReadonlyMap<string, Imp
320
323
  (tag.children ?? []).every(child => hostElementsOnly(child, testImports) &&
321
324
  (child.kind !== JS.Kind.JsxEmbeddedExpression || rendersAsHost((child as JSX.EmbeddedExpression).expression.element, testImports)));
322
325
  }
326
+
327
+ /** What a component renders that `shallow` leaves out or doesn't run, and the code that names it, such as "`<Button>` from `@patternfly/react-core`". */
328
+ export interface ShallowMiss {
329
+ kind: "child" | "effect" | "hook" | "wrapped" | "package" | "passed";
330
+ detail: string;
331
+ }
332
+
333
+ /** Each source's first {@link ShallowMiss}, and its exports that are a call, such as `memo(...)`, with the callee. */
334
+ export interface CompositeFacts {
335
+ miss?: ShallowMiss;
336
+ wrapped: ReadonlyMap<string, string>;
337
+ }
338
+
339
+ export type Composites = Map<string, CompositeFacts>;
340
+
341
+ function tagName(tag: JSX.Tag): string | undefined {
342
+ const name = tag.openName.element;
343
+ return isIdentifier(name) ? name.simpleName : name.kind === J.Kind.FieldAccess ? `${rootName(name as J.FieldAccess)}.${(name as J.FieldAccess).name.element.simpleName}` : undefined;
344
+ }
345
+
346
+ /** `name` as code, with the module its root is imported from, such as "`<Button>` from `@patternfly/react-core`". */
347
+ function named(name: string, bindings: ReturnType<typeof importBindings>, shown = name): string {
348
+ const module = bindings.find(({local}) => local === name.split(".")[0])?.module;
349
+ return module ? `\`${shown}\` from \`${module}\`` : `\`${shown}\``;
350
+ }
351
+
352
+ /** The callee of a call, such as `forwardRef`, `styled.div` or `withSize`, for `withSize()(Actions)`. */
353
+ function callee(node: J): string | undefined {
354
+ if (node.kind !== J.Kind.MethodInvocation) return undefined;
355
+ const call = node as J.MethodInvocation;
356
+ const select = call.select?.element;
357
+ if (select?.kind === J.Kind.MethodInvocation) return callee(select);
358
+ return select && rootName(select as Expression) ? `${rootName(select as Expression)}.${call.name.simpleName}` : call.name.simpleName;
359
+ }
360
+
361
+ /**
362
+ * Why the components a source declares may render what `shallow` leaves out: the first element of a component, effect or
363
+ * hook that {@link hostElementsOnly} rejects, and each export that wraps a component in a call. Undefined where it declares none.
364
+ */
365
+ export function compositeFacts(cu: JS.CompilationUnit): CompositeFacts | undefined {
366
+ const wrapped = new Map<string, string>();
367
+ for (const {element} of cu.statements) {
368
+ const statement = element.kind === JS.Kind.ExportDeclaration ? undefined : element;
369
+ if (statement?.kind !== J.Kind.VariableDeclarations) continue;
370
+ const declaration = statement as J.VariableDeclarations;
371
+ const variable = declaration.variables.length === 1 ? declaration.variables[0].element : undefined;
372
+ const initializer = variable?.initializer?.element;
373
+ const exported = variable && isIdentifier(variable.name) ? exportName(declaration, variable.name.simpleName) : undefined;
374
+ const wrapper = initializer && callee(initializer);
375
+ if (exported && wrapper) wrapped.set(exported, wrapper);
376
+ }
377
+ for (const {element} of cu.statements) {
378
+ if (element.kind !== JS.Kind.ExportAssignment || (element as JS.ExportAssignment).exportEquals) continue;
379
+ const wrapper = callee((element as JS.ExportAssignment).expression.element);
380
+ if (wrapper) wrapped.set("default", wrapper);
381
+ }
382
+ if (wrapped.size === 0 && componentExports(cu).size === 0) return undefined;
383
+ const bindings = importBindings(cu);
384
+ let miss: ShallowMiss | undefined;
385
+ const hook = bindings.find(({local, module}) => HOOK.test(local) && module !== "react");
386
+ if (hook) miss = {kind: "hook", detail: named(hook.local, bindings)};
387
+ walk(cu, tree => {
388
+ if (miss) return false;
389
+ if (tree.kind === J.Kind.Identifier && RENDERS_OTHERWISE.has((tree as J.Identifier).simpleName)) {
390
+ const name = (tree as J.Identifier).simpleName;
391
+ miss = {kind: RUNS_OTHERWISE.has(name) ? "effect" : "child", detail: `\`${name}\``};
392
+ } else if (tree.kind === J.Kind.MethodInvocation && HOOK.test((tree as J.MethodInvocation).name.simpleName) &&
393
+ !SAME_IN_SHALLOW.has((tree as J.MethodInvocation).name.simpleName)) {
394
+ const name = (tree as J.MethodInvocation).name.simpleName;
395
+ miss = RUNS_OTHERWISE.has(name) ? {kind: "effect", detail: `\`${name}\``} : {kind: "hook", detail: named(name, bindings)};
396
+ } else if (tree.kind === JS.Kind.JsxTag && !hostTag(tree as JSX.Tag)) {
397
+ const name = tagName(tree as JSX.Tag);
398
+ if (name) miss = {kind: "child", detail: named(name, bindings, `<${name}>`)};
399
+ }
400
+ return !miss;
401
+ });
402
+ return {miss, wrapped};
403
+ }
404
+
405
+ /**
406
+ * What a `shallow` of `element` leaves out where {@link rendersHostElements} rejects it: an element of a component passed in
407
+ * its props or children, a component from a package, or what the component's own source renders. Undefined where it can't tell.
408
+ */
409
+ export function shallowMiss(element: J, imports: ReadonlyMap<string, ImportedExport>, components: HostComponents, composites: Composites,
410
+ bindings: ReturnType<typeof importBindings>): ShallowMiss | undefined {
411
+ if (element.kind !== JS.Kind.JsxTag) return undefined;
412
+ const tag = element as JSX.Tag;
413
+ const name = tag.openName.element;
414
+ if (!isIdentifier(name)) return undefined;
415
+ const source = imports.get(name.simpleName);
416
+ if (!source) {
417
+ const module = bindings.find(({local}) => local === name.simpleName)?.module;
418
+ return module && !module.startsWith(".") ? {kind: "package", detail: named(name.simpleName, bindings, `<${name.simpleName}>`)} : undefined;
419
+ }
420
+ if (components.get(source.path)?.has(source.name)) {
421
+ let passed: string | undefined;
422
+ walk(tag, tree => {
423
+ if (passed) return false;
424
+ if (tree !== tag && tree.kind === JS.Kind.JsxTag && !hostTag(tree as JSX.Tag)) passed = tagName(tree as JSX.Tag);
425
+ return !passed;
426
+ });
427
+ return passed ? {kind: "passed", detail: named(passed, bindings, `<${passed}>`)} : undefined;
428
+ }
429
+ const facts = composites.get(source.path);
430
+ const wrapper = facts?.wrapped.get(source.name);
431
+ return wrapper ? {kind: "wrapped", detail: `\`${wrapper}\``} : facts?.miss;
432
+ }
@@ -1,7 +1,10 @@
1
1
  import {JS, JSX, moduleNameOf, walk} from "@openrewrite/rewrite/javascript";
2
2
  import {isIdentifier, J} from "@openrewrite/rewrite/java";
3
3
  import {posix} from "path";
4
- import {importBindings, isRelativeSpecifier, resolveRelative} from "../util/module-imports";
4
+ import {exportedNames, importBindings, isRelativeSpecifier, packageName, Resolver} from "../util/module-imports";
5
+
6
+ export {packageName, resolver} from "../util/module-imports";
7
+ export type {Resolver} from "../util/module-imports";
5
8
  import {ConstantParts, constantStrings} from "./enzyme-constant-strings";
6
9
 
7
10
  /** An import a source renders: the module, and the export of it that a JSX tag in the source names. */
@@ -74,27 +77,6 @@ export function moduleFacts(cu: JS.CompilationUnit): ModuleFacts {
74
77
  return {portal: callsCreatePortal(cu), rendered, reExports, declares, forwards, imports: imported, strings: constantStrings(cu)};
75
78
  }
76
79
 
77
- /** Each name a named export clause exports, to the name it has in the module it comes from. */
78
- function exportedNames(clause: JS.NamedExports): Map<string, string> {
79
- const names = new Map<string, string>();
80
- for (const {element: exported} of clause.elements.elements) {
81
- if (exported.kind !== JS.Kind.ExportSpecifier) continue;
82
- const named = (exported as JS.ExportSpecifier).specifier;
83
- if (isIdentifier(named)) names.set(named.simpleName, named.simpleName);
84
- if (named.kind === JS.Kind.Alias && isIdentifier((named as JS.Alias).alias)) {
85
- const property = (named as JS.Alias).propertyName.element;
86
- names.set(((named as JS.Alias).alias as J.Identifier).simpleName,
87
- isIdentifier(property) ? property.simpleName : String((property as J.Literal).value));
88
- }
89
- }
90
- return names;
91
- }
92
-
93
- /** Where module specifiers of a source resolve: relative ones as Node resolves them, bare ones through a `baseUrl` alias. */
94
- export interface Resolver {
95
- (from: string, specifier: string): string | undefined;
96
- }
97
-
98
80
  /**
99
81
  * Whether the export `name` of the source at `path` may render into a portal: the source calls
100
82
  * `createPortal`, renders a component imported from a source whose export may, or re-exports `name`
@@ -162,28 +144,6 @@ export function packagePortal(module: string, name: string): boolean {
162
144
  return exports.has(subpath !== "" && name === "default" ? subpath.split("/")[0] : name);
163
145
  }
164
146
 
165
- /** The package a bare module specifier names, such as `@scope/name` for `@scope/name/sub`. */
166
- export function packageName(specifier: string): string {
167
- const parts = specifier.split("/");
168
- return specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0];
169
- }
170
-
171
- /**
172
- * Resolves relative specifiers among the scanned sources, and a bare one that no enclosing package
173
- * declares from each of `roots`, the way a `baseUrl` of the package or the repository resolves it.
174
- */
175
- export function resolver(modules: Modules, roots: readonly string[], declares: (name: string) => boolean): Resolver {
176
- return (from, specifier) => {
177
- const relative = resolveRelative(from, specifier, modules);
178
- if (relative || isRelativeSpecifier(specifier) || specifier.startsWith("node:") || declares(packageName(specifier))) return relative;
179
- for (const root of roots) {
180
- const aliased = resolveRelative(posix.join(root || ".", "_"), `./${specifier}`, modules);
181
- if (aliased) return aliased;
182
- }
183
- return undefined;
184
- };
185
- }
186
-
187
147
  export interface PortalContext {
188
148
  /** The test source. */
189
149
  sourcePath: string;
@@ -0,0 +1,278 @@
1
+ import {Cursor, TreePrinters} from "@openrewrite/rewrite";
2
+ import {JS} from "@openrewrite/rewrite/javascript";
3
+ import {isIdentifier, J} from "@openrewrite/rewrite/java";
4
+ import {eventKind, selectorKind} from "../search/find-enzyme-usage";
5
+ import {migrationReason} from "./enzyme-usage";
6
+ import type {BlockingReference} from "./enzyme-wrapper-scope";
7
+ import type {ShallowMiss} from "./enzyme-host-components";
8
+
9
+ /** Why the converter kept a render it analyzed on Enzyme, other than a use of its wrapper. */
10
+ export type RenderGate = "setProps" | "rootStyles" | "shallow" | "portal";
11
+
12
+ // The methods of Enzyme's wrappers, past which a chain reads what one returned, such as a DOM node
13
+ const ENZYME_WRAPPER_METHODS = new Set(["at", "childAt", "children", "closest", "contains", "containsAllMatchingElements",
14
+ "containsAnyMatchingElements", "containsMatchingElement", "context", "debug", "dive", "every", "everyWhere", "exists", "filter",
15
+ "filterWhere", "find", "findWhere", "first", "forEach", "get", "getDOMNode", "getElement", "getElements", "getNode", "getNodes",
16
+ "hasClass", "hostNodes", "html", "instance", "invoke", "is", "isEmptyRender", "key", "last", "map", "matchesElement", "name",
17
+ "not", "parent", "parents", "prop", "props", "reduce", "reduceRight", "ref", "render", "renderProp", "root", "setContext",
18
+ "setProps", "setState", "shallow", "simulate", "simulateError", "slice", "some", "someWhere", "state", "tap", "text", "type",
19
+ "unmount", "update"]);
20
+
21
+ // Calls that return another wrapper, which a variable then holds as Enzyme found it
22
+ const WRAPPER_RESULTS = new Set(["find", "at", "first", "last", "children", "childAt", "filter", "filterWhere", "findWhere",
23
+ "hostNodes", "closest", "parent", "parents", "dive", "not", "slice", "getElements", "getNodes"]);
24
+
25
+ const PASSED = "Blocked by a wrapper passed on: the recipe converts a wrapper only where each use is a read in the test itself. " +
26
+ "Inline what the helper reads here, or change the helper to take the element RTL queried, such as `container.querySelector(selector)`.";
27
+ const STORED = "Blocked by a stored find: Enzyme's found wrapper keeps the render as it was, while an RTL element is live. " +
28
+ "Query the element where each assertion reads it, such as `container.querySelector(selector)`, rather than keeping the found wrapper in a variable.";
29
+ const SNAPSHOT_RECIPE = "`org.openrewrite.react.migrate.enzyme-snapshots-to-react-testing-library`";
30
+ const SNAPSHOT_AFTER = "RTL records the DOM where Enzyme recorded a component tree, so run the tests once with `--updateSnapshot` and review the new snapshots.";
31
+ const SNAPSHOT = `Blocked by a snapshot of the wrapper, which this recipe leaves for review: ${SNAPSHOT_RECIPE} converts it to \`expect(asFragment()).toMatchSnapshot()\`. ` +
32
+ `Run that recipe instead. ${SNAPSHOT_AFTER}`;
33
+ const UNMOUNTED = "Blocked by a read after unmount: RTL's container is empty once the render unmounts. " +
34
+ "Assert before calling `unmount()`, or render again for what comes after.";
35
+ const FIND_HERE = "Blocked by `find`: Enzyme and the DOM can match different elements for this selector where it stands, " +
36
+ "as positions into matches of a selector without a tag in each part, or a part a component's props can match. " +
37
+ "Name the tag in each part of the selector, or call `hostNodes()` before taking a position.";
38
+ const SIMULATE_HERE = "Blocked by `simulate`: `fireEvent` doesn't dispatch this event as Enzyme does here, " +
39
+ "because React 15 and 16 need a render attached to the document, a click runs a link's or form control's default action, " +
40
+ "or the call isn't a statement of its own. Fire it as a statement on the element, or with `userEvent` where the default action is wanted.";
41
+ const GATES: Readonly<Record<RenderGate, string>> = {
42
+ setProps: "Blocked by `setProps`: the recipe writes `rerender` only for props it can merge into the element as written. " +
43
+ "Call `rerender` with the whole element and its new props.",
44
+ shallow: "Blocked by shallow rendering: the component renders other components or runs effects, which `shallow` leaves out and RTL's `render` runs. " +
45
+ "Render it with `render` and assert on what the whole tree renders. Where a test relies on a child not rendering, `jest.mock` that child's module with a stub.",
46
+ portal: "Blocked by a portal: a component it renders may render into a portal, which RTL renders outside the container. " +
47
+ "Query `screen` or `baseElement` for that content instead of the wrapper.",
48
+ rootStyles: "Blocked by root styles: a component of this package adds its `<style>` to the document root, which RTL's detached container lacks. " +
49
+ "Render without the `container` option, so the render is attached to the document, before reading text or markup."
50
+ };
51
+
52
+ const SHALLOW_MISSES: Readonly<Record<ShallowMiss["kind"], [string, string]>> = {
53
+ child: ["a child component", "`shallow` leaves each child component unrendered, and RTL's `render` renders it in full. " +
54
+ "Render it with `render` and assert on what the child renders, such as its text or role. Where a test relies on the child not rendering, `jest.mock` its module with a stub."],
55
+ effect: ["an effect or ref", "`shallow` runs no effect and attaches no ref, and RTL's `render` does both. " +
56
+ "Render it with `render`, and mock what the effect calls where a test relies on it not running."],
57
+ hook: ["a hook from outside React", "the hook may run effects, which `shallow` doesn't run and RTL's `render` does. " +
58
+ "Render it with `render`, and `jest.mock` the hook's module where a test relies on its effects not running."],
59
+ wrapped: ["a wrapped component", "`shallow` renders only the wrapper's output, and RTL's `render` renders through it. " +
60
+ "Render it with `render` and assert on what the inner component renders, wrapping it in what the wrapper needs, such as a store or theme provider."],
61
+ package: ["a component the recipe can't read", "it may render other components or run effects, which `shallow` leaves out and RTL's `render` runs. " +
62
+ "Render it with `render` and assert on what the whole tree renders."],
63
+ passed: ["an element passed in", "`shallow` leaves an element of a component in the props or children unrendered, and RTL's `render` renders it in full. " +
64
+ "Render it with `render` and assert on what that element renders, or pass a host element, such as a `<div>`, where a test needs only a placeholder."]
65
+ };
66
+
67
+ /** The suggested action for a `shallow` the recipe keeps, naming what it leaves out where that is known. */
68
+ export function blockedByShallow(miss: ShallowMiss | undefined): string {
69
+ if (!miss) return GATES.shallow;
70
+ const [what, why] = SHALLOW_MISSES[miss.kind];
71
+ return `Blocked by shallow rendering of ${what} (${miss.detail}): ${why}`;
72
+ }
73
+
74
+ /** Why the converter leaves every render of a source on Enzyme. */
75
+ export type FileGate = "react" | "rtl" | "rtlMissing" | "commonjs";
76
+
77
+ const FILES: Readonly<Record<FileGate, string>> = {
78
+ react: "Blocked for this file by its React: the recipe converts packages on React and React DOM 15.5 to 18, of the same major. " +
79
+ "On React 19, migrate the file by hand to RTL 16's `render`, `screen` and `fireEvent`, following the file's other rows.",
80
+ rtl: "Blocked for this file by its React Testing Library: the recipe converts with RTL 12 on React 15.5 to 17, or RTL 16 on React 18. " +
81
+ "Move `@testing-library/react` to that version, then run the recipe again.",
82
+ rtlMissing: "Blocked for this file: the run added no React Testing Library, as no package of the file declares Enzyme. " +
83
+ "Add `@testing-library/react` to the package that provides Enzyme to its tests, then run the recipe again.",
84
+ commonjs: "Blocked for this file by `require`: the recipe converts ES modules only. Load the file's modules with `import`, then run the recipe again."
85
+ };
86
+
87
+ export function blockedByFile(gate: FileGate): string {
88
+ return FILES[gate];
89
+ }
90
+
91
+ /** Why a dependency step added no RTL to a package root that declares Enzyme, known once the step has generated. */
92
+ export type NotAdded = {kind: "withheld" | "peer" | "gate"} | {kind: "declined", warning?: string};
93
+
94
+ /** How the package manager declined an edit, read from the warning `AddDependency` leaves on the manifest. */
95
+ type Decline = "eresolve" | "engine" | "yarn" | "registry" | "other";
96
+
97
+ const DECLINES: Readonly<Record<Decline, string>> = {
98
+ eresolve: "npm rejects the edit with a peer dependency conflict (ERESOLVE). Where a plain `npm ci` of the unchanged repository fails too, " +
99
+ "the conflict is the repository's: resolve it, then run the recipe again.",
100
+ engine: "the recipe can't regenerate a lockfile of this package manager's version. Add `@testing-library/react` with the repository's own package manager, " +
101
+ "then run the recipe again.",
102
+ yarn: "yarn rejects the edit. Add `@testing-library/react` with the repository's yarn to see why, then run the recipe again.",
103
+ registry: "a registry request failed while the lockfile was regenerated. Run the recipe again.",
104
+ other: "the package manager declined the edit. Add `@testing-library/react` with the repository's own package manager to see why, then run the recipe again."
105
+ };
106
+
107
+ function declineOf(warning: string): Decline {
108
+ if (/ERESOLVE/.test(warning)) return "eresolve";
109
+ if (/pnpm \S+ is not a release|cannot know what \S+ \S+ writes/.test(warning)) return "engine";
110
+ if (/Failed to fetch|SocketTimeout|ETIMEDOUT|ECONNRESET|ENOTFOUND|EAI_AGAIN/.test(warning)) return "registry";
111
+ if (/yarn rejects/.test(warning)) return "yarn";
112
+ return "other";
113
+ }
114
+
115
+ /** What names the cause in a decline's warning, such as the packages of an npm peer conflict, short enough to group rows by. */
116
+ function declineDetail(decline: Decline, warning: string): string | undefined {
117
+ if (decline === "eresolve") {
118
+ // REGEX: the package npm was resolving, and the version it found that conflicts, from npm's ERESOLVE report
119
+ const resolving = /While resolving: (\S+)/.exec(warning)?.[1];
120
+ const found = /Found: (\S+)/.exec(warning)?.[1];
121
+ return resolving && found ? `\`${resolving}\` against \`${found}\`` : undefined;
122
+ }
123
+ // REGEX: a package manager and its version, such as "pnpm 10.11.0"
124
+ if (decline === "engine") return /\b(pnpm|yarn|npm|bun) (\d+\.\d+\.\d+)/.exec(warning)?.slice(1).join(" ");
125
+ return undefined;
126
+ }
127
+
128
+ /** The suggested action for a source kept on Enzyme because the run added no RTL to `root`, the package declaring Enzyme. */
129
+ export function blockedByPackage(root: string, outcome: NotAdded | undefined): string {
130
+ const manifest = `\`${root}package.json\``;
131
+ switch (outcome?.kind) {
132
+ case "withheld":
133
+ return `Blocked for this file: the run added no React Testing Library to ${manifest}, as no test in its lockfile converts with it. ` +
134
+ "Resolve the other review rows of these tests, then run the recipe again.";
135
+ case "peer":
136
+ return `Blocked for this file: the run added no React Testing Library 16 to ${manifest}, as its peer \`@testing-library/dom\` ` +
137
+ "was declined in the same lockfile. Add both with the repository's own package manager, then run the recipe again.";
138
+ case "gate":
139
+ return `Blocked for this file: the run added no React Testing Library to ${manifest}, as its lockfile doesn't resolve React and React DOM ` +
140
+ "to the versions that RTL supports. Install, so that the lockfile records them, then run the recipe again.";
141
+ case "declined": {
142
+ const decline = declineOf(outcome.warning ?? "");
143
+ const detail = declineDetail(decline, outcome.warning ?? "");
144
+ return `Blocked for this file: the run added no React Testing Library to ${manifest}${detail ? ` (${detail})` : ""}, as ${DECLINES[decline]}`;
145
+ }
146
+ default:
147
+ return FILES.rtlMissing;
148
+ }
149
+ }
150
+
151
+ /** The suggested action for a render that the uses at `references` keep on Enzyme, naming the first of them that isn't a snapshot the snapshot recipe converts. */
152
+ export async function blockedByUses(references: BlockingReference[]): Promise<string> {
153
+ const snapshots = references.filter(reference => reference.snapshot).length;
154
+ const first = references.find(reference => !reference.snapshot);
155
+ const uses = references.length > 1 ? `First of ${references.length} uses that keep it on Enzyme` : "The use";
156
+ if (!first) return `${SNAPSHOT} ${uses}: \`${await snippet(references[0].snapshot!)}\``;
157
+ const {top, calls} = chainOf(first.cursor);
158
+ const action = first.unmounted ? UNMOUNTED : actionFor(top, calls, first.cursor);
159
+ const shown = calls.length === 0 && !first.unmounted ? passedTo(first.cursor) ?? top : top;
160
+ const rest = snapshots === 0 ? "" : ` ${snapshots === 1 ? "Its snapshot assertion converts" : `Its ${snapshots} snapshot assertions convert`} ` +
161
+ `with ${SNAPSHOT_RECIPE} once the other uses do.`;
162
+ return `${action} ${uses}: \`${await snippet(shown)}\`${rest}`;
163
+ }
164
+
165
+ async function snippet(node: J): Promise<string> {
166
+ // REGEX: the comments a statement starts with, which print with the node that begins it
167
+ const printed = (await TreePrinters.printer(JS.Kind.CompilationUnit).print(node)).replace(/^(\s*(\/\/[^\n]*|\/\*[\s\S]*?\*\/))+/, "")
168
+ .trim().replace(/\s+/g, " ");
169
+ return printed.length > 80 ? `${printed.slice(0, 77)}...` : printed;
170
+ }
171
+
172
+ /** The call or `return` a bare wrapper is handed to, which says more than the wrapper's name. */
173
+ function passedTo(reference: Cursor): J | undefined {
174
+ const parent = reference.parentTree()?.value as J | undefined;
175
+ return parent?.kind === J.Kind.MethodInvocation || parent?.kind === J.Kind.NewClass || parent?.kind === J.Kind.Return ? parent : undefined;
176
+ }
177
+
178
+ export function blockedByGate(gate: RenderGate): string {
179
+ return GATES[gate];
180
+ }
181
+
182
+ /** The calls and accesses on the wrapper at `reference`, outermost last. */
183
+ function chainOf(reference: Cursor): {top: J, calls: J.MethodInvocation[]} {
184
+ let top = reference.value as J;
185
+ const calls: J.MethodInvocation[] = [];
186
+ for (let c = reference.parentTree(); c; c = c.parentTree()) {
187
+ const node = c.value as J;
188
+ if (node.kind === J.Kind.MethodInvocation && (node as J.MethodInvocation).select?.element === top) calls.push(node as J.MethodInvocation);
189
+ else if (!(node.kind === J.Kind.FieldAccess && (node as J.FieldAccess).target === top) &&
190
+ !(node.kind === J.Kind.ArrayAccess && (node as J.ArrayAccess).indexed === top)) break;
191
+ top = node;
192
+ }
193
+ return {top, calls};
194
+ }
195
+
196
+ function actionFor(top: J, calls: J.MethodInvocation[], reference: Cursor): string {
197
+ if (calls.length === 0) return PASSED;
198
+ let parent = reference.parentTree();
199
+ while (parent && parent.value !== top) parent = parent.parentTree();
200
+ const holder = parent?.parentTree()?.value as J | undefined;
201
+ // A component selector has no DOM query, whatever reads its matches
202
+ const component = calls.find(call => call.name.simpleName === "find" && selectorKind("find", call.arguments.elements[0]?.element) === "component");
203
+ const enzymeCalls = calls.filter(call => ENZYME_WRAPPER_METHODS.has(call.name.simpleName));
204
+ const last = enzymeCalls[enzymeCalls.length - 1] ?? calls[calls.length - 1];
205
+ if (!component && WRAPPER_RESULTS.has(last.name.simpleName)) {
206
+ if (holder?.kind === J.Kind.NamedVariable || holder?.kind === J.Kind.Assignment) return STORED;
207
+ if (last.name.simpleName !== "find") return PASSED;
208
+ }
209
+ const blocking = component ?? last;
210
+ const api = blocking.name.simpleName;
211
+ const args = blocking.arguments.elements.map(argument => argument.element);
212
+ const selector = selectorKind(api, args[0]);
213
+ const event = eventKind(api, args);
214
+ // Read on its own, a DOM selector or a plain event converts, so here it is where it stands that keeps it
215
+ if (selector === "dom") return FIND_HERE;
216
+ if (event === "event") return SIMULATE_HERE;
217
+ return `Blocked by \`${api}\`: ${migrationReason(api, selector, event).suggestedAction}`;
218
+ }
219
+
220
+ /** A render of a shared wrapper whose own test converts, where another test of the wrapper keeps it on Enzyme. */
221
+ export function blockedByShared(name: string): string {
222
+ return `Blocked by another test of the shared \`${name}\`: the recipe converts a wrapper that its tests or a \`beforeEach\` assign only where every test of it converts. ` +
223
+ "This test's uses convert, so see the rows of the other tests.";
224
+ }
225
+
226
+ const HELD = "the recipe converts a render that a `const` of the test declares, or one held in a `let` declared without a value that each test, " +
227
+ "or the last statement of a `beforeEach`, assigns before any other use.";
228
+
229
+ /**
230
+ * Why a render the converter didn't analyze stays on Enzyme, where its shape says so: a render held in a `let`, `var` or
231
+ * assignment, or returned from a named function. Any other shape gets nothing, which keeps the generic action.
232
+ */
233
+ export function blockedByShape(render: Cursor): string | undefined {
234
+ const call = render.value as J.MethodInvocation;
235
+ const api = call.name.simpleName;
236
+ const parent = render.parentTree();
237
+ const node = parent?.value as J | undefined;
238
+ if (node?.kind === J.Kind.NamedVariable && (node as J.VariableDeclarations.NamedVariable).initializer?.element === call) {
239
+ const variable = node as J.VariableDeclarations.NamedVariable;
240
+ const declaration = parent!.parentTree()?.value as J | undefined;
241
+ const keyword = declaration?.kind === J.Kind.VariableDeclarations ?
242
+ (declaration as J.VariableDeclarations).modifiers.find(modifier => modifier.keyword === "let" || modifier.keyword === "var")?.keyword : undefined;
243
+ if (!keyword || !isIdentifier(variable.name)) return undefined;
244
+ const name = variable.name.simpleName;
245
+ return `Blocked by \`${keyword} ${name}\`: ${HELD} Give each render a \`const\` of its own, such as \`const ${name} = ${api}(...)\`, in the test that reads it.`;
246
+ }
247
+ if (node?.kind === J.Kind.Assignment && (node as J.Assignment).assignment.element === call) {
248
+ const target = (node as J.Assignment).variable;
249
+ if (!isIdentifier(target)) return undefined;
250
+ const name = target.simpleName;
251
+ return `Blocked by assigning the render to \`${name}\`: ${HELD} Otherwise give each render a \`const\` of its own, such as \`const ${name} = ${api}(...)\`, in the test that reads it.`;
252
+ }
253
+ const returning = node?.kind === J.Kind.Return && (node as J.Return).expression === call ? enclosingFunction(parent!) :
254
+ node?.kind === J.Kind.Lambda && (node as J.Lambda).body === call ? parent : undefined;
255
+ const name = returning && functionName(returning);
256
+ if (!name) return undefined;
257
+ return `Blocked by a render that \`${name}\` returns: the recipe converts a render where the test that reads it declares it. ` +
258
+ `Render in each test with \`const wrapper = ${api}(...)\`, or have \`${name}\` return the result of RTL's \`render\` and change what its callers read by hand.`;
259
+ }
260
+
261
+ function enclosingFunction(cursor: Cursor): Cursor | undefined {
262
+ for (let c = cursor.parentTree(); c; c = c.parentTree()) {
263
+ const kind = (c.value as J).kind;
264
+ if (kind === J.Kind.MethodDeclaration || kind === J.Kind.Lambda) return c;
265
+ }
266
+ return undefined;
267
+ }
268
+
269
+ /** The name of a function declaration, or of the variable an arrow function initializes; a callback has none. */
270
+ function functionName(fn: Cursor): string | undefined {
271
+ const node = fn.value as J;
272
+ if (node.kind === J.Kind.MethodDeclaration) return (node as J.MethodDeclaration).name.simpleName;
273
+ let outer = fn.parentTree();
274
+ if ((outer?.value as J | undefined)?.kind === JS.Kind.ArrowFunction) outer = outer!.parentTree();
275
+ const holder = outer?.value as J | undefined;
276
+ return holder?.kind === J.Kind.NamedVariable && isIdentifier((holder as J.VariableDeclarations.NamedVariable).name) ?
277
+ ((holder as J.VariableDeclarations.NamedVariable).name as J.Identifier).simpleName : undefined;
278
+ }