@openrewrite/recipes-react 0.21.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.
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +27 -0
- package/dist/index.js.map +1 -1
- package/dist/mui/adapt-v4-theme.d.ts +8 -0
- package/dist/mui/adapt-v4-theme.d.ts.map +1 -0
- package/dist/mui/adapt-v4-theme.js +65 -0
- package/dist/mui/adapt-v4-theme.js.map +1 -0
- package/dist/mui/add-component-prop.d.ts +18 -0
- package/dist/mui/add-component-prop.d.ts.map +1 -0
- package/dist/mui/add-component-prop.js +53 -0
- package/dist/mui/add-component-prop.js.map +1 -0
- package/dist/mui/add-emotion-prepend.d.ts +8 -0
- package/dist/mui/add-emotion-prepend.d.ts.map +1 -0
- package/dist/mui/add-emotion-prepend.js +71 -0
- package/dist/mui/add-emotion-prepend.js.map +1 -0
- package/dist/mui/change-module-specifier.d.ts +14 -0
- package/dist/mui/change-module-specifier.d.ts.map +1 -0
- package/dist/mui/change-module-specifier.js +95 -0
- package/dist/mui/change-module-specifier.js.map +1 -0
- package/dist/mui/convert-mui-imports.d.ts +14 -0
- package/dist/mui/convert-mui-imports.d.ts.map +1 -0
- package/dist/mui/convert-mui-imports.js +195 -0
- package/dist/mui/convert-mui-imports.js.map +1 -0
- package/dist/mui/convert-prop-to-sx.d.ts +22 -0
- package/dist/mui/convert-prop-to-sx.d.ts.map +1 -0
- package/dist/mui/convert-prop-to-sx.js +99 -0
- package/dist/mui/convert-prop-to-sx.js.map +1 -0
- package/dist/mui/index.d.ts +32 -0
- package/dist/mui/index.d.ts.map +1 -0
- package/dist/mui/index.js +67 -0
- package/dist/mui/index.js.map +1 -0
- package/dist/mui/jsx-attributes.d.ts +27 -0
- package/dist/mui/jsx-attributes.d.ts.map +1 -0
- package/dist/mui/jsx-attributes.js +140 -0
- package/dist/mui/jsx-attributes.js.map +1 -0
- package/dist/mui/mark-manual-migration.d.ts +16 -0
- package/dist/mui/mark-manual-migration.d.ts.map +1 -0
- package/dist/mui/mark-manual-migration.js +73 -0
- package/dist/mui/mark-manual-migration.js.map +1 -0
- package/dist/mui/mark-palette-mode-usage.d.ts +12 -0
- package/dist/mui/mark-palette-mode-usage.d.ts.map +1 -0
- package/dist/mui/mark-palette-mode-usage.js +50 -0
- package/dist/mui/mark-palette-mode-usage.js.map +1 -0
- package/dist/mui/move-component-prop-to-slot.d.ts +22 -0
- package/dist/mui/move-component-prop-to-slot.d.ts.map +1 -0
- package/dist/mui/move-component-prop-to-slot.js +87 -0
- package/dist/mui/move-component-prop-to-slot.js.map +1 -0
- package/dist/mui/move-primary-text-to-children.d.ts +12 -0
- package/dist/mui/move-primary-text-to-children.d.ts.map +1 -0
- package/dist/mui/move-primary-text-to-children.js +52 -0
- package/dist/mui/move-primary-text-to-children.js.map +1 -0
- package/dist/mui/move-system-props-to-sx.d.ts +16 -0
- package/dist/mui/move-system-props-to-sx.d.ts.map +1 -0
- package/dist/mui/move-system-props-to-sx.js +122 -0
- package/dist/mui/move-system-props-to-sx.js.map +1 -0
- package/dist/mui/mui-components.d.ts +8 -0
- package/dist/mui/mui-components.d.ts.map +1 -0
- package/dist/mui/mui-components.js +41 -0
- package/dist/mui/mui-components.js.map +1 -0
- package/dist/mui/mui-tag-visitor.d.ts +5 -0
- package/dist/mui/mui-tag-visitor.d.ts.map +1 -0
- package/dist/mui/mui-tag-visitor.js +54 -0
- package/dist/mui/mui-tag-visitor.js.map +1 -0
- package/dist/mui/pre-v5-recipe.d.ts +14 -0
- package/dist/mui/pre-v5-recipe.d.ts.map +1 -0
- package/dist/mui/pre-v5-recipe.js +88 -0
- package/dist/mui/pre-v5-recipe.js.map +1 -0
- package/dist/mui/remove-component-prop.d.ts +18 -0
- package/dist/mui/remove-component-prop.d.ts.map +1 -0
- package/dist/mui/remove-component-prop.js +55 -0
- package/dist/mui/remove-component-prop.js.map +1 -0
- package/dist/mui/remove-root-ref.d.ts +8 -0
- package/dist/mui/remove-root-ref.d.ts.map +1 -0
- package/dist/mui/remove-root-ref.js +61 -0
- package/dist/mui/remove-root-ref.js.map +1 -0
- package/dist/mui/remove-spacing-px-suffix.d.ts +8 -0
- package/dist/mui/remove-spacing-px-suffix.d.ts.map +1 -0
- package/dist/mui/remove-spacing-px-suffix.js +62 -0
- package/dist/mui/remove-spacing-px-suffix.js.map +1 -0
- package/dist/mui/rename-component-prop.d.ts +20 -0
- package/dist/mui/rename-component-prop.d.ts.map +1 -0
- package/dist/mui/rename-component-prop.js +66 -0
- package/dist/mui/rename-component-prop.js.map +1 -0
- package/dist/mui/rename-joy-css-variables.d.ts +8 -0
- package/dist/mui/rename-joy-css-variables.d.ts.map +1 -0
- package/dist/mui/rename-joy-css-variables.js +51 -0
- package/dist/mui/rename-joy-css-variables.js.map +1 -0
- package/dist/mui/rename-theme-palette-type.d.ts +8 -0
- package/dist/mui/rename-theme-palette-type.d.ts.map +1 -0
- package/dist/mui/rename-theme-palette-type.js +61 -0
- package/dist/mui/rename-theme-palette-type.js.map +1 -0
- package/dist/mui/replace-box-border-radius.d.ts +10 -0
- package/dist/mui/replace-box-border-radius.d.ts.map +1 -0
- package/dist/mui/replace-box-border-radius.js +50 -0
- package/dist/mui/replace-box-border-radius.js.map +1 -0
- package/dist/mui/replace-breakpoints-width.d.ts +8 -0
- package/dist/mui/replace-breakpoints-width.d.ts.map +1 -0
- package/dist/mui/replace-breakpoints-width.js +46 -0
- package/dist/mui/replace-breakpoints-width.js.map +1 -0
- package/dist/mui/replace-component-class.d.ts +18 -0
- package/dist/mui/replace-component-class.d.ts.map +1 -0
- package/dist/mui/replace-component-class.js +126 -0
- package/dist/mui/replace-component-class.js.map +1 -0
- package/dist/mui/replace-components-with-slots.d.ts +14 -0
- package/dist/mui/replace-components-with-slots.d.ts.map +1 -0
- package/dist/mui/replace-components-with-slots.js +69 -0
- package/dist/mui/replace-components-with-slots.js.map +1 -0
- package/dist/mui/replace-import-paths.d.ts +14 -0
- package/dist/mui/replace-import-paths.d.ts.map +1 -0
- package/dist/mui/replace-import-paths.js +101 -0
- package/dist/mui/replace-import-paths.js.map +1 -0
- package/dist/mui/replace-in-string-literals.d.ts +15 -0
- package/dist/mui/replace-in-string-literals.d.ts.map +1 -0
- package/dist/mui/replace-in-string-literals.js +62 -0
- package/dist/mui/replace-in-string-literals.js.map +1 -0
- package/dist/mui/replace-list-item-button-prop.d.ts +12 -0
- package/dist/mui/replace-list-item-button-prop.d.ts.map +1 -0
- package/dist/mui/replace-list-item-button-prop.js +80 -0
- package/dist/mui/replace-list-item-button-prop.js.map +1 -0
- package/dist/mui/replace-tabs-scroll-buttons.d.ts +8 -0
- package/dist/mui/replace-tabs-scroll-buttons.d.ts.map +1 -0
- package/dist/mui/replace-tabs-scroll-buttons.js +41 -0
- package/dist/mui/replace-tabs-scroll-buttons.js.map +1 -0
- package/dist/mui/replace-theme-color-functions.d.ts +8 -0
- package/dist/mui/replace-theme-color-functions.d.ts.map +1 -0
- package/dist/mui/replace-theme-color-functions.js +72 -0
- package/dist/mui/replace-theme-color-functions.js.map +1 -0
- package/dist/mui/replace-theme-spacing-unit.d.ts +8 -0
- package/dist/mui/replace-theme-spacing-unit.d.ts.map +1 -0
- package/dist/mui/replace-theme-spacing-unit.js +77 -0
- package/dist/mui/replace-theme-spacing-unit.js.map +1 -0
- package/dist/mui/replace-typography-round.d.ts +8 -0
- package/dist/mui/replace-typography-round.d.ts.map +1 -0
- package/dist/mui/replace-typography-round.js +44 -0
- package/dist/mui/replace-typography-round.js.map +1 -0
- package/dist/mui/shift-hidden-down-props.d.ts +10 -0
- package/dist/mui/shift-hidden-down-props.d.ts.map +1 -0
- package/dist/mui/shift-hidden-down-props.js +49 -0
- package/dist/mui/shift-hidden-down-props.js.map +1 -0
- package/dist/mui/theme-access.d.ts +5 -0
- package/dist/mui/theme-access.d.ts.map +1 -0
- package/dist/mui/theme-access.js +21 -0
- package/dist/mui/theme-access.js.map +1 -0
- package/dist/mui/update-theme-breakpoints.d.ts +10 -0
- package/dist/mui/update-theme-breakpoints.d.ts.map +1 -0
- package/dist/mui/update-theme-breakpoints.js +58 -0
- package/dist/mui/update-theme-breakpoints.js.map +1 -0
- package/dist/mui/upgrade-grid-props.d.ts +16 -0
- package/dist/mui/upgrade-grid-props.d.ts.map +1 -0
- package/dist/mui/upgrade-grid-props.js +90 -0
- package/dist/mui/upgrade-grid-props.js.map +1 -0
- package/dist/search/find-enzyme-usage.d.ts +4 -0
- package/dist/search/find-enzyme-usage.d.ts.map +1 -1
- package/dist/search/find-enzyme-usage.js +91 -7
- package/dist/search/find-enzyme-usage.js.map +1 -1
- package/dist/testing/enzyme-host-components.d.ts +12 -0
- package/dist/testing/enzyme-host-components.d.ts.map +1 -1
- package/dist/testing/enzyme-host-components.js +100 -0
- package/dist/testing/enzyme-host-components.js.map +1 -1
- package/dist/testing/enzyme-render-blockers.d.ts +13 -4
- package/dist/testing/enzyme-render-blockers.d.ts.map +1 -1
- package/dist/testing/enzyme-render-blockers.js +162 -6
- package/dist/testing/enzyme-render-blockers.js.map +1 -1
- package/dist/testing/enzyme-to-react-testing-library.d.ts +9 -2
- package/dist/testing/enzyme-to-react-testing-library.d.ts.map +1 -1
- package/dist/testing/enzyme-to-react-testing-library.js +163 -16
- package/dist/testing/enzyme-to-react-testing-library.js.map +1 -1
- package/dist/testing/enzyme-usage.d.ts +7 -0
- package/dist/testing/enzyme-usage.d.ts.map +1 -1
- package/dist/testing/enzyme-usage.js +8 -1
- package/dist/testing/enzyme-usage.js.map +1 -1
- package/dist/testing/enzyme-wrapper-scope.d.ts +8 -5
- package/dist/testing/enzyme-wrapper-scope.d.ts.map +1 -1
- package/dist/testing/enzyme-wrapper-scope.js +16 -4
- package/dist/testing/enzyme-wrapper-scope.js.map +1 -1
- package/dist/zustand/redux-stores.d.ts +2 -0
- package/dist/zustand/redux-stores.d.ts.map +1 -1
- package/dist/zustand/redux-stores.js +120 -6
- package/dist/zustand/redux-stores.js.map +1 -1
- package/dist/zustand/redux-to-zustand.d.ts.map +1 -1
- package/dist/zustand/redux-to-zustand.js +10 -4
- package/dist/zustand/redux-to-zustand.js.map +1 -1
- package/dist/zustand/zustand-plan.d.ts +7 -0
- package/dist/zustand/zustand-plan.d.ts.map +1 -1
- package/dist/zustand/zustand-plan.js +141 -21
- package/dist/zustand/zustand-plan.js.map +1 -1
- package/package.json +1 -1
- package/src/index.ts +10 -0
- package/src/mui/adapt-v4-theme.ts +43 -0
- package/src/mui/add-component-prop.ts +43 -0
- package/src/mui/add-emotion-prepend.ts +48 -0
- package/src/mui/change-module-specifier.ts +71 -0
- package/src/mui/convert-mui-imports.ts +184 -0
- package/src/mui/convert-prop-to-sx.ts +89 -0
- package/src/mui/index.ts +31 -0
- package/src/mui/jsx-attributes.ts +133 -0
- package/src/mui/mark-manual-migration.ts +53 -0
- package/src/mui/mark-palette-mode-usage.ts +36 -0
- package/src/mui/move-component-prop-to-slot.ts +84 -0
- package/src/mui/move-primary-text-to-children.ts +41 -0
- package/src/mui/move-system-props-to-sx.ts +118 -0
- package/src/mui/mui-components.ts +40 -0
- package/src/mui/mui-tag-visitor.ts +36 -0
- package/src/mui/pre-v5-recipe.ts +82 -0
- package/src/mui/remove-component-prop.ts +43 -0
- package/src/mui/remove-root-ref.ts +41 -0
- package/src/mui/remove-spacing-px-suffix.ts +43 -0
- package/src/mui/rename-component-prop.ts +55 -0
- package/src/mui/rename-joy-css-variables.ts +41 -0
- package/src/mui/rename-theme-palette-type.ts +42 -0
- package/src/mui/replace-box-border-radius.ts +42 -0
- package/src/mui/replace-breakpoints-width.ts +28 -0
- package/src/mui/replace-component-class.ts +97 -0
- package/src/mui/replace-components-with-slots.ts +61 -0
- package/src/mui/replace-import-paths.ts +100 -0
- package/src/mui/replace-in-string-literals.ts +44 -0
- package/src/mui/replace-list-item-button-prop.ts +59 -0
- package/src/mui/replace-tabs-scroll-buttons.ts +31 -0
- package/src/mui/replace-theme-color-functions.ts +55 -0
- package/src/mui/replace-theme-spacing-unit.ts +59 -0
- package/src/mui/replace-typography-round.ts +29 -0
- package/src/mui/shift-hidden-down-props.ts +44 -0
- package/src/mui/theme-access.ts +18 -0
- package/src/mui/update-theme-breakpoints.ts +47 -0
- package/src/mui/upgrade-grid-props.ts +82 -0
- package/src/search/find-enzyme-usage.ts +80 -7
- package/src/testing/enzyme-host-components.ts +110 -0
- package/src/testing/enzyme-render-blockers.ts +174 -9
- package/src/testing/enzyme-to-react-testing-library.ts +159 -25
- package/src/testing/enzyme-usage.ts +13 -0
- package/src/testing/enzyme-wrapper-scope.ts +27 -6
- package/src/zustand/redux-stores.ts +119 -5
- package/src/zustand/redux-to-zustand.ts +12 -5
- package/src/zustand/zustand-plan.ts +159 -18
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import {ExecutionContext, TreeVisitor, check, not} from "@openrewrite/rewrite";
|
|
2
|
+
import {JavaScriptVisitor, isVendoredOrBundled} from "@openrewrite/rewrite/javascript";
|
|
3
|
+
import {PreV5Recipe} from "./pre-v5-recipe";
|
|
4
|
+
import {J} from "@openrewrite/rewrite/java";
|
|
5
|
+
import {endsWithName, stringValue, withString} from "./theme-access";
|
|
6
|
+
|
|
7
|
+
const NEXT = new Map([["xs", "sm"], ["sm", "md"], ["md", "lg"], ["lg", "xl"], ["xl", "xl"]]);
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Moves the breakpoint values of `theme.breakpoints.down()` and the end of `between()` up one step, since v5 reads
|
|
11
|
+
* them as exclusive.
|
|
12
|
+
*
|
|
13
|
+
* Before: `theme.breakpoints.down('sm')`, `theme.breakpoints.between('sm', 'md')`
|
|
14
|
+
* After: `theme.breakpoints.down('md')`, `theme.breakpoints.between('sm', 'lg')`
|
|
15
|
+
*
|
|
16
|
+
* It is not idempotent: run it once.
|
|
17
|
+
*
|
|
18
|
+
* @see https://mui.com/material-ui/migration/v5-component-changes/#theme
|
|
19
|
+
*/
|
|
20
|
+
export class UpdateThemeBreakpoints extends PreV5Recipe {
|
|
21
|
+
readonly name = "org.openrewrite.react.mui.update-theme-breakpoints";
|
|
22
|
+
readonly displayName: string = "Update theme breakpoint values for v5";
|
|
23
|
+
readonly description: string = "Moves the breakpoint passed to `theme.breakpoints.down()`, and the second one passed to `between()`, up one step to match the v5 logic. Not idempotent: run it once.";
|
|
24
|
+
|
|
25
|
+
/** The literals shifted so far in a run, which the recipe instance keeps across cycles, since a second cycle would shift them again. */
|
|
26
|
+
private readonly shifted = new Set<string>();
|
|
27
|
+
|
|
28
|
+
protected async v4Editor(): Promise<TreeVisitor<any, ExecutionContext>> {
|
|
29
|
+
const shifted = this.shifted;
|
|
30
|
+
return check(not(isVendoredOrBundled()), new class extends JavaScriptVisitor<ExecutionContext> {
|
|
31
|
+
override async visitMethodInvocation(invocation: J.MethodInvocation, ctx: ExecutionContext): Promise<J | undefined> {
|
|
32
|
+
const visited = await super.visitMethodInvocation(invocation, ctx) as J.MethodInvocation;
|
|
33
|
+
const name = visited.name.simpleName;
|
|
34
|
+
if ((name !== "down" && name !== "between") || !endsWithName(visited.select?.element, "breakpoints")) return visited;
|
|
35
|
+
const elements = visited.arguments.elements.map((a, i) => {
|
|
36
|
+
const value = stringValue(a.element);
|
|
37
|
+
const next = value && NEXT.get(value);
|
|
38
|
+
if (!next || !(name === "down" || i === 1) || shifted.has(a.element.id)) return a;
|
|
39
|
+
shifted.add(a.element.id);
|
|
40
|
+
return {...a, element: withString(a.element as J.Literal, next)};
|
|
41
|
+
});
|
|
42
|
+
if (elements.every((e, i) => e === visited.arguments.elements[i])) return visited;
|
|
43
|
+
return {...visited, arguments: {...visited.arguments, elements}} as J.MethodInvocation;
|
|
44
|
+
}
|
|
45
|
+
}());
|
|
46
|
+
}
|
|
47
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import {Cursor, ExecutionContext, Option, Recipe, TreeVisitor} from "@openrewrite/rewrite";
|
|
2
|
+
import {JSX} from "@openrewrite/rewrite/javascript";
|
|
3
|
+
import {J} from "@openrewrite/rewrite/java";
|
|
4
|
+
import {
|
|
5
|
+
appendProperty, attributeExpression, bare, hasSpread, newAttribute, newObject, newProperty, sourceExpression, withAttributes
|
|
6
|
+
} from "./jsx-attributes";
|
|
7
|
+
import {attributeName} from "./mui-components";
|
|
8
|
+
import {muiTagEditor} from "./mui-tag-visitor";
|
|
9
|
+
|
|
10
|
+
const DEFAULT_BREAKPOINTS = ["xs", "sm", "md", "lg", "xl"];
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Moves the breakpoint props of the responsive `Grid` into its `size` and `offset` props, and drops `item` and
|
|
14
|
+
* `zeroMinWidth`.
|
|
15
|
+
*
|
|
16
|
+
* Before: `<Grid item xs={12} sm={6} xsOffset={2} />`
|
|
17
|
+
* After: `<Grid size={{ xs: 12, sm: 6 }} offset={2} />`
|
|
18
|
+
*
|
|
19
|
+
* A prop without a value, such as a bare `xs`, becomes `"grow"`. A tag with a spread attribute is left alone.
|
|
20
|
+
*
|
|
21
|
+
* @see https://mui.com/material-ui/migration/upgrade-to-grid-v2/
|
|
22
|
+
*/
|
|
23
|
+
export class UpgradeGridProps extends Recipe {
|
|
24
|
+
readonly name = "org.openrewrite.react.mui.upgrade-grid-props";
|
|
25
|
+
readonly displayName: string = "Upgrade the props of Grid to `size` and `offset`";
|
|
26
|
+
readonly description: string = "Moves the breakpoint props of the responsive Grid, `xs={12}` and `xsOffset={2}`, into its `size` and `offset` props, and removes `item` and `zeroMinWidth`. Tags with a spread attribute are left alone.";
|
|
27
|
+
|
|
28
|
+
@Option({displayName: "Component name", description: "The Grid component, `Grid` or `Grid2`.", example: "Grid"})
|
|
29
|
+
componentName!: string;
|
|
30
|
+
|
|
31
|
+
@Option({displayName: "Breakpoints", description: "The breakpoints of the theme, separated by commas.", example: "xs,sm,md,lg,xl", required: false})
|
|
32
|
+
breakpoints?: string;
|
|
33
|
+
|
|
34
|
+
@Option({displayName: "Package name", description: "A package that re-exports Material UI.", example: "@org/ui", required: false})
|
|
35
|
+
packageName?: string;
|
|
36
|
+
|
|
37
|
+
constructor(options?: { componentName?: string; breakpoints?: string; packageName?: string }) {
|
|
38
|
+
super(options);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
|
|
42
|
+
const component = this.componentName;
|
|
43
|
+
const breakpoints = this.breakpoints ? this.breakpoints.split(",").map(s => s.trim()) : DEFAULT_BREAKPOINTS;
|
|
44
|
+
|
|
45
|
+
return muiTagEditor(component, this.packageName, async (visited, cursor) => {
|
|
46
|
+
if (hasSpread(visited)) return visited;
|
|
47
|
+
const attributes = visited.attributes.map(a => a.element as JSX.Attribute);
|
|
48
|
+
const sizes = attributes.filter(a => breakpoints.includes(attributeName(a) ?? ""));
|
|
49
|
+
const offsets = attributes.filter(a => breakpoints.includes((attributeName(a) ?? "").replace(/Offset$/, "")) && attributeName(a)!.endsWith("Offset"));
|
|
50
|
+
const obsolete = attributes.filter(a => ["item", "zeroMinWidth"].includes(attributeName(a) ?? ""));
|
|
51
|
+
if (!sizes.length && !offsets.length && !obsolete.length) return visited;
|
|
52
|
+
|
|
53
|
+
const created = new Map<JSX.Attribute, JSX.Attribute>();
|
|
54
|
+
for (const [group, name, suffix] of [[sizes, "size", ""], [offsets, "offset", "Offset"]] as const) {
|
|
55
|
+
if (!group.length) continue;
|
|
56
|
+
const entries: [string, J][] = [];
|
|
57
|
+
for (const attribute of group) {
|
|
58
|
+
const value = attribute.value ? attributeExpression(attribute) : undefined;
|
|
59
|
+
const isTrue = value?.kind === J.Kind.Literal && (value as J.Literal).value === true;
|
|
60
|
+
entries.push([attributeName(attribute)!.slice(0, attributeName(attribute)!.length - suffix.length),
|
|
61
|
+
!value || isTrue ? await sourceExpression(cursor, visited, '"grow"') : bare(value)]);
|
|
62
|
+
}
|
|
63
|
+
created.set(group[0], await build(cursor, visited, name, entries));
|
|
64
|
+
}
|
|
65
|
+
const removed = new Set<unknown>([...sizes, ...offsets, ...obsolete]);
|
|
66
|
+
return withAttributes(visited, visited.attributes.flatMap(a => {
|
|
67
|
+
const attribute = a.element as JSX.Attribute;
|
|
68
|
+
const replacement = created.get(attribute);
|
|
69
|
+
if (replacement) return [{...a, element: {...replacement, prefix: attribute.prefix}}];
|
|
70
|
+
return removed.has(attribute) ? [] : [a];
|
|
71
|
+
}));
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** `name={value}` for a lone `xs`, and `name={{ xs: a, md: b }}` otherwise. */
|
|
77
|
+
async function build(cursor: Cursor, tag: JSX.Tag, name: string, entries: [string, J][]): Promise<JSX.Attribute> {
|
|
78
|
+
if (entries.length === 1 && entries[0][0] === "xs") return newAttribute(cursor, tag, name, entries[0][1]);
|
|
79
|
+
let object = await newObject(cursor, tag, entries[0][0], entries[0][1]);
|
|
80
|
+
for (const [key, value] of entries.slice(1)) object = appendProperty(object, await newProperty(cursor, tag, key, value));
|
|
81
|
+
return newAttribute(cursor, tag, name, object);
|
|
82
|
+
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import {and, check, not, or, DataTable, ExecutionContext, foundSearchResult, Recipe, RecipeRef, TreeVisitor} from "@openrewrite/rewrite";
|
|
2
2
|
import {isObjectLiteral, isVendoredOrBundled, JavaScriptVisitor, JS, usesMethod, usesType} from "@openrewrite/rewrite/javascript";
|
|
3
3
|
import {isIdentifier, J, Type, TypedTree} from "@openrewrite/rewrite/java";
|
|
4
|
-
import {enclosingScope, ENZYME_GUIDE, ENZYME_USAGE_TABLE, enzymeMethod, enzymeModule, enzymeWrapper, EnzymeUsageRow, EventKind, FILE_BLOCKER, migrationReason, RENDER_BLOCKERS, SelectorKind} from "../testing/enzyme-usage";
|
|
4
|
+
import {enclosingScope, ENZYME_GUIDE, ENZYME_USAGE_TABLE, enzymeMethod, enzymeModule, enzymeWrapper, EnzymeUsageRow, EventKind, FILE_BLOCKER, migrationReason, RENDER_BLOCKERS, SELECTOR_VALUES, SelectorKind, unreadSelector} from "../testing/enzyme-usage";
|
|
5
5
|
import {domSelector, objectProperties, simulatedEvent} from "../testing/enzyme-wrapper-scope";
|
|
6
6
|
|
|
7
7
|
const LENGTH_ACTION = "Use the `length` of the `querySelectorAll` or `getAllBy*` result. For a component selector, count the elements the component renders.";
|
|
@@ -39,14 +39,18 @@ export function eventKind(api: string, [name, mock]: J[]): EventKind | undefined
|
|
|
39
39
|
return ["mouseEnter", "mouseLeave", "mouseOver", "mouseOut"].includes(event) ? "hover" : "event";
|
|
40
40
|
}
|
|
41
41
|
|
|
42
|
+
/** What a selector string matches by. */
|
|
43
|
+
export function stringSelectorKind(value: string): SelectorKind {
|
|
44
|
+
// Enzyme reads a selector starting with a capital as a component's display name
|
|
45
|
+
return /^[A-Z]/.test(value) ? "component" : domSelector(value) ? "dom" : "enzyme";
|
|
46
|
+
}
|
|
47
|
+
|
|
42
48
|
export function selectorKind(api: string, selector: J | undefined): SelectorKind | undefined {
|
|
43
49
|
if (api === "findWhere" || api === "filterWhere") return "predicate";
|
|
44
50
|
if (api !== "find" || !selector) return undefined;
|
|
45
51
|
if (selector.kind === J.Kind.Literal) {
|
|
46
52
|
const value = (selector as J.Literal).value;
|
|
47
|
-
|
|
48
|
-
// Enzyme reads a selector starting with a capital as a component's display name
|
|
49
|
-
return /^[A-Z]/.test(value) ? "component" : domSelector(value) ? "dom" : "enzyme";
|
|
53
|
+
return typeof value === "string" ? stringSelectorKind(value) : undefined;
|
|
50
54
|
}
|
|
51
55
|
if (isObjectLiteral(selector)) return "props";
|
|
52
56
|
const name = isIdentifier(selector) ? selector.simpleName :
|
|
@@ -54,6 +58,68 @@ export function selectorKind(api: string, selector: J | undefined): SelectorKind
|
|
|
54
58
|
return name && /^[A-Z]/.test(name) && TypedTree.getType(selector) !== Type.Primitive.String ? "component" : undefined;
|
|
55
59
|
}
|
|
56
60
|
|
|
61
|
+
const IMPORT_REVIEW = "Review this import and its consumers; unresolved or indirect calls require manual inspection. Keep it while Enzyme consumers remain.";
|
|
62
|
+
|
|
63
|
+
function moduleOf(imp: JS.Import): string | undefined {
|
|
64
|
+
const module = imp.moduleSpecifier?.element;
|
|
65
|
+
return module?.kind === J.Kind.Literal ? (module as J.Literal).value as string : undefined;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** The local names an import binds: its default, named and type-only specifiers, and a namespace. */
|
|
69
|
+
export function importedLocals(imp: JS.Import): string[] {
|
|
70
|
+
const clause = imp.importClause;
|
|
71
|
+
if (!clause) return [];
|
|
72
|
+
const names = clause.name ? [clause.name.element.simpleName] : [];
|
|
73
|
+
const bindings = clause.namedBindings;
|
|
74
|
+
if (bindings?.kind === JS.Kind.Alias && isIdentifier((bindings as JS.Alias).alias)) names.push(((bindings as JS.Alias).alias as J.Identifier).simpleName);
|
|
75
|
+
if (bindings?.kind === JS.Kind.NamedImports) {
|
|
76
|
+
for (const {element: imported} of (bindings as JS.NamedImports).elements.elements) {
|
|
77
|
+
if (imported.kind !== JS.Kind.ImportSpecifier) continue;
|
|
78
|
+
const named = (imported as JS.ImportSpecifier).specifier;
|
|
79
|
+
if (isIdentifier(named)) names.push(named.simpleName);
|
|
80
|
+
else if (named.kind === JS.Kind.Alias && isIdentifier((named as JS.Alias).alias)) names.push(((named as JS.Alias).alias as J.Identifier).simpleName);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
return names;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** How often the source refers to each of `names` outside its imports, leaving out member names such as `wrapper.mount()`. */
|
|
87
|
+
async function referencesTo(cu: JS.CompilationUnit, names: ReadonlySet<string>, ctx: ExecutionContext): Promise<Map<string, number>> {
|
|
88
|
+
const counts = new Map<string, number>();
|
|
89
|
+
if (names.size === 0) return counts;
|
|
90
|
+
await new class extends JavaScriptVisitor<ExecutionContext> {
|
|
91
|
+
override async visitImportDeclaration(imp: JS.Import): Promise<J | undefined> {
|
|
92
|
+
return imp;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
override async visitIdentifier(identifier: J.Identifier, p: ExecutionContext): Promise<J | undefined> {
|
|
96
|
+
if (names.has(identifier.simpleName)) {
|
|
97
|
+
const parent = this.cursor.parentTree()?.value as J | undefined;
|
|
98
|
+
const member = parent?.kind === J.Kind.FieldAccess && (parent as J.FieldAccess).name.element === identifier ||
|
|
99
|
+
parent?.kind === J.Kind.MethodInvocation && (parent as J.MethodInvocation).name === identifier && (parent as J.MethodInvocation).select !== undefined;
|
|
100
|
+
if (!member) counts.set(identifier.simpleName, (counts.get(identifier.simpleName) ?? 0) + 1);
|
|
101
|
+
}
|
|
102
|
+
return super.visitIdentifier(identifier, p);
|
|
103
|
+
}
|
|
104
|
+
}().visit(cu, ctx);
|
|
105
|
+
return counts;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** What to do with an Enzyme import: which of its names the source still uses, and how often, or that it uses none. */
|
|
109
|
+
export function importAction(locals: readonly string[], references: ReadonlyMap<string, number>): string {
|
|
110
|
+
if (locals.length === 0) return IMPORT_REVIEW;
|
|
111
|
+
const quoted = (names: string[]) => names.map(name => `\`${name}\``).join(", ");
|
|
112
|
+
const used = locals.filter(name => (references.get(name) ?? 0) > 0);
|
|
113
|
+
const unused = locals.filter(name => !used.includes(name));
|
|
114
|
+
if (used.length === 0) return `This file uses none of the names this import binds, ${quoted(unused)}: remove the import.`;
|
|
115
|
+
const kept = used.map(name => {
|
|
116
|
+
const count = references.get(name)!;
|
|
117
|
+
return `\`${name}\` (${count} ${count === 1 ? "use" : "uses"})`;
|
|
118
|
+
}).join(", ");
|
|
119
|
+
const rest = unused.length === 0 ? "" : ` This file doesn't use ${quoted(unused)}, so remove ${unused.length === 1 ? "it" : "them"} from the import.`;
|
|
120
|
+
return `Kept for ${kept} in this file. Remove a name from this import once no use of it remains.${rest}`;
|
|
121
|
+
}
|
|
122
|
+
|
|
57
123
|
/**
|
|
58
124
|
* Inventories imports/setup even when types are unavailable; calls and wrapper fields are
|
|
59
125
|
* attributed to Enzyme by declaring type, not by names such as `find` or `state`.
|
|
@@ -81,9 +147,12 @@ export class FindEnzymeUsage extends Recipe {
|
|
|
81
147
|
);
|
|
82
148
|
return check(and(not(isVendoredOrBundled()), relevant), new class extends JavaScriptVisitor<ExecutionContext> {
|
|
83
149
|
private sourcePath = "";
|
|
150
|
+
private references = new Map<string, number>();
|
|
84
151
|
|
|
85
152
|
override async visitJsCompilationUnit(cu: JS.CompilationUnit, ctx: ExecutionContext): Promise<J | undefined> {
|
|
86
153
|
this.sourcePath = cu.sourcePath;
|
|
154
|
+
this.references = await referencesTo(cu, new Set(cu.statements.flatMap(({element}) => element.kind === JS.Kind.Import &&
|
|
155
|
+
enzymeModule(moduleOf(element as JS.Import)) ? importedLocals(element as JS.Import) : [])), ctx);
|
|
87
156
|
return super.visitJsCompilationUnit(cu, ctx);
|
|
88
157
|
}
|
|
89
158
|
|
|
@@ -92,8 +161,7 @@ export class FindEnzymeUsage extends Recipe {
|
|
|
92
161
|
const moduleName = module?.kind === J.Kind.Literal ? (module as J.Literal).value : undefined;
|
|
93
162
|
const result = await super.visitImportDeclaration(imp, ctx) as JS.Import;
|
|
94
163
|
if (!enzymeModule(moduleName)) return result;
|
|
95
|
-
return this.report(result, moduleName, "MODULE_REFERENCE",
|
|
96
|
-
"Review this import and its consumers; unresolved or indirect calls require manual inspection. Keep it while Enzyme consumers remain.", ctx);
|
|
164
|
+
return this.report(result, moduleName, "MODULE_REFERENCE", importAction(importedLocals(imp), this.references), ctx);
|
|
97
165
|
}
|
|
98
166
|
|
|
99
167
|
override async visitExportDeclaration(exp: JS.ExportDeclaration, ctx: ExecutionContext): Promise<J | undefined> {
|
|
@@ -121,7 +189,12 @@ export class FindEnzymeUsage extends Recipe {
|
|
|
121
189
|
}
|
|
122
190
|
const api = enzymeMethod(method);
|
|
123
191
|
if (!api) return result;
|
|
124
|
-
|
|
192
|
+
// The converter, run before this, read the string a selector other than a literal holds, where it could
|
|
193
|
+
const read = api === "find" ? SELECTOR_VALUES.get(this.sourcePath)?.get(method.id) : undefined;
|
|
194
|
+
const selector = read && "value" in read ? stringSelectorKind(read.value) : selectorKind(api, args[0]);
|
|
195
|
+
const migration = migrationReason(api, selector, eventKind(api, args));
|
|
196
|
+
const {reason} = migration;
|
|
197
|
+
const suggestedAction = read && "unread" in read ? unreadSelector(read.unread) : migration.suggestedAction;
|
|
125
198
|
// The converter, run before this, says what kept a render it left on Enzyme
|
|
126
199
|
const blocker = reason === "RENDER_REVIEW" || reason === "SHALLOW_RENDERING" ? (RENDER_BLOCKERS.get(this.sourcePath)?.get(method.id) ?? RENDER_BLOCKERS.get(this.sourcePath)?.get(FILE_BLOCKER)) : undefined;
|
|
127
200
|
if (blocker) return this.report(result, api, reason, blocker, ctx);
|
|
@@ -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,8 +1,10 @@
|
|
|
1
1
|
import {Cursor, TreePrinters} from "@openrewrite/rewrite";
|
|
2
2
|
import {JS} from "@openrewrite/rewrite/javascript";
|
|
3
|
-
import {J} from "@openrewrite/rewrite/java";
|
|
3
|
+
import {isIdentifier, J} from "@openrewrite/rewrite/java";
|
|
4
4
|
import {eventKind, selectorKind} from "../search/find-enzyme-usage";
|
|
5
5
|
import {migrationReason} from "./enzyme-usage";
|
|
6
|
+
import type {BlockingReference} from "./enzyme-wrapper-scope";
|
|
7
|
+
import type {ShallowMiss} from "./enzyme-host-components";
|
|
6
8
|
|
|
7
9
|
/** Why the converter kept a render it analyzed on Enzyme, other than a use of its wrapper. */
|
|
8
10
|
export type RenderGate = "setProps" | "rootStyles" | "shallow" | "portal";
|
|
@@ -24,6 +26,10 @@ const PASSED = "Blocked by a wrapper passed on: the recipe converts a wrapper on
|
|
|
24
26
|
"Inline what the helper reads here, or change the helper to take the element RTL queried, such as `container.querySelector(selector)`.";
|
|
25
27
|
const STORED = "Blocked by a stored find: Enzyme's found wrapper keeps the render as it was, while an RTL element is live. " +
|
|
26
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}`;
|
|
27
33
|
const UNMOUNTED = "Blocked by a read after unmount: RTL's container is empty once the render unmounts. " +
|
|
28
34
|
"Assert before calling `unmount()`, or render again for what comes after.";
|
|
29
35
|
const FIND_HERE = "Blocked by `find`: Enzyme and the DOM can match different elements for this selector where it stands, " +
|
|
@@ -43,6 +49,28 @@ const GATES: Readonly<Record<RenderGate, string>> = {
|
|
|
43
49
|
"Render without the `container` option, so the render is attached to the document, before reading text or markup."
|
|
44
50
|
};
|
|
45
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
|
+
|
|
46
74
|
/** Why the converter leaves every render of a source on Enzyme. */
|
|
47
75
|
export type FileGate = "react" | "rtl" | "rtlMissing" | "commonjs";
|
|
48
76
|
|
|
@@ -51,8 +79,8 @@ const FILES: Readonly<Record<FileGate, string>> = {
|
|
|
51
79
|
"On React 19, migrate the file by hand to RTL 16's `render`, `screen` and `fireEvent`, following the file's other rows.",
|
|
52
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. " +
|
|
53
81
|
"Move `@testing-library/react` to that version, then run the recipe again.",
|
|
54
|
-
rtlMissing: "Blocked for this file: the run added no React Testing Library
|
|
55
|
-
"
|
|
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.",
|
|
56
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."
|
|
57
85
|
};
|
|
58
86
|
|
|
@@ -60,14 +88,91 @@ export function blockedByFile(gate: FileGate): string {
|
|
|
60
88
|
return FILES[gate];
|
|
61
89
|
}
|
|
62
90
|
|
|
63
|
-
/**
|
|
64
|
-
export
|
|
65
|
-
|
|
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!)}\``;
|
|
66
157
|
const {top, calls} = chainOf(first.cursor);
|
|
67
158
|
const action = first.unmounted ? UNMOUNTED : actionFor(top, calls, first.cursor);
|
|
68
|
-
const
|
|
69
|
-
const
|
|
70
|
-
|
|
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;
|
|
71
176
|
}
|
|
72
177
|
|
|
73
178
|
export function blockedByGate(gate: RenderGate): string {
|
|
@@ -111,3 +216,63 @@ function actionFor(top: J, calls: J.MethodInvocation[], reference: Cursor): stri
|
|
|
111
216
|
if (event === "event") return SIMULATE_HERE;
|
|
112
217
|
return `Blocked by \`${api}\`: ${migrationReason(api, selector, event).suggestedAction}`;
|
|
113
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
|
+
}
|