@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.
- package/dist/i18n/translate-hard-coded-strings.d.ts +67 -0
- package/dist/i18n/translate-hard-coded-strings.d.ts.map +1 -0
- package/dist/i18n/translate-hard-coded-strings.js +439 -0
- package/dist/i18n/translate-hard-coded-strings.js.map +1 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +37 -1
- 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 +8 -0
- package/dist/search/find-enzyme-usage.d.ts.map +1 -1
- package/dist/search/find-enzyme-usage.js +119 -8
- package/dist/search/find-enzyme-usage.js.map +1 -1
- package/dist/search/find-hard-coded-strings.d.ts +110 -0
- package/dist/search/find-hard-coded-strings.d.ts.map +1 -0
- package/dist/search/find-hard-coded-strings.js +987 -0
- package/dist/search/find-hard-coded-strings.js.map +1 -0
- package/dist/search/find-missing-use-client-directive.d.ts +2 -0
- package/dist/search/find-missing-use-client-directive.d.ts.map +1 -1
- package/dist/search/find-missing-use-client-directive.js +1 -0
- package/dist/search/find-missing-use-client-directive.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-portals.d.ts +3 -5
- package/dist/testing/enzyme-portals.d.ts.map +1 -1
- package/dist/testing/enzyme-portals.js +8 -39
- package/dist/testing/enzyme-portals.js.map +1 -1
- package/dist/testing/enzyme-render-blockers.d.ts +19 -0
- package/dist/testing/enzyme-render-blockers.d.ts.map +1 -0
- package/dist/testing/enzyme-render-blockers.js +275 -0
- package/dist/testing/enzyme-render-blockers.js.map +1 -0
- package/dist/testing/enzyme-to-react-testing-library.d.ts +17 -3
- package/dist/testing/enzyme-to-react-testing-library.d.ts.map +1 -1
- package/dist/testing/enzyme-to-react-testing-library.js +237 -27
- package/dist/testing/enzyme-to-react-testing-library.js.map +1 -1
- package/dist/testing/enzyme-usage.d.ts +9 -0
- package/dist/testing/enzyme-usage.d.ts.map +1 -1
- package/dist/testing/enzyme-usage.js +36 -3
- package/dist/testing/enzyme-usage.js.map +1 -1
- package/dist/testing/enzyme-wrapper-scope.d.ts +8 -1
- package/dist/testing/enzyme-wrapper-scope.d.ts.map +1 -1
- package/dist/testing/enzyme-wrapper-scope.js +26 -5
- package/dist/testing/enzyme-wrapper-scope.js.map +1 -1
- package/dist/util/json-and-javascript.d.ts +4 -0
- package/dist/util/json-and-javascript.d.ts.map +1 -0
- package/dist/util/json-and-javascript.js +37 -0
- package/dist/util/json-and-javascript.js.map +1 -0
- package/dist/util/module-imports.d.ts +36 -0
- package/dist/util/module-imports.d.ts.map +1 -1
- package/dist/util/module-imports.js +216 -0
- package/dist/util/module-imports.js.map +1 -1
- package/dist/util/test-source.d.ts +2 -0
- package/dist/util/test-source.d.ts.map +1 -0
- package/dist/util/test-source.js +5 -0
- package/dist/util/test-source.js.map +1 -0
- package/dist/zustand/entry-store.d.ts +9 -0
- package/dist/zustand/entry-store.d.ts.map +1 -0
- package/dist/zustand/entry-store.js +136 -0
- package/dist/zustand/entry-store.js.map +1 -0
- package/dist/zustand/redux-stores.d.ts +7 -4
- package/dist/zustand/redux-stores.d.ts.map +1 -1
- package/dist/zustand/redux-stores.js +128 -11
- package/dist/zustand/redux-stores.js.map +1 -1
- package/dist/zustand/redux-to-zustand.d.ts +11 -2
- package/dist/zustand/redux-to-zustand.d.ts.map +1 -1
- package/dist/zustand/redux-to-zustand.js +147 -46
- package/dist/zustand/redux-to-zustand.js.map +1 -1
- package/dist/zustand/zustand-plan.d.ts +14 -5
- package/dist/zustand/zustand-plan.d.ts.map +1 -1
- package/dist/zustand/zustand-plan.js +226 -52
- package/dist/zustand/zustand-plan.js.map +1 -1
- package/package.json +1 -1
- package/src/i18n/translate-hard-coded-strings.ts +442 -0
- package/src/index.ts +17 -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 +109 -12
- package/src/search/find-hard-coded-strings.ts +1006 -0
- package/src/search/find-missing-use-client-directive.ts +1 -1
- package/src/testing/enzyme-host-components.ts +110 -0
- package/src/testing/enzyme-portals.ts +4 -44
- package/src/testing/enzyme-render-blockers.ts +278 -0
- package/src/testing/enzyme-to-react-testing-library.ts +240 -34
- package/src/testing/enzyme-usage.ts +48 -2
- package/src/testing/enzyme-wrapper-scope.ts +35 -3
- package/src/util/json-and-javascript.ts +26 -0
- package/src/util/module-imports.ts +223 -0
- package/src/util/test-source.ts +2 -0
- package/src/zustand/entry-store.ts +131 -0
- package/src/zustand/redux-stores.ts +131 -12
- package/src/zustand/redux-to-zustand.ts +179 -52
- package/src/zustand/zustand-plan.ts +256 -49
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {Cursor, DataTable, emptyMarkers, ExecutionContext, Markup, MarkersKind, Option, or, randomId, ScanningRecipe, SourceFile, Tree, TreePrinters, TreeVisitor} from "@openrewrite/rewrite";
|
|
2
2
|
import {
|
|
3
|
-
AddDependencyOptions, autoFormat, ChangeImport, findNodeResolutionResult, isVendoredOrBundled, JavaScriptVisitor, JS, JSX, maybeAddImport, maybeRemoveImport, raw, template
|
|
3
|
+
AddDependencyOptions, autoFormat, ChangeImport, findNodeResolutionResult, isVendoredOrBundled, JavaScriptVisitor, JS, JSX, maybeAddImport, maybeRemoveImport, namesReferencedWithin, raw, template
|
|
4
4
|
} from "@openrewrite/rewrite/javascript";
|
|
5
5
|
import {emptySpace, isIdentifier, J, Statement} from "@openrewrite/rewrite/java";
|
|
6
6
|
import {Json, JsonVisitor} from "@openrewrite/rewrite/json";
|
|
@@ -8,9 +8,10 @@ import {create} from "mutative";
|
|
|
8
8
|
import {minVersion, satisfies, valid, validRange} from "semver";
|
|
9
9
|
import {check, not} from "@openrewrite/rewrite";
|
|
10
10
|
import {JavaDependencyRecipe, treesOfType} from "../util/java-recipe-proxy";
|
|
11
|
-
import {importBindings,
|
|
11
|
+
import {addPathsConfig, importBindings, isAliasSpecifier, PathsConfigs, Resolve, resolveModule} from "../util/module-imports";
|
|
12
12
|
import {rewriteVersion, supportsResolvingGate} from "../testing/enzyme-to-react-testing-library";
|
|
13
|
-
import {
|
|
13
|
+
import {ENTRY_STORE_MODULE, EntrySplit, splitEntryStore} from "./entry-store";
|
|
14
|
+
import {caseReducers, Finding, importedAs, legacyEnhancer, localSlices, objectProperties, preloadedValue, withoutEffects, REDUX_STORES_TABLE, ReduxStoreRow, REDUX, RTK, SliceModule, storeFunctions, SUGGESTED_ACTIONS, TEST_SOURCE} from "./redux-stores";
|
|
14
15
|
import {
|
|
15
16
|
actionsExport, argumentsOf, dispatchedAction, getStateRead, isDispatcherDeclaration, isReactDependencies, isReducerExport, parentTree, Plan, planPackages, PlannedSlice, providerChild, providerChildren,
|
|
16
17
|
REACT_REDUX, readSelector, relativeSpecifier, selectorRead, sliceSource, SliceSource, SourceFacts, sourceFacts, StoreFacts, storeFacts
|
|
@@ -52,6 +53,9 @@ interface PackageFacts {
|
|
|
52
53
|
reactNative?: string;
|
|
53
54
|
zustand?: string;
|
|
54
55
|
immer?: string;
|
|
56
|
+
redux?: string;
|
|
57
|
+
toolkit?: string;
|
|
58
|
+
reactRedux?: string;
|
|
55
59
|
}
|
|
56
60
|
|
|
57
61
|
interface Scanned {
|
|
@@ -59,8 +63,23 @@ interface Scanned {
|
|
|
59
63
|
modules: Map<string, SliceModule>;
|
|
60
64
|
sliceSources: Map<string, SliceSource>;
|
|
61
65
|
packages: Map<string, PackageFacts>;
|
|
66
|
+
/** The `paths` of each directory's `tsconfig.json`, or else its `jsconfig.json`, by the directory. */
|
|
67
|
+
configs: PathsConfigs;
|
|
62
68
|
}
|
|
63
69
|
|
|
70
|
+
/** Resolves a specifier among the scanned sources, an alias through the nearest config's `paths`. */
|
|
71
|
+
function resolverOf(scanned: Scanned): Resolve {
|
|
72
|
+
return (from, specifier) => resolveModule(from, specifier, scanned.sources, scanned.configs);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Whether a source's import of a specifier is one the conversion follows: react-redux's, or one that may name a source. */
|
|
76
|
+
function followsImport(module: string): boolean {
|
|
77
|
+
return module === REACT_REDUX || module.startsWith(".") || isAliasSpecifier(module);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** A source split so that the store it creates and doesn't export moves to `modulePath`. */
|
|
81
|
+
type Split = EntrySplit & {modulePath: string};
|
|
82
|
+
|
|
64
83
|
/** Adds a dependency to the package whose Redux store converts, with the gates of Java's `AddDependency`. */
|
|
65
84
|
abstract class ZustandDependency extends JavaDependencyRecipe {
|
|
66
85
|
/** The package roots whose `package.json` declares the dependency once this run's edit lands. Mutated in place. */
|
|
@@ -258,7 +277,8 @@ const ADDS_DEPENDENCIES = (() => {
|
|
|
258
277
|
* slice's, a thunk that reaches the rest of the store or a dispatch whose result is used, moves whole instead:
|
|
259
278
|
*
|
|
260
279
|
* - the store's reducer, combined as `configureStore` combines it, runs on one zustand store, `useAppStore`, whose
|
|
261
|
-
* `dispatch` runs a thunk as Redux Toolkit's default middleware does and any other action through the reducer
|
|
280
|
+
* `dispatch` runs a thunk as Redux Toolkit's default middleware does, and any other action through the reducer
|
|
281
|
+
* once it is a plain object with a `type`, a string on Redux 5, and throws otherwise, as Redux does;
|
|
262
282
|
* - the store's variable keeps the store's `getState` and `dispatch`, so their uses stay as they are, in the store's
|
|
263
283
|
* source too, as do the slices, their action creators and thunks;
|
|
264
284
|
* - where the store's source or another calls `store.subscribe(listener)`, the store keeps a `subscribe` too, whose
|
|
@@ -274,8 +294,8 @@ const ADDS_DEPENDENCIES = (() => {
|
|
|
274
294
|
* each read, `useAppStoreSelector(selector)`, a hook the store's source declares that keeps it.
|
|
275
295
|
*
|
|
276
296
|
* A legacy `createStore(reducer)` or `createStore(reducer, preloadedState)`, of a preloaded state written as a value,
|
|
277
|
-
* moves whole the same way. It has no middleware, so its `dispatch` runs
|
|
278
|
-
*
|
|
297
|
+
* moves whole the same way. It has no middleware, so its `dispatch` runs no thunk, and its state starts from the
|
|
298
|
+
* preloaded state. One
|
|
279
299
|
* whose enhancer is `applyMiddleware(thunk)`, perhaps inside `compose` or Redux DevTools, also runs a function it is
|
|
280
300
|
* dispatched with `dispatch` and `getState`, as redux-thunk does; DevTools is dropped.
|
|
281
301
|
*
|
|
@@ -293,7 +313,7 @@ const ADDS_DEPENDENCIES = (() => {
|
|
|
293
313
|
export class ReduxToZustand extends ScanningRecipe<Scanned> {
|
|
294
314
|
readonly name = "org.openrewrite.react.migrate.redux-to-zustand";
|
|
295
315
|
readonly displayName = "Migrate Redux Toolkit slices to zustand";
|
|
296
|
-
readonly description = "Moves a repository's one Redux Toolkit store to zustand when it is a `configureStore` of `createSlice` reducers with no other option, its sources are JavaScript, and every use of it converts: each slice becomes a zustand store whose action creators keep their names and run the slice's reducers through immer's `produce`, `useSelector` reads of one slice become the slice's zustand hook, `dispatch` and `store.dispatch` of the slices' action creators become calls of them, `store.getState()` reads become the slice store's `getState()`, and the react-redux `Provider`, replaced with its children, and the store's source are removed. A slice's own `createAsyncThunk`s, whose stages its `extraReducers` handles, keep running on Redux Toolkit and send their actions to the slice's zustand store. A store of its `reducer` alone whose slices can't move one by one, such as one with a reducer that is no slice's, thunks that reach the rest of the store or dispatches whose result is used, moves whole: its reducer runs on one zustand store whose `dispatch` runs thunks as Redux Toolkit's default middleware does, its selectors run on that store, through a hook of the store's source that keeps each selection per state where zustand 5 would run the selector on each read, and the store keeps its `getState` and `dispatch`, and its `subscribe`, whose listeners its `dispatch` calls after every action as Redux does, where a source subscribes to it. A legacy `createStore` of a reducer, and perhaps a preloaded state, moves whole too, its `dispatch` taking plain actions only, as Redux's does without middleware, or thunks as well where its enhancer is `applyMiddleware(thunk)`, perhaps inside `compose` or Redux DevTools, which is dropped. Components connected with `connect`, with no `mergeProps` and no option but `forwardRef`, move with a store that moves whole: its source declares a `connect` for the zustand store that passes the same props, copies the same statics and skips the same re-renders as react-redux's, and the store batches its updates as react-redux does. Adds `zustand`, and `immer` where slices move one by one, where they are missing. Stores with any other use, such as `connect` with `mergeProps`, other middleware or enhancers, other uses of the store object such as `persistStore(store)`, selectors with their own equality function or several stores, stay in Redux and are recorded for review.";
|
|
316
|
+
readonly description = "Moves a repository's one Redux Toolkit store to zustand when it is a `configureStore` of `createSlice` reducers with no other option, its sources are JavaScript, and every use of it converts: each slice becomes a zustand store whose action creators keep their names and run the slice's reducers through immer's `produce`, `useSelector` reads of one slice become the slice's zustand hook, `dispatch` and `store.dispatch` of the slices' action creators become calls of them, `store.getState()` reads become the slice store's `getState()`, and the react-redux `Provider`, replaced with its children, and the store's source are removed. A slice's own `createAsyncThunk`s, whose stages its `extraReducers` handles, keep running on Redux Toolkit and send their actions to the slice's zustand store. A store of its `reducer` alone whose slices can't move one by one, such as one with a reducer that is no slice's, thunks that reach the rest of the store or dispatches whose result is used, moves whole: its reducer runs on one zustand store whose `dispatch` runs thunks as Redux Toolkit's default middleware does, its selectors run on that store, through a hook of the store's source that keeps each selection per state where zustand 5 would run the selector on each read, and the store keeps its `getState` and `dispatch`, and its `subscribe`, whose listeners its `dispatch` calls after every action as Redux does, where a source subscribes to it. A legacy `createStore` of a reducer, and perhaps a preloaded state, moves whole too, its `dispatch` taking plain actions only, as Redux's does without middleware, or thunks as well where its enhancer is `applyMiddleware(thunk)`, perhaps inside `compose` or Redux DevTools, which is dropped. Components connected with `connect`, with no `mergeProps` and no option but `forwardRef`, move with a store that moves whole: its source declares a `connect` for the zustand store that passes the same props, copies the same statics and skips the same re-renders as react-redux's, and the store batches its updates as react-redux does. A store that moves whole but is created, and not exported, at the top level of an application's entry source, such as the one that renders the `Provider`, moves to an `appStore` module beside that source, with the imports and top-level `const`s and `let`s only it uses, and the source imports back what it still uses. A store's source may export it in its declaration, as its default export or in an export list such as `export {store}`, and other sources may import it, and its slices, by relative paths or by aliases such as `@/store` that the `paths` of the nearest `tsconfig.json` or `jsconfig.json` declare. Adds `zustand`, and `immer` where slices move one by one, where they are missing. Stores with any other use, such as `connect` with `mergeProps`, other middleware or enhancers, other uses of the store object such as `persistStore(store)`, selectors with their own equality function or several stores, stay in Redux and are recorded for review.";
|
|
297
317
|
|
|
298
318
|
@Option({
|
|
299
319
|
displayName: "Move stores whole",
|
|
@@ -322,7 +342,7 @@ export class ReduxToZustand extends ScanningRecipe<Scanned> {
|
|
|
322
342
|
|
|
323
343
|
initialValue(): Scanned {
|
|
324
344
|
this.storeSources.length = 0;
|
|
325
|
-
return {sources: new Map(), modules: new Map(), sliceSources: new Map(), packages: new Map()};
|
|
345
|
+
return {sources: new Map(), modules: new Map(), sliceSources: new Map(), packages: new Map(), configs: new Map()};
|
|
326
346
|
}
|
|
327
347
|
|
|
328
348
|
async scanner(scanned: Scanned): Promise<TreeVisitor<any, ExecutionContext>> {
|
|
@@ -351,8 +371,9 @@ export class ReduxToZustand extends ScanningRecipe<Scanned> {
|
|
|
351
371
|
if (/(^|\/)package\.json$/.test(doc.sourcePath)) {
|
|
352
372
|
const declared = findNodeResolutionResult(doc) ? undefined : await declaredDependencies(doc);
|
|
353
373
|
const get = (name: string) => declared ? declared[name] : version(doc, name);
|
|
354
|
-
scanned.packages.set(packageRoot(doc.sourcePath), {react: get("react"), reactDom: get("react-dom"), reactNative: get("react-native"), zustand: get(ZUSTAND), immer: get(IMMER)});
|
|
374
|
+
scanned.packages.set(packageRoot(doc.sourcePath), {react: get("react"), reactDom: get("react-dom"), reactNative: get("react-native"), zustand: get(ZUSTAND), immer: get(IMMER), redux: get("redux"), toolkit: get(RTK), reactRedux: get("react-redux")});
|
|
355
375
|
}
|
|
376
|
+
await addPathsConfig(scanned.configs, doc);
|
|
356
377
|
return doc;
|
|
357
378
|
}
|
|
358
379
|
}();
|
|
@@ -370,6 +391,12 @@ export class ReduxToZustand extends ScanningRecipe<Scanned> {
|
|
|
370
391
|
return check(or(treesOfType("org.openrewrite.json.tree.Json"), treesOfType("org.openrewrite.javascript.tree.JS")), scan);
|
|
371
392
|
}
|
|
372
393
|
|
|
394
|
+
/** The rows reported for each scan's stores. */
|
|
395
|
+
private reported = new WeakMap<Scanned, Set<string>>();
|
|
396
|
+
|
|
397
|
+
/** The sources split by `split`, by path, kept out of the accumulator, which keeps no trees. */
|
|
398
|
+
private splits = new WeakMap<Scanned, Map<string, Split>>();
|
|
399
|
+
|
|
373
400
|
/** The plan, once every source is scanned. `forecast` assumes that zustand and immer land wherever they're missing. */
|
|
374
401
|
private plans = new WeakMap<Scanned, Promise<Plan[]>>();
|
|
375
402
|
|
|
@@ -380,9 +407,11 @@ export class ReduxToZustand extends ScanningRecipe<Scanned> {
|
|
|
380
407
|
if (cached) return cached;
|
|
381
408
|
}
|
|
382
409
|
const result = (async () => {
|
|
410
|
+
const splits = await this.split(scanned);
|
|
383
411
|
for (const cu of this.storeSources) {
|
|
384
|
-
const
|
|
385
|
-
|
|
412
|
+
const source = splits.get(cu.sourcePath)?.module ?? cu;
|
|
413
|
+
const facts = scanned.sources.get(source.sourcePath);
|
|
414
|
+
if (facts) facts.stores = await storeFacts(source, scanned.modules, resolverOf(scanned));
|
|
386
415
|
}
|
|
387
416
|
return planPackages(scanned.sources, scanned.sliceSources, path => packageOf(scanned.packages, path),
|
|
388
417
|
(storePath, immer) => this.dependencies(scanned, storePath, forecast, immer), this.wholeStores !== false, storePath => {
|
|
@@ -392,12 +421,56 @@ export class ReduxToZustand extends ScanningRecipe<Scanned> {
|
|
|
392
421
|
// zustand 5's hook, which the package declares or gets on React 18, runs the selector on each read
|
|
393
422
|
const facts = scanned.packages.get(packageOf(scanned.packages, storePath) ?? "");
|
|
394
423
|
return facts?.zustand !== undefined ? (major(facts.zustand) ?? 0) >= 5 : (major(facts?.react) ?? 0) >= 18;
|
|
395
|
-
});
|
|
424
|
+
}, resolverOf(scanned));
|
|
396
425
|
})();
|
|
397
426
|
if (!forecast) this.plans.set(scanned, result);
|
|
398
427
|
return result;
|
|
399
428
|
}
|
|
400
429
|
|
|
430
|
+
/**
|
|
431
|
+
* Splits each source that creates one store it doesn't export, at the top level of an application source, so that
|
|
432
|
+
* the store moves to a module of its own beside it, which its consumers can import, and the source imports it back.
|
|
433
|
+
* The split replaces the source's facts and adds the module's; the sources change only once the store converts.
|
|
434
|
+
*/
|
|
435
|
+
private async split(scanned: Scanned): Promise<Map<string, Split>> {
|
|
436
|
+
const known = this.splits.get(scanned);
|
|
437
|
+
if (known) return known;
|
|
438
|
+
const splits = new Map<string, Split>();
|
|
439
|
+
this.splits.set(scanned, splits);
|
|
440
|
+
const paths = [...scanned.sources.keys()];
|
|
441
|
+
const created = new Map<JS.CompilationUnit, Awaited<ReturnType<typeof storeFacts>>>();
|
|
442
|
+
for (const cu of this.storeSources) created.set(cu, await storeFacts(cu, scanned.modules, resolverOf(scanned)));
|
|
443
|
+
// A package with several stores keeps them in Redux, so none of its sources needs to split
|
|
444
|
+
const storesIn = (root: string | undefined) => [...created].filter(([cu]) => packageOf(scanned.packages, cu.sourcePath) === root).reduce((n, [, stores]) => n + stores.length, 0);
|
|
445
|
+
for (const [cu, stores] of created) {
|
|
446
|
+
if (/\.(?:ts|tsx|mts|cts)$/.test(cu.sourcePath) || TEST_SOURCE.test(cu.sourcePath)) continue;
|
|
447
|
+
if (stores.length !== 1 || stores[0].exportedAs || storesIn(packageOf(scanned.packages, cu.sourcePath)) !== 1) continue;
|
|
448
|
+
const directory = cu.sourcePath.includes("/") ? cu.sourcePath.slice(0, cu.sourcePath.lastIndexOf("/") + 1) : "";
|
|
449
|
+
const base = directory + ENTRY_STORE_MODULE;
|
|
450
|
+
// A module of that name, or a directory, would take the imports of the other
|
|
451
|
+
if (paths.some(path => path.startsWith(base + ".") || path.startsWith(base + "/"))) continue;
|
|
452
|
+
const split = await splitEntryStore(cu, stores[0].store, base + ".js", new ExecutionContext());
|
|
453
|
+
if (!split) continue;
|
|
454
|
+
splits.set(cu.sourcePath, {...split, modulePath: base + ".js"});
|
|
455
|
+
paths.push(base + ".js");
|
|
456
|
+
for (const source of [split.entry, split.module]) {
|
|
457
|
+
const {reducers, slices} = localSlices(source);
|
|
458
|
+
scanned.modules.set(source.sourcePath, {reducers, slices});
|
|
459
|
+
scanned.sources.set(source.sourcePath, await sourceFacts(source));
|
|
460
|
+
const slice = sliceSource(source);
|
|
461
|
+
if (slice) scanned.sliceSources.set(source.sourcePath, slice);
|
|
462
|
+
else scanned.sliceSources.delete(source.sourcePath);
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
return splits;
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
override async generate(scanned: Scanned, ctx: ExecutionContext): Promise<SourceFile[]> {
|
|
469
|
+
const plans = await this.planned(scanned, true);
|
|
470
|
+
// Slices that move one by one take the store's source with them, so only a store that moves whole needs the module
|
|
471
|
+
return [...(await this.split(scanned)).values()].filter(split => plans.some(p => p.store?.path === split.modulePath && p.reducerStore)).map(split => split.module);
|
|
472
|
+
}
|
|
473
|
+
|
|
401
474
|
/** Why the package of the store can't take zustand and immer, if it can't. */
|
|
402
475
|
private dependencies(scanned: Scanned, storePath: string, forecast: boolean, needsImmer = true): Finding | undefined {
|
|
403
476
|
const root = packageOf(scanned.packages, storePath);
|
|
@@ -407,7 +480,8 @@ export class ReduxToZustand extends ScanningRecipe<Scanned> {
|
|
|
407
480
|
if (react === undefined || react < 16 || react === 16 && (minVersion(facts.react!)?.minor ?? 0) < 8) return {reason: "REACT_VERSION", detail: facts.react ?? "react not declared"};
|
|
408
481
|
// A package the steps weren't asked to change keeps its store for another reason, recorded already
|
|
409
482
|
const refusal = !forecast ? this.forecast.refused?.get(root) : undefined;
|
|
410
|
-
if (refusal) return {reason: "DEPENDENCY", detail: `zustand isn't added: ${refusal.message}
|
|
483
|
+
if (refusal) return {reason: "DEPENDENCY", detail: `zustand isn't added: ${refusal.message}`,
|
|
484
|
+
action: `The recipe adds \`zustand\` and \`immer\` only where it can write the lockfile the package manager would, which the detail says it can't here: add \`zustand\` ${(react >= 18 ? ZUSTAND_5 : ZUSTAND_4).version} and \`immer\` ${IMMER_10.version} to the package yourself, with its own package manager, and run the recipe again.`};
|
|
411
485
|
const landed = (step: ZustandDependency | undefined) => forecast || !this.asked?.has(root) && this.asked !== undefined ? !!this.steps : !!step?.landed.has(root);
|
|
412
486
|
const zustand = facts.zustand !== undefined ? (major(facts.zustand) ?? 0) >= (react >= 18 ? 4 : 4) && (react >= 18 || major(facts.zustand) === 4)
|
|
413
487
|
: landed(react >= 18 ? this.steps?.zustand : this.steps?.zustand4);
|
|
@@ -420,32 +494,41 @@ export class ReduxToZustand extends ScanningRecipe<Scanned> {
|
|
|
420
494
|
async editorWithData(scanned: Scanned): Promise<TreeVisitor<any, ExecutionContext>> {
|
|
421
495
|
const recipe = this;
|
|
422
496
|
const stores = this.stores;
|
|
423
|
-
|
|
497
|
+
// The editor that visits a generated source may be another, which reports none of the same rows again
|
|
498
|
+
let reported = this.reported.get(scanned);
|
|
499
|
+
if (!reported) this.reported.set(scanned, reported = new Set<string>());
|
|
424
500
|
return check(not(isVendoredOrBundled()), new class extends JavaScriptVisitor<ExecutionContext> {
|
|
425
501
|
override async visitJsCompilationUnit(cu: JS.CompilationUnit, ctx: ExecutionContext): Promise<J | undefined> {
|
|
426
502
|
const plans = await recipe.planned(scanned);
|
|
427
503
|
const facts = scanned.sources.get(cu.sourcePath);
|
|
428
|
-
|
|
504
|
+
const splits = await recipe.split(scanned);
|
|
505
|
+
const split = splits.get(cu.sourcePath);
|
|
506
|
+
const entryOf = (path: string) => [...splits].find(([, s]) => s.modulePath === path)?.[0] ?? path;
|
|
507
|
+
// A store that moves to a module of its own is reported for the source it was created in
|
|
508
|
+
for (const store of [...facts?.stores ?? [], ...split ? scanned.sources.get(split.modulePath)?.stores ?? [] : []]) {
|
|
429
509
|
const key = `${store.path}\0${store.store}\0${store.api}`;
|
|
430
510
|
if (reported.has(key)) continue;
|
|
431
511
|
reported.add(key);
|
|
432
512
|
const p = plans.find(candidate => candidate.store === store) ?? plans.find(candidate => candidate.blocked.has(store));
|
|
433
513
|
const findings = p?.store === store ? [] : p?.blocked.get(store) ?? store.findings;
|
|
434
514
|
const rows = findings.length === 0 ? [{reason: p?.reducerStore ? "REDUCER_STORE" : "SLICE_STORE", detail: ""}] : findings;
|
|
435
|
-
for (const {reason, detail} of rows) {
|
|
515
|
+
for (const {reason, detail, action} of rows as Finding[]) {
|
|
436
516
|
stores.insertRow(ctx, {
|
|
437
|
-
sourcePath: store.path, store: store.store, api: store.api,
|
|
517
|
+
sourcePath: entryOf(store.path), store: store.store, api: store.api,
|
|
438
518
|
status: p?.store === store ? "CONVERTED" : "REVIEW", reason, detail,
|
|
439
|
-
testSource: TEST_SOURCE.test(store.path), suggestedAction: SUGGESTED_ACTIONS[reason] ?? CONVERSION_ACTIONS[reason] ?? ""
|
|
519
|
+
testSource: TEST_SOURCE.test(entryOf(store.path)), suggestedAction: action ?? SUGGESTED_ACTIONS[reason] ?? CONVERSION_ACTIONS[reason] ?? ""
|
|
440
520
|
});
|
|
441
521
|
}
|
|
442
522
|
}
|
|
443
523
|
const p = plans.find(candidate => candidate.store && candidate.sources.has(cu.sourcePath));
|
|
444
|
-
|
|
445
|
-
|
|
524
|
+
// A module the store would have moved to goes again where the store stays
|
|
525
|
+
const generated = [...splits.values()].some(s => s.modulePath === cu.sourcePath);
|
|
526
|
+
if (!p?.store) return generated ? undefined : cu;
|
|
527
|
+
if (p.reducerStore) return cu.sourcePath === p.store.path ? convertReducerStore(cu, p, scanned.packages.get(packageOf(scanned.packages, cu.sourcePath) ?? ""), ctx) : convertReducerConsumer(split?.entry ?? cu, p, scanned, ctx);
|
|
446
528
|
if (cu.sourcePath === p.store.path) return undefined;
|
|
447
529
|
const slice = [...p.slices.values()].find(s => s.path === cu.sourcePath);
|
|
448
|
-
const
|
|
530
|
+
const source = split?.entry ?? cu;
|
|
531
|
+
const converted = slice ? await convertSlice(this, source, slice, scanned, ctx) : source;
|
|
449
532
|
return convertConsumer(converted, p, scanned, ctx);
|
|
450
533
|
}
|
|
451
534
|
}());
|
|
@@ -459,7 +542,7 @@ export class ReduxToZustand extends ScanningRecipe<Scanned> {
|
|
|
459
542
|
|
|
460
543
|
const CONVERSION_ACTIONS: Readonly<Record<string, string>> = {
|
|
461
544
|
MULTIPLE_STORES: "Convert by hand, or one store at a time: the uses of react-redux can't be told apart by store.",
|
|
462
|
-
STORE_NOT_MODULE_LEVEL: "Create the store once at the top level of its module; a zustand store is a module-level singleton.",
|
|
545
|
+
STORE_NOT_MODULE_LEVEL: "Create the store once at the top level of its module, and export it; a zustand store is a module-level singleton. A store its source creates at the top level moves to a module of its own where only imports and top-level `const`s and `let`s it uses move with it, nothing that stays uses them, and no `appStore` module is beside the source already.",
|
|
463
546
|
STORE_SOURCE: "Move what else the store's source declares, such as types or helpers, to another module.",
|
|
464
547
|
SLICE_SOURCE: "Declare each slice in a source of its own, held in a `const` of its own.",
|
|
465
548
|
SLICE_KEY: "Use a reducer key that is a JavaScript identifier, which names the zustand hook.",
|
|
@@ -675,10 +758,10 @@ function withPrefix<T extends J>(node: T, prefix: J.Space): T {
|
|
|
675
758
|
/** Rewrites the uses of react-redux, the store and its slices in a source. */
|
|
676
759
|
async function convertConsumer(cu: JS.CompilationUnit, p: Plan, scanned: Scanned, ctx: ExecutionContext): Promise<J | undefined> {
|
|
677
760
|
const bindings = importBindings(cu);
|
|
678
|
-
const followed = new Map(bindings.filter(b => b.module
|
|
761
|
+
const followed = new Map(bindings.filter(b => followsImport(b.module)).map(b => [b.local, b]));
|
|
679
762
|
const isStore = (name: string) => {
|
|
680
763
|
const binding = followed.get(name);
|
|
681
|
-
return !!binding && binding.module !== REACT_REDUX &&
|
|
764
|
+
return !!binding && binding.module !== REACT_REDUX && resolverOf(scanned)(cu.sourcePath, binding.module) === p.store!.path &&
|
|
682
765
|
binding.name === p.store!.exportedAs;
|
|
683
766
|
};
|
|
684
767
|
const reactRedux = (name: string, member: string) => followed.get(name)?.module === REACT_REDUX && followed.get(name)?.name === member;
|
|
@@ -837,8 +920,14 @@ function storeStatement(cu: JS.CompilationUnit, store: StoreFacts): {index: numb
|
|
|
837
920
|
// NOTE: the arguments are moved into new calls, so they drop the line breaks they had in the store's call
|
|
838
921
|
return {index, call, reducer: {...args[0], prefix: emptySpace}, preloaded: preloaded && {...preloaded, prefix: emptySpace}, consts: enhancer && !("unsupported" in enhancer) ? enhancer.consts : new Set()};
|
|
839
922
|
}
|
|
840
|
-
const
|
|
841
|
-
|
|
923
|
+
const options = objectProperties(argumentsOf(call)[0]);
|
|
924
|
+
const reducer = options?.get("reducer");
|
|
925
|
+
// The development-only options go with the call, and so may the `const`s only they read, unless making one has effects
|
|
926
|
+
const effectful = new Set(cu.statements.map(padded => padded.element).filter(s => s.kind === J.Kind.VariableDeclarations)
|
|
927
|
+
.flatMap(s => (s as J.VariableDeclarations).variables.map(v => v.element))
|
|
928
|
+
.filter(v => isIdentifier(v.name) && v.initializer && !withoutEffects(v.initializer.element)).map(v => (v.name as J.Identifier).simpleName));
|
|
929
|
+
const consts = new Set([...options ?? []].filter(([key]) => key !== "reducer").flatMap(([, value]) => [...namesReferencedWithin(value)]).filter(name => !effectful.has(name)));
|
|
930
|
+
return reducer ? {index, call, reducer, consts} : undefined;
|
|
842
931
|
}
|
|
843
932
|
return undefined;
|
|
844
933
|
}
|
|
@@ -870,12 +959,6 @@ async function withoutUnused(cu: JS.CompilationUnit, names: Set<string>): Promis
|
|
|
870
959
|
return cu;
|
|
871
960
|
}
|
|
872
961
|
|
|
873
|
-
/**
|
|
874
|
-
* Rewrites the store's source for a store that moves whole: its reducer runs on one zustand store, whose `dispatch`
|
|
875
|
-
* runs a thunk as Redux Toolkit's default middleware does and any other action through the reducer, and the store's
|
|
876
|
-
* variable keeps the store's `getState` and `dispatch`. A legacy `createStore` has no middleware, so its `dispatch`
|
|
877
|
-
* takes only plain-object actions with a `type`, as Redux's own does, and its state starts from its preloaded state.
|
|
878
|
-
*/
|
|
879
962
|
/**
|
|
880
963
|
* react-redux's `connect` for a store that moves to zustand whole: the props it passes, the statics it copies and the
|
|
881
964
|
* re-renders it skips are react-redux's, for any `mapStateToProps` and `mapDispatchToProps` and the `forwardRef` option.
|
|
@@ -898,7 +981,21 @@ export const SELECTOR = `export function SELECTOR_HOOK(selector) {
|
|
|
898
981
|
return useSyncExternalStore(HOOK.subscribe, select, select);
|
|
899
982
|
}`;
|
|
900
983
|
|
|
901
|
-
|
|
984
|
+
/** What `connect` does when `mapStateToProps` throws on the state of a store update, by react-redux's major version. */
|
|
985
|
+
const STORE_UPDATE_ERROR = {
|
|
986
|
+
// react-redux 8 maps a store update in its subscription, which drops the error and keeps the props from before
|
|
987
|
+
swallowed: `if (!update) throw error;`,
|
|
988
|
+
// react-redux 7 throws it again on every render until the next update
|
|
989
|
+
rethrown: `if (update) cache.error = error;
|
|
990
|
+
throw error;`
|
|
991
|
+
};
|
|
992
|
+
|
|
993
|
+
/** The `connect` that the store's source declares for its hook `hook`, as the react-redux of range `reactRedux` behaves. */
|
|
994
|
+
export function connectSource(hook: string, reactRedux: string | undefined): string {
|
|
995
|
+
return CONNECT.split("HOOK").join(hook).replace("STORE_UPDATE_ERROR", STORE_UPDATE_ERROR[(major(reactRedux) ?? 8) >= 8 ? "swallowed" : "rethrown"]);
|
|
996
|
+
}
|
|
997
|
+
|
|
998
|
+
const CONNECT = `export function connect(mapStateToProps, mapDispatchToProps, mergeProps, options) {
|
|
902
999
|
const forwardsRef = Boolean(options && options.forwardRef);
|
|
903
1000
|
const selectState = mapStateToProps ? state => state : () => undefined;
|
|
904
1001
|
const dependsOnOwnProps = map => map.dependsOnOwnProps !== undefined && map.dependsOnOwnProps !== null ? Boolean(map.dependsOnOwnProps) : map.length !== 1;
|
|
@@ -961,17 +1058,34 @@ export const CONNECT = `export function connect(mapStateToProps, mapDispatchToPr
|
|
|
961
1058
|
}
|
|
962
1059
|
}
|
|
963
1060
|
const ownProps = cache.ownProps;
|
|
964
|
-
|
|
965
|
-
|
|
1061
|
+
// Own props compare shallowly with those of the last render, whether that render finished or not
|
|
1062
|
+
const ownPropsChanged = !cache.seenOwnProps || !shallowEqual(cache.seenOwnProps, ownProps);
|
|
1063
|
+
cache.seenOwnProps = ownProps;
|
|
1064
|
+
const propsChanged = Boolean(mapState) && mapState.dependsOnOwnProps() && !(cache.stateOwnProps && shallowEqual(cache.stateOwnProps, ownProps));
|
|
1065
|
+
if (!cache.stateProps || (mapState && (cache.state !== state || propsChanged))) {
|
|
1066
|
+
// The state and props count as mapped before the map runs, so a render React retries after the map
|
|
1067
|
+
// throws keeps the props from before
|
|
1068
|
+
const update = cache.stateProps !== undefined && cache.state !== state && !propsChanged;
|
|
966
1069
|
cache.state = state;
|
|
967
1070
|
cache.stateOwnProps = ownProps;
|
|
1071
|
+
cache.error = undefined;
|
|
1072
|
+
try {
|
|
1073
|
+
cache.stateProps = mapState ? mapState.map(state, ownProps) : {};
|
|
1074
|
+
cache.kept = false;
|
|
1075
|
+
} catch (error) {
|
|
1076
|
+
// The props passed last stay, own props too, until the map returns again
|
|
1077
|
+
cache.kept = true;
|
|
1078
|
+
STORE_UPDATE_ERROR
|
|
1079
|
+
}
|
|
1080
|
+
} else if (cache.error) {
|
|
1081
|
+
throw cache.error;
|
|
968
1082
|
}
|
|
969
1083
|
if (!cache.dispatchProps || (mapDispatch && mapDispatch.dependsOnOwnProps() && cache.dispatchOwnProps !== ownProps)) {
|
|
970
1084
|
cache.dispatchProps = mapDispatch ? mapDispatch.map(HOOK.dispatch, ownProps) : mapDispatchToProps ? bound(mapDispatchToProps) : {dispatch: HOOK.dispatch};
|
|
971
1085
|
cache.dispatchOwnProps = ownProps;
|
|
972
1086
|
}
|
|
973
1087
|
const merged = {...ownProps, ...cache.stateProps, ...cache.dispatchProps};
|
|
974
|
-
if (!cache.merged || !shallowEqual(cache.merged, merged)) cache.merged = merged;
|
|
1088
|
+
if (!cache.merged || (!cache.kept || ownPropsChanged) && !shallowEqual(cache.merged, merged)) cache.merged = merged;
|
|
975
1089
|
if (!cache.element || cache.rendered !== cache.merged || cache.ref !== props.reactReduxForwardedRef) {
|
|
976
1090
|
cache.rendered = cache.merged;
|
|
977
1091
|
cache.ref = props.reactReduxForwardedRef;
|
|
@@ -992,7 +1106,24 @@ export const CONNECT = `export function connect(mapStateToProps, mapDispatchToPr
|
|
|
992
1106
|
}`;
|
|
993
1107
|
|
|
994
1108
|
|
|
995
|
-
|
|
1109
|
+
/**
|
|
1110
|
+
* Whether the Redux that creates a store is 5 or later, whose `dispatch` rejects a type that isn't a string: for a
|
|
1111
|
+
* store of Redux Toolkit, the Redux that Toolkit 2 depends on, and otherwise the Redux the package declares, or else
|
|
1112
|
+
* the one its Toolkit brings.
|
|
1113
|
+
*/
|
|
1114
|
+
function typedByString(facts: PackageFacts | undefined, fromToolkit: boolean): boolean {
|
|
1115
|
+
const redux = fromToolkit ? undefined : major(facts?.redux);
|
|
1116
|
+
if (redux !== undefined) return redux >= 5;
|
|
1117
|
+
return (major(facts?.toolkit) ?? 0) >= 2;
|
|
1118
|
+
}
|
|
1119
|
+
|
|
1120
|
+
/**
|
|
1121
|
+
* Rewrites the store's source for a store that moves whole: its reducer runs on one zustand store, whose `dispatch`
|
|
1122
|
+
* runs a thunk as Redux Toolkit's default middleware does and any other plain-object action with a `type` through the
|
|
1123
|
+
* reducer, as Redux does, and the store's variable keeps the store's `getState` and `dispatch`. A legacy `createStore`
|
|
1124
|
+
* has no middleware, so its `dispatch` runs no thunk, and its state starts from its preloaded state.
|
|
1125
|
+
*/
|
|
1126
|
+
async function convertReducerStore(cu: JS.CompilationUnit, p: Plan, facts: PackageFacts | undefined, ctx: ExecutionContext): Promise<J | undefined> {
|
|
996
1127
|
const store = p.store!;
|
|
997
1128
|
const {hook, reducer, renderer, selectorHook, listeners} = p.reducerStore!;
|
|
998
1129
|
const found = storeStatement(cu, store);
|
|
@@ -1005,6 +1136,10 @@ async function convertReducerStore(cu: JS.CompilationUnit, p: Plan, ctx: Executi
|
|
|
1005
1136
|
const legacy = store.reducerStore === "legacy" || store.reducerStore === "legacyThunk";
|
|
1006
1137
|
// redux-thunk runs a function with `dispatch` and `getState`, and passes any other action on to the store
|
|
1007
1138
|
const thunk = store.reducerStore === "legacyThunk";
|
|
1139
|
+
// Redux rejects what isn't a plain object with a type before a reducer sees it
|
|
1140
|
+
const checks = `if (typeof action !== "object" || action === null || ![Object.prototype, null].includes(Object.getPrototypeOf(action))) throw new Error("Actions must be plain objects.");
|
|
1141
|
+
if (action.type === undefined) throw new Error("Actions may not have an undefined 'type' property.");` +
|
|
1142
|
+
(typedByString(facts, importedAs(cu, RTK, "configureStore", "createStore", "legacy_createStore").has(store.api)) ? `\n if (typeof action.type !== "string") throw new Error("Action 'type' property must be a string.");` : "");
|
|
1008
1143
|
// react-redux batches a store's updates, so that a parent renders before the children it may remove
|
|
1009
1144
|
// Redux calls the listeners of `subscribe` after every dispatch, as they were when it began, before react-redux renders
|
|
1010
1145
|
const update = `${hook}.setState(${reducer}(${hook}.getState(), action), true);`;
|
|
@@ -1025,23 +1160,15 @@ async function convertReducerStore(cu: JS.CompilationUnit, p: Plan, ctx: Executi
|
|
|
1025
1160
|
await template`export const ${raw(hook)} = create(() => ${raw(reducer)}(${found.preloaded}, {type: "@@redux/INIT"}));`.apply(statement, cursor) :
|
|
1026
1161
|
await template`export const ${raw(hook)} = create(() => ${raw(reducer)}(undefined, {type: "@@redux/INIT"}));`.apply(statement, cursor),
|
|
1027
1162
|
...listeners ? [await template`const ${raw(listeners)} = new Map();`.apply(statement, cursor)] : [],
|
|
1028
|
-
thunk ?
|
|
1029
|
-
await template`${raw(hook)}.dispatch = action => {
|
|
1030
|
-
if (typeof action === "function") return action(${raw(hook)}.dispatch, ${raw(hook)}.getState, undefined);
|
|
1031
|
-
if (typeof action !== "object" || action === null || ![Object.prototype, null].includes(Object.getPrototypeOf(action))) throw new Error("Actions must be plain objects.");
|
|
1032
|
-
if (action.type === undefined) throw new Error("Actions may not have an undefined 'type' property.");
|
|
1033
|
-
${raw(setState)}
|
|
1034
|
-
return action;
|
|
1035
|
-
};`.apply(statement, cursor) :
|
|
1036
|
-
legacy ?
|
|
1163
|
+
legacy && !thunk ?
|
|
1037
1164
|
await template`${raw(hook)}.dispatch = action => {
|
|
1038
|
-
|
|
1039
|
-
if (action.type === undefined) throw new Error("Actions may not have an undefined 'type' property.");
|
|
1165
|
+
${raw(checks)}
|
|
1040
1166
|
${raw(setState)}
|
|
1041
1167
|
return action;
|
|
1042
1168
|
};`.apply(statement, cursor) :
|
|
1043
1169
|
await template`${raw(hook)}.dispatch = action => {
|
|
1044
1170
|
if (typeof action === "function") return action(${raw(hook)}.dispatch, ${raw(hook)}.getState, undefined);
|
|
1171
|
+
${raw(checks)}
|
|
1045
1172
|
${raw(setState)}
|
|
1046
1173
|
return action;
|
|
1047
1174
|
};`.apply(statement, cursor),
|
|
@@ -1049,7 +1176,7 @@ async function convertReducerStore(cu: JS.CompilationUnit, p: Plan, ctx: Executi
|
|
|
1049
1176
|
await template`export default {${raw(members)}};`.apply(statement, cursor) :
|
|
1050
1177
|
await template`${raw((statement as J.VariableDeclarations).modifiers.some(m => m.keyword === "export") ? "export " : "")}const ${raw(store.store)} = {${raw(members)}};`.apply(statement, cursor),
|
|
1051
1178
|
...selectorHook ? [await template`${raw(SELECTOR.split("SELECTOR_HOOK").join(selectorHook).split("HOOK").join(hook))}`.apply(statement, cursor)] : [],
|
|
1052
|
-
...renderer ? [await template`${raw(
|
|
1179
|
+
...renderer ? [await template`${raw(connectSource(hook, facts?.reactRedux))}`.apply(statement, cursor)] : []
|
|
1053
1180
|
];
|
|
1054
1181
|
const statements: J.RightPadded<Statement>[] = [...cu.statements.slice(0, found.index)];
|
|
1055
1182
|
for (let i = 0; i < generated.length; i++) {
|
|
@@ -1106,9 +1233,9 @@ async function convertReducerConsumer(cu: JS.CompilationUnit, p: Plan, scanned:
|
|
|
1106
1233
|
const source = scanned.sources.get(cu.sourcePath);
|
|
1107
1234
|
// A read of the state keeps the store's own hook; another selector, on zustand 5, goes through the store's selector hook
|
|
1108
1235
|
const reads = (selector: J | undefined) => !!selectorRead(selector) ||
|
|
1109
|
-
isIdentifier(selector) && !!source && readSelector(source, selector.simpleName, scanned.sources);
|
|
1236
|
+
isIdentifier(selector) && !!source && readSelector(source, selector.simpleName, scanned.sources, resolverOf(scanned));
|
|
1110
1237
|
const bindings = importBindings(cu);
|
|
1111
|
-
const followed = new Map(bindings.filter(b => b.module
|
|
1238
|
+
const followed = new Map(bindings.filter(b => followsImport(b.module)).map(b => [b.local, b]));
|
|
1112
1239
|
const reactRedux = (name: string, member: string) => followed.get(name)?.module === REACT_REDUX && followed.get(name)?.name === member;
|
|
1113
1240
|
const removed = new Set<string>();
|
|
1114
1241
|
// The store's hooks the source now calls
|
|
@@ -1169,7 +1296,7 @@ async function convertReducerConsumer(cu: JS.CompilationUnit, p: Plan, scanned:
|
|
|
1169
1296
|
// The store's variable stays, so its import goes only where nothing uses it any more
|
|
1170
1297
|
if (removed.has("Provider")) {
|
|
1171
1298
|
for (const binding of bindings) {
|
|
1172
|
-
if (binding.module !== REACT_REDUX &&
|
|
1299
|
+
if (binding.module !== REACT_REDUX && resolverOf(scanned)(cu.sourcePath, binding.module) === p.store!.path) maybeRemoveImport(this, binding.module, binding.name);
|
|
1173
1300
|
}
|
|
1174
1301
|
}
|
|
1175
1302
|
for (const member of [hook, selectorHook]) {
|