@openrewrite/recipes-react 0.20.0 → 0.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (276) hide show
  1. package/dist/i18n/translate-hard-coded-strings.d.ts +67 -0
  2. package/dist/i18n/translate-hard-coded-strings.d.ts.map +1 -0
  3. package/dist/i18n/translate-hard-coded-strings.js +439 -0
  4. package/dist/i18n/translate-hard-coded-strings.js.map +1 -0
  5. package/dist/index.d.ts +3 -0
  6. package/dist/index.d.ts.map +1 -1
  7. package/dist/index.js +37 -1
  8. package/dist/index.js.map +1 -1
  9. package/dist/mui/adapt-v4-theme.d.ts +8 -0
  10. package/dist/mui/adapt-v4-theme.d.ts.map +1 -0
  11. package/dist/mui/adapt-v4-theme.js +65 -0
  12. package/dist/mui/adapt-v4-theme.js.map +1 -0
  13. package/dist/mui/add-component-prop.d.ts +18 -0
  14. package/dist/mui/add-component-prop.d.ts.map +1 -0
  15. package/dist/mui/add-component-prop.js +53 -0
  16. package/dist/mui/add-component-prop.js.map +1 -0
  17. package/dist/mui/add-emotion-prepend.d.ts +8 -0
  18. package/dist/mui/add-emotion-prepend.d.ts.map +1 -0
  19. package/dist/mui/add-emotion-prepend.js +71 -0
  20. package/dist/mui/add-emotion-prepend.js.map +1 -0
  21. package/dist/mui/change-module-specifier.d.ts +14 -0
  22. package/dist/mui/change-module-specifier.d.ts.map +1 -0
  23. package/dist/mui/change-module-specifier.js +95 -0
  24. package/dist/mui/change-module-specifier.js.map +1 -0
  25. package/dist/mui/convert-mui-imports.d.ts +14 -0
  26. package/dist/mui/convert-mui-imports.d.ts.map +1 -0
  27. package/dist/mui/convert-mui-imports.js +195 -0
  28. package/dist/mui/convert-mui-imports.js.map +1 -0
  29. package/dist/mui/convert-prop-to-sx.d.ts +22 -0
  30. package/dist/mui/convert-prop-to-sx.d.ts.map +1 -0
  31. package/dist/mui/convert-prop-to-sx.js +99 -0
  32. package/dist/mui/convert-prop-to-sx.js.map +1 -0
  33. package/dist/mui/index.d.ts +32 -0
  34. package/dist/mui/index.d.ts.map +1 -0
  35. package/dist/mui/index.js +67 -0
  36. package/dist/mui/index.js.map +1 -0
  37. package/dist/mui/jsx-attributes.d.ts +27 -0
  38. package/dist/mui/jsx-attributes.d.ts.map +1 -0
  39. package/dist/mui/jsx-attributes.js +140 -0
  40. package/dist/mui/jsx-attributes.js.map +1 -0
  41. package/dist/mui/mark-manual-migration.d.ts +16 -0
  42. package/dist/mui/mark-manual-migration.d.ts.map +1 -0
  43. package/dist/mui/mark-manual-migration.js +73 -0
  44. package/dist/mui/mark-manual-migration.js.map +1 -0
  45. package/dist/mui/mark-palette-mode-usage.d.ts +12 -0
  46. package/dist/mui/mark-palette-mode-usage.d.ts.map +1 -0
  47. package/dist/mui/mark-palette-mode-usage.js +50 -0
  48. package/dist/mui/mark-palette-mode-usage.js.map +1 -0
  49. package/dist/mui/move-component-prop-to-slot.d.ts +22 -0
  50. package/dist/mui/move-component-prop-to-slot.d.ts.map +1 -0
  51. package/dist/mui/move-component-prop-to-slot.js +87 -0
  52. package/dist/mui/move-component-prop-to-slot.js.map +1 -0
  53. package/dist/mui/move-primary-text-to-children.d.ts +12 -0
  54. package/dist/mui/move-primary-text-to-children.d.ts.map +1 -0
  55. package/dist/mui/move-primary-text-to-children.js +52 -0
  56. package/dist/mui/move-primary-text-to-children.js.map +1 -0
  57. package/dist/mui/move-system-props-to-sx.d.ts +16 -0
  58. package/dist/mui/move-system-props-to-sx.d.ts.map +1 -0
  59. package/dist/mui/move-system-props-to-sx.js +122 -0
  60. package/dist/mui/move-system-props-to-sx.js.map +1 -0
  61. package/dist/mui/mui-components.d.ts +8 -0
  62. package/dist/mui/mui-components.d.ts.map +1 -0
  63. package/dist/mui/mui-components.js +41 -0
  64. package/dist/mui/mui-components.js.map +1 -0
  65. package/dist/mui/mui-tag-visitor.d.ts +5 -0
  66. package/dist/mui/mui-tag-visitor.d.ts.map +1 -0
  67. package/dist/mui/mui-tag-visitor.js +54 -0
  68. package/dist/mui/mui-tag-visitor.js.map +1 -0
  69. package/dist/mui/pre-v5-recipe.d.ts +14 -0
  70. package/dist/mui/pre-v5-recipe.d.ts.map +1 -0
  71. package/dist/mui/pre-v5-recipe.js +88 -0
  72. package/dist/mui/pre-v5-recipe.js.map +1 -0
  73. package/dist/mui/remove-component-prop.d.ts +18 -0
  74. package/dist/mui/remove-component-prop.d.ts.map +1 -0
  75. package/dist/mui/remove-component-prop.js +55 -0
  76. package/dist/mui/remove-component-prop.js.map +1 -0
  77. package/dist/mui/remove-root-ref.d.ts +8 -0
  78. package/dist/mui/remove-root-ref.d.ts.map +1 -0
  79. package/dist/mui/remove-root-ref.js +61 -0
  80. package/dist/mui/remove-root-ref.js.map +1 -0
  81. package/dist/mui/remove-spacing-px-suffix.d.ts +8 -0
  82. package/dist/mui/remove-spacing-px-suffix.d.ts.map +1 -0
  83. package/dist/mui/remove-spacing-px-suffix.js +62 -0
  84. package/dist/mui/remove-spacing-px-suffix.js.map +1 -0
  85. package/dist/mui/rename-component-prop.d.ts +20 -0
  86. package/dist/mui/rename-component-prop.d.ts.map +1 -0
  87. package/dist/mui/rename-component-prop.js +66 -0
  88. package/dist/mui/rename-component-prop.js.map +1 -0
  89. package/dist/mui/rename-joy-css-variables.d.ts +8 -0
  90. package/dist/mui/rename-joy-css-variables.d.ts.map +1 -0
  91. package/dist/mui/rename-joy-css-variables.js +51 -0
  92. package/dist/mui/rename-joy-css-variables.js.map +1 -0
  93. package/dist/mui/rename-theme-palette-type.d.ts +8 -0
  94. package/dist/mui/rename-theme-palette-type.d.ts.map +1 -0
  95. package/dist/mui/rename-theme-palette-type.js +61 -0
  96. package/dist/mui/rename-theme-palette-type.js.map +1 -0
  97. package/dist/mui/replace-box-border-radius.d.ts +10 -0
  98. package/dist/mui/replace-box-border-radius.d.ts.map +1 -0
  99. package/dist/mui/replace-box-border-radius.js +50 -0
  100. package/dist/mui/replace-box-border-radius.js.map +1 -0
  101. package/dist/mui/replace-breakpoints-width.d.ts +8 -0
  102. package/dist/mui/replace-breakpoints-width.d.ts.map +1 -0
  103. package/dist/mui/replace-breakpoints-width.js +46 -0
  104. package/dist/mui/replace-breakpoints-width.js.map +1 -0
  105. package/dist/mui/replace-component-class.d.ts +18 -0
  106. package/dist/mui/replace-component-class.d.ts.map +1 -0
  107. package/dist/mui/replace-component-class.js +126 -0
  108. package/dist/mui/replace-component-class.js.map +1 -0
  109. package/dist/mui/replace-components-with-slots.d.ts +14 -0
  110. package/dist/mui/replace-components-with-slots.d.ts.map +1 -0
  111. package/dist/mui/replace-components-with-slots.js +69 -0
  112. package/dist/mui/replace-components-with-slots.js.map +1 -0
  113. package/dist/mui/replace-import-paths.d.ts +14 -0
  114. package/dist/mui/replace-import-paths.d.ts.map +1 -0
  115. package/dist/mui/replace-import-paths.js +101 -0
  116. package/dist/mui/replace-import-paths.js.map +1 -0
  117. package/dist/mui/replace-in-string-literals.d.ts +15 -0
  118. package/dist/mui/replace-in-string-literals.d.ts.map +1 -0
  119. package/dist/mui/replace-in-string-literals.js +62 -0
  120. package/dist/mui/replace-in-string-literals.js.map +1 -0
  121. package/dist/mui/replace-list-item-button-prop.d.ts +12 -0
  122. package/dist/mui/replace-list-item-button-prop.d.ts.map +1 -0
  123. package/dist/mui/replace-list-item-button-prop.js +80 -0
  124. package/dist/mui/replace-list-item-button-prop.js.map +1 -0
  125. package/dist/mui/replace-tabs-scroll-buttons.d.ts +8 -0
  126. package/dist/mui/replace-tabs-scroll-buttons.d.ts.map +1 -0
  127. package/dist/mui/replace-tabs-scroll-buttons.js +41 -0
  128. package/dist/mui/replace-tabs-scroll-buttons.js.map +1 -0
  129. package/dist/mui/replace-theme-color-functions.d.ts +8 -0
  130. package/dist/mui/replace-theme-color-functions.d.ts.map +1 -0
  131. package/dist/mui/replace-theme-color-functions.js +72 -0
  132. package/dist/mui/replace-theme-color-functions.js.map +1 -0
  133. package/dist/mui/replace-theme-spacing-unit.d.ts +8 -0
  134. package/dist/mui/replace-theme-spacing-unit.d.ts.map +1 -0
  135. package/dist/mui/replace-theme-spacing-unit.js +77 -0
  136. package/dist/mui/replace-theme-spacing-unit.js.map +1 -0
  137. package/dist/mui/replace-typography-round.d.ts +8 -0
  138. package/dist/mui/replace-typography-round.d.ts.map +1 -0
  139. package/dist/mui/replace-typography-round.js +44 -0
  140. package/dist/mui/replace-typography-round.js.map +1 -0
  141. package/dist/mui/shift-hidden-down-props.d.ts +10 -0
  142. package/dist/mui/shift-hidden-down-props.d.ts.map +1 -0
  143. package/dist/mui/shift-hidden-down-props.js +49 -0
  144. package/dist/mui/shift-hidden-down-props.js.map +1 -0
  145. package/dist/mui/theme-access.d.ts +5 -0
  146. package/dist/mui/theme-access.d.ts.map +1 -0
  147. package/dist/mui/theme-access.js +21 -0
  148. package/dist/mui/theme-access.js.map +1 -0
  149. package/dist/mui/update-theme-breakpoints.d.ts +10 -0
  150. package/dist/mui/update-theme-breakpoints.d.ts.map +1 -0
  151. package/dist/mui/update-theme-breakpoints.js +58 -0
  152. package/dist/mui/update-theme-breakpoints.js.map +1 -0
  153. package/dist/mui/upgrade-grid-props.d.ts +16 -0
  154. package/dist/mui/upgrade-grid-props.d.ts.map +1 -0
  155. package/dist/mui/upgrade-grid-props.js +90 -0
  156. package/dist/mui/upgrade-grid-props.js.map +1 -0
  157. package/dist/search/find-enzyme-usage.d.ts +8 -0
  158. package/dist/search/find-enzyme-usage.d.ts.map +1 -1
  159. package/dist/search/find-enzyme-usage.js +119 -8
  160. package/dist/search/find-enzyme-usage.js.map +1 -1
  161. package/dist/search/find-hard-coded-strings.d.ts +110 -0
  162. package/dist/search/find-hard-coded-strings.d.ts.map +1 -0
  163. package/dist/search/find-hard-coded-strings.js +987 -0
  164. package/dist/search/find-hard-coded-strings.js.map +1 -0
  165. package/dist/search/find-missing-use-client-directive.d.ts +2 -0
  166. package/dist/search/find-missing-use-client-directive.d.ts.map +1 -1
  167. package/dist/search/find-missing-use-client-directive.js +1 -0
  168. package/dist/search/find-missing-use-client-directive.js.map +1 -1
  169. package/dist/testing/enzyme-host-components.d.ts +12 -0
  170. package/dist/testing/enzyme-host-components.d.ts.map +1 -1
  171. package/dist/testing/enzyme-host-components.js +100 -0
  172. package/dist/testing/enzyme-host-components.js.map +1 -1
  173. package/dist/testing/enzyme-portals.d.ts +3 -5
  174. package/dist/testing/enzyme-portals.d.ts.map +1 -1
  175. package/dist/testing/enzyme-portals.js +8 -39
  176. package/dist/testing/enzyme-portals.js.map +1 -1
  177. package/dist/testing/enzyme-render-blockers.d.ts +19 -0
  178. package/dist/testing/enzyme-render-blockers.d.ts.map +1 -0
  179. package/dist/testing/enzyme-render-blockers.js +275 -0
  180. package/dist/testing/enzyme-render-blockers.js.map +1 -0
  181. package/dist/testing/enzyme-to-react-testing-library.d.ts +17 -3
  182. package/dist/testing/enzyme-to-react-testing-library.d.ts.map +1 -1
  183. package/dist/testing/enzyme-to-react-testing-library.js +237 -27
  184. package/dist/testing/enzyme-to-react-testing-library.js.map +1 -1
  185. package/dist/testing/enzyme-usage.d.ts +9 -0
  186. package/dist/testing/enzyme-usage.d.ts.map +1 -1
  187. package/dist/testing/enzyme-usage.js +36 -3
  188. package/dist/testing/enzyme-usage.js.map +1 -1
  189. package/dist/testing/enzyme-wrapper-scope.d.ts +8 -1
  190. package/dist/testing/enzyme-wrapper-scope.d.ts.map +1 -1
  191. package/dist/testing/enzyme-wrapper-scope.js +26 -5
  192. package/dist/testing/enzyme-wrapper-scope.js.map +1 -1
  193. package/dist/util/json-and-javascript.d.ts +4 -0
  194. package/dist/util/json-and-javascript.d.ts.map +1 -0
  195. package/dist/util/json-and-javascript.js +37 -0
  196. package/dist/util/json-and-javascript.js.map +1 -0
  197. package/dist/util/module-imports.d.ts +36 -0
  198. package/dist/util/module-imports.d.ts.map +1 -1
  199. package/dist/util/module-imports.js +216 -0
  200. package/dist/util/module-imports.js.map +1 -1
  201. package/dist/util/test-source.d.ts +2 -0
  202. package/dist/util/test-source.d.ts.map +1 -0
  203. package/dist/util/test-source.js +5 -0
  204. package/dist/util/test-source.js.map +1 -0
  205. package/dist/zustand/entry-store.d.ts +9 -0
  206. package/dist/zustand/entry-store.d.ts.map +1 -0
  207. package/dist/zustand/entry-store.js +136 -0
  208. package/dist/zustand/entry-store.js.map +1 -0
  209. package/dist/zustand/redux-stores.d.ts +7 -4
  210. package/dist/zustand/redux-stores.d.ts.map +1 -1
  211. package/dist/zustand/redux-stores.js +128 -11
  212. package/dist/zustand/redux-stores.js.map +1 -1
  213. package/dist/zustand/redux-to-zustand.d.ts +11 -2
  214. package/dist/zustand/redux-to-zustand.d.ts.map +1 -1
  215. package/dist/zustand/redux-to-zustand.js +147 -46
  216. package/dist/zustand/redux-to-zustand.js.map +1 -1
  217. package/dist/zustand/zustand-plan.d.ts +14 -5
  218. package/dist/zustand/zustand-plan.d.ts.map +1 -1
  219. package/dist/zustand/zustand-plan.js +226 -52
  220. package/dist/zustand/zustand-plan.js.map +1 -1
  221. package/package.json +1 -1
  222. package/src/i18n/translate-hard-coded-strings.ts +442 -0
  223. package/src/index.ts +17 -0
  224. package/src/mui/adapt-v4-theme.ts +43 -0
  225. package/src/mui/add-component-prop.ts +43 -0
  226. package/src/mui/add-emotion-prepend.ts +48 -0
  227. package/src/mui/change-module-specifier.ts +71 -0
  228. package/src/mui/convert-mui-imports.ts +184 -0
  229. package/src/mui/convert-prop-to-sx.ts +89 -0
  230. package/src/mui/index.ts +31 -0
  231. package/src/mui/jsx-attributes.ts +133 -0
  232. package/src/mui/mark-manual-migration.ts +53 -0
  233. package/src/mui/mark-palette-mode-usage.ts +36 -0
  234. package/src/mui/move-component-prop-to-slot.ts +84 -0
  235. package/src/mui/move-primary-text-to-children.ts +41 -0
  236. package/src/mui/move-system-props-to-sx.ts +118 -0
  237. package/src/mui/mui-components.ts +40 -0
  238. package/src/mui/mui-tag-visitor.ts +36 -0
  239. package/src/mui/pre-v5-recipe.ts +82 -0
  240. package/src/mui/remove-component-prop.ts +43 -0
  241. package/src/mui/remove-root-ref.ts +41 -0
  242. package/src/mui/remove-spacing-px-suffix.ts +43 -0
  243. package/src/mui/rename-component-prop.ts +55 -0
  244. package/src/mui/rename-joy-css-variables.ts +41 -0
  245. package/src/mui/rename-theme-palette-type.ts +42 -0
  246. package/src/mui/replace-box-border-radius.ts +42 -0
  247. package/src/mui/replace-breakpoints-width.ts +28 -0
  248. package/src/mui/replace-component-class.ts +97 -0
  249. package/src/mui/replace-components-with-slots.ts +61 -0
  250. package/src/mui/replace-import-paths.ts +100 -0
  251. package/src/mui/replace-in-string-literals.ts +44 -0
  252. package/src/mui/replace-list-item-button-prop.ts +59 -0
  253. package/src/mui/replace-tabs-scroll-buttons.ts +31 -0
  254. package/src/mui/replace-theme-color-functions.ts +55 -0
  255. package/src/mui/replace-theme-spacing-unit.ts +59 -0
  256. package/src/mui/replace-typography-round.ts +29 -0
  257. package/src/mui/shift-hidden-down-props.ts +44 -0
  258. package/src/mui/theme-access.ts +18 -0
  259. package/src/mui/update-theme-breakpoints.ts +47 -0
  260. package/src/mui/upgrade-grid-props.ts +82 -0
  261. package/src/search/find-enzyme-usage.ts +109 -12
  262. package/src/search/find-hard-coded-strings.ts +1006 -0
  263. package/src/search/find-missing-use-client-directive.ts +1 -1
  264. package/src/testing/enzyme-host-components.ts +110 -0
  265. package/src/testing/enzyme-portals.ts +4 -44
  266. package/src/testing/enzyme-render-blockers.ts +278 -0
  267. package/src/testing/enzyme-to-react-testing-library.ts +240 -34
  268. package/src/testing/enzyme-usage.ts +48 -2
  269. package/src/testing/enzyme-wrapper-scope.ts +35 -3
  270. package/src/util/json-and-javascript.ts +26 -0
  271. package/src/util/module-imports.ts +223 -0
  272. package/src/util/test-source.ts +2 -0
  273. package/src/zustand/entry-store.ts +131 -0
  274. package/src/zustand/redux-stores.ts +131 -12
  275. package/src/zustand/redux-to-zustand.ts +179 -52
  276. package/src/zustand/zustand-plan.ts +256 -49
@@ -0,0 +1,442 @@
1
+ import {check, Cursor, emptyMarkers, ExecutionContext, not, Option, randomId, ScanningRecipe, TreeVisitor} from "@openrewrite/rewrite";
2
+ import {bindingNames, isVendoredOrBundled, JavaScriptParser, JavaScriptVisitor, JS, JSX, maybeAddImport, raw, scopeOf, template} from "@openrewrite/rewrite/javascript";
3
+ import {emptySpace, isIdentifier, J, Type} from "@openrewrite/rewrite/java";
4
+ import {Json, jsonLiteral, JsonVisitor, setMember} from "@openrewrite/rewrite/json";
5
+ import {
6
+ dependencyNames, FindingSink, FUNCTION_KINDS, functionName, HardCodedStringRow, HardCodedStringsVisitor, propertyPath, stringValue
7
+ } from "../search/find-hard-coded-strings";
8
+ import {hasDirective} from "../search/find-missing-use-client-directive";
9
+ import {jsonAndJavaScript} from "../util/json-and-javascript";
10
+
11
+ /** A source-language locale file of i18next, such as `public/locales/en/translation.json` or `locales/en.json`. */
12
+ const SOURCE_LOCALE = /(^|\/)locales?\/en([-_][A-Za-z]{2,4})?(?:\/([^/]+))?\.json$/;
13
+
14
+ interface Locale {
15
+ path: string;
16
+ /** The namespace a `useTranslation` call names to read it, or undefined for i18next's default `translation`. */
17
+ namespace?: string;
18
+ /** Whether it is plain or US English, which a project with several English locales writes first. */
19
+ primary: boolean;
20
+ /** Every string the file holds, by its dotted key. */
21
+ entries: Map<string, string>;
22
+ /** The dotted key of every member, whatever its value, which a new key must not overwrite. */
23
+ taken: Set<string>;
24
+ }
25
+
26
+ /** A string to translate: a literal, or a template literal whose interpolations are names. */
27
+ interface Finding {
28
+ file: string;
29
+ node: string;
30
+ component: string;
31
+ text: string;
32
+ /** For a template literal, each placeholder and the expression it stands for. */
33
+ values?: {name: string, expression: string}[];
34
+ /** Whether the source starts with `'use client'`, without which a Next.js app router may render it as a server component. */
35
+ client: boolean;
36
+ }
37
+
38
+ /** A component holding strings to translate, and the namespace of the `useTranslation` it already calls, if any. */
39
+ interface Component {
40
+ file: string;
41
+ hook?: {namespace?: string};
42
+ }
43
+
44
+ class Plan {
45
+ readonly packages = new Map<string, ReadonlySet<string>>();
46
+ readonly locales: Locale[] = [];
47
+ readonly findings: Finding[] = [];
48
+ readonly components = new Map<string, Component>();
49
+ /** Every source path seen, to find which packages have a Next.js `app` directory. */
50
+ readonly sources: string[] = [];
51
+ private decided?: Decisions;
52
+
53
+ decisions(localeFile?: string): Decisions {
54
+ return this.decided ??= this.decide(localeFile);
55
+ }
56
+
57
+ private decide(localeFile?: string): Decisions {
58
+ const keys = new Map<string, {key: string, values?: Finding["values"]}>();
59
+ const hooks = new Map<string, string | undefined>();
60
+ const added = new Map<string, Map<string, string>>();
61
+ const files = new Map<string, {hook: boolean}>();
62
+ for (const finding of this.findings) {
63
+ const locale = this.localeFor(finding.file, localeFile);
64
+ const component = this.components.get(finding.component);
65
+ if (!locale || !component || component.hook && component.hook.namespace !== locale.namespace) continue;
66
+ if (!finding.client && this.appRouters().has(this.rootOf(finding.file)!)) continue;
67
+ if (!component.hook) hooks.set(finding.component, locale.namespace);
68
+ files.set(finding.file, {hook: !component.hook || !!files.get(finding.file)?.hook});
69
+ const entries = added.get(locale.path) ?? new Map<string, string>();
70
+ added.set(locale.path, entries);
71
+ keys.set(finding.node, {key: this.keyFor(finding.text, locale, entries), values: finding.values});
72
+ }
73
+ return {keys, hooks, added, files};
74
+ }
75
+
76
+ /** The source locale file of the package holding `file`, where that package uses react-i18next and has exactly one. */
77
+ private localeFor(file: string, localeFile?: string): Locale | undefined {
78
+ const root = this.rootOf(file);
79
+ if (root === undefined || !this.packages.get(root)!.has("react-i18next")) return undefined;
80
+ const named = localeFile ? this.locales.find(locale => locale.path === localeFile) : undefined;
81
+ if (named) return this.rootOf(named.path) === root ? named : undefined;
82
+ const candidates = this.locales.filter(locale => locale.path !== localeFile && this.rootOf(locale.path) === root);
83
+ if (candidates.length === 1) return candidates[0];
84
+ const defaults = candidates.filter(locale => locale.namespace === undefined);
85
+ const preferred = defaults.length > 1 ? defaults.filter(locale => locale.primary) : defaults;
86
+ return preferred.length === 1 ? preferred[0] : undefined;
87
+ }
88
+
89
+ private routers?: Set<string>;
90
+
91
+ /** The roots of Next.js packages with an `app` directory, where any component without `'use client'` may be a server component. */
92
+ private appRouters(): Set<string> {
93
+ return this.routers ??= new Set(this.sources.flatMap(path => {
94
+ const root = this.rootOf(path);
95
+ return root !== undefined && this.packages.get(root)!.has("next") && /^(src\/)?app\//.test(path.slice(root.length)) ? [root] : [];
96
+ }));
97
+ }
98
+
99
+ private readonly roots = new Map<string, string | undefined>();
100
+
101
+ /** The root of the package holding `path`: the nearest directory with a `package.json`. */
102
+ private rootOf(path: string): string | undefined {
103
+ if (!this.roots.has(path)) this.roots.set(path, [...this.packages.keys()].filter(root => path.startsWith(root)).sort((a, b) => b.length - a.length)[0]);
104
+ return this.roots.get(path);
105
+ }
106
+
107
+ private readonly styles = new Map<string, {byText: boolean, dots: boolean, colons: boolean, keysByValue: Map<string, string>}>();
108
+
109
+ /**
110
+ * The key for `text` in `locale`: one whose value already is the text; else the text itself where the file keys by
111
+ * text and uses any `.` or `:` in it, which i18next otherwise reads as key and namespace separators; else a generated one.
112
+ */
113
+ private keyFor(text: string, locale: Locale, added: Map<string, string>): string {
114
+ let style = this.styles.get(locale.path);
115
+ if (!style) {
116
+ const keys = [...locale.entries.keys()];
117
+ style = {
118
+ byText: keys.length > 0 && [...locale.entries].filter(([key, value]) => key === value).length * 2 >= keys.length,
119
+ dots: keys.some(key => key.includes(".") && locale.entries.get(key) === key),
120
+ colons: keys.some(key => key.includes(":")),
121
+ keysByValue: new Map([...locale.entries].reverse().map(([key, value]) => [value, key]))
122
+ };
123
+ this.styles.set(locale.path, style);
124
+ }
125
+ const existing = style.keysByValue.get(text);
126
+ if (existing !== undefined) return existing;
127
+ const byText = style.byText && (style.dots || !text.includes(".")) && (style.colons || !text.includes(":"));
128
+ const base = byText ? text : text.toLowerCase().normalize("NFKD").replace(/[^\p{L}\p{N}]+/gu, " ").trim().split(" ").slice(0, 6).join("_") || "text";
129
+ let key = base;
130
+ for (let n = 2; locale.taken.has(key) || added.has(key); n++) key = `${base}_${n}`;
131
+ added.set(key, text);
132
+ style.keysByValue.set(text, key);
133
+ return key;
134
+ }
135
+ }
136
+
137
+ interface Decisions {
138
+ /** Each string to translate by node id, with its key. */
139
+ keys: Map<string, {key: string, values?: Finding["values"]}>;
140
+ /** Each component that needs a `useTranslation` call, with the namespace it names. */
141
+ hooks: Map<string, string | undefined>;
142
+ /** The entries to add to each locale file. */
143
+ added: Map<string, Map<string, string>>;
144
+ /** The sources to change, and whether any of their components needs a `useTranslation` call. */
145
+ files: Map<string, {hook: boolean}>;
146
+ }
147
+
148
+ /**
149
+ * Translates the hard-coded strings that function components show with react-i18next, as `{t("key")}`,
150
+ * in packages that already depend on it and have one source locale file.
151
+ *
152
+ * @example
153
+ * // before
154
+ * export function Dialog({name}) { return <button title="Close">Delete {name}</button>; }
155
+ * // after
156
+ * export function Dialog({name}) { const {t} = useTranslation(); return <button title={t("Close")}>Delete {name}</button>; }
157
+ *
158
+ * @see https://react.i18next.com/latest/usetranslation-hook
159
+ */
160
+ export class TranslateHardCodedStrings extends ScanningRecipe<Plan> {
161
+ readonly name = "org.openrewrite.react.i18n.translate-hard-coded-strings";
162
+ readonly displayName = "Translate hard-coded strings with react-i18next";
163
+ readonly description = "Replaces the hard-coded strings that `FindHardCodedStrings` reports in function components with `t(\"key\")` calls of react-i18next's " +
164
+ "`useTranslation` hook, and adds each new key to the source locale file. A template literal whose interpolations are names becomes `t(\"key\", {name})`. " +
165
+ "Keys follow the locale file: the text itself where its keys are mostly their own text, otherwise a generated key, reusing a key whose value is already the text. " +
166
+ "Only packages that depend on react-i18next and have one English locale file, such as `public/locales/en/translation.json`, are changed. " +
167
+ "Sentences that need `<Trans>`, strings outside function components with a block body, class components, async components, components without `'use client'` in a Next.js app router, and components whose `t` is something else stay as they are.";
168
+
169
+ @Option({
170
+ displayName: "Locale file",
171
+ description: "The source-language locale file to add keys to, where a package has more than one candidate.",
172
+ required: false,
173
+ example: "public/locales/en/translation.json"
174
+ })
175
+ localeFile?: string;
176
+
177
+ constructor(options?: {localeFile?: string}) {
178
+ super(options);
179
+ }
180
+
181
+ initialValue(): Plan {
182
+ return new Plan();
183
+ }
184
+
185
+ async scanner(plan: Plan): Promise<TreeVisitor<any, ExecutionContext>> {
186
+ const localeFile = this.localeFile;
187
+ const sink: FindingSink = {insertRow: (_ctx, row, node, cursor) => plan && node && cursor && collect(plan, row, node, cursor)};
188
+ const sources = await check(not(isVendoredOrBundled()), new class extends HardCodedStringsVisitor {
189
+ override async visitJsCompilationUnit(cu: JS.CompilationUnit, ctx: ExecutionContext): Promise<J | undefined> {
190
+ plan?.sources.push(cu.sourcePath);
191
+ return super.visitJsCompilationUnit(cu, ctx);
192
+ }
193
+ }(undefined, sink));
194
+ const manifests = new class extends JsonVisitor<ExecutionContext> {
195
+ override async visitDocument(doc: Json.Document): Promise<Json | undefined> {
196
+ if (!plan) return doc;
197
+ if (/(^|\/)package\.json$/.test(doc.sourcePath)) plan.packages.set(doc.sourcePath.slice(0, -"package.json".length), dependencyNames(doc));
198
+ const locale = SOURCE_LOCALE.exec(doc.sourcePath);
199
+ if (locale || doc.sourcePath === localeFile) {
200
+ const namespace = !locale || locale[3] === "translation" ? undefined : locale[3];
201
+ const taken = new Set<string>();
202
+ plan.locales.push({path: doc.sourcePath, namespace, primary: !locale?.[2] || /^[-_]us$/i.test(locale[2]), entries: flatten(doc.value, "", new Map(), taken), taken});
203
+ }
204
+ return doc;
205
+ }
206
+ }();
207
+ // The search visitor marks what it finds; scanning keeps the sources as they are
208
+ return jsonAndJavaScript(manifests, sources, true);
209
+ }
210
+
211
+ async editorWithData(plan: Plan): Promise<TreeVisitor<any, ExecutionContext>> {
212
+ const decisions = plan.decisions(this.localeFile);
213
+ const locales = new class extends JsonVisitor<ExecutionContext> {
214
+ override async visitDocument(doc: Json.Document): Promise<Json | undefined> {
215
+ const entries = decisions.added.get(doc.sourcePath);
216
+ if (!entries?.size || doc.value.kind !== Json.Kind.Object) return doc;
217
+ let value = doc.value as Json.Object;
218
+ for (const [key, text] of entries) value = setMember(value, key, jsonLiteral(text));
219
+ return value === doc.value ? doc : {...doc, value} as Json.Document;
220
+ }
221
+ }();
222
+ const sources = await check(not(isVendoredOrBundled()), new Translator(decisions));
223
+ return jsonAndJavaScript(locales, sources);
224
+ }
225
+ }
226
+
227
+ /** Records a string the search visitor found, where a function component with a block body shows it as plain text. */
228
+ function collect(plan: Plan, row: HardCodedStringRow, node: J, cursor: Cursor): void {
229
+ if (row.context !== "JSX" || node.kind === JS.Kind.JsxTag) return;
230
+ let text: string | undefined;
231
+ let values: Finding["values"];
232
+ if (node.kind === J.Kind.Literal && row.kind !== "MIXED") {
233
+ text = decodeEntities(row.text);
234
+ } else if (node.kind === JS.Kind.TemplateExpression) {
235
+ const template = templateText(node as JS.TemplateExpression);
236
+ text = template?.text;
237
+ values = template?.values;
238
+ }
239
+ const component = enclosingComponent(cursor);
240
+ if (text === undefined || !component) return;
241
+ const hook = existingHook(component.value as J);
242
+ if (hook === "unsupported") return;
243
+ // The `t` the string would call must be the component's own hook, or there must be none to shadow or clash with
244
+ const declaring = scopeOf(cursor).declaringScope("t");
245
+ if (hook ? declaring?.id !== bodyOf(component.value as J)?.id : declaring !== undefined) return;
246
+ const cu = cursor.firstEnclosing((t): t is JS.CompilationUnit => t.kind === JS.Kind.CompilationUnit)!;
247
+ plan.findings.push({file: row.sourcePath, node: node.id, component: component.value.id, text, values, client: hasDirective(cu, "use client")});
248
+ plan.components.set(component.value.id, {file: row.sourcePath, hook});
249
+ }
250
+
251
+ /** Rewrites the strings and components the plan decided on. */
252
+ class Translator extends JavaScriptVisitor<ExecutionContext> {
253
+ private hookName = "useTranslation";
254
+
255
+ constructor(private readonly decisions: Decisions) {
256
+ super();
257
+ }
258
+
259
+ override async visitJsCompilationUnit(cu: JS.CompilationUnit, ctx: ExecutionContext): Promise<J | undefined> {
260
+ const file = this.decisions.files.get(cu.sourcePath);
261
+ if (!file) return cu;
262
+ if (file.hook) {
263
+ this.hookName = maybeAddImport(this, {module: "react-i18next", member: "useTranslation", onlyIfReferenced: false}) ?? "useTranslation";
264
+ }
265
+ return super.visitJsCompilationUnit(cu, ctx);
266
+ }
267
+
268
+ override async visitJsxTag(tag: JSX.Tag, ctx: ExecutionContext): Promise<J | undefined> {
269
+ const visited = await super.visitJsxTag(tag, ctx) as JSX.Tag;
270
+ if (!visited.children?.some(child => this.decisions.keys.has(child.id))) return visited;
271
+ const children: JSX.Tag["children"] = [];
272
+ for (const child of visited.children) {
273
+ const decision = this.decisions.keys.get(child.id);
274
+ if (!decision || child.kind !== J.Kind.Literal) {
275
+ children.push(child);
276
+ continue;
277
+ }
278
+ // Keep the text's own whitespace around the call, so the layout and what React renders stay
279
+ const source = String((child as J.Literal).value);
280
+ const leading = /^\s*/.exec(source)![0];
281
+ const trailing = /\s*$/.exec(source.slice(leading.length))![0];
282
+ if (leading) children.push(textLiteral(leading));
283
+ children.push(embedded(await this.call(decision.key, undefined, child, ctx)));
284
+ if (trailing) children.push(textLiteral(trailing));
285
+ }
286
+ return {...visited, children} as JSX.Tag;
287
+ }
288
+
289
+ override async visitLiteral(literal: J.Literal, ctx: ExecutionContext): Promise<J | undefined> {
290
+ const decision = this.decisions.keys.get(literal.id);
291
+ const parent = this.cursor.parentTree()?.value as J | undefined;
292
+ if (!decision || parent?.kind === JS.Kind.JsxTag) return literal;
293
+ const call = await this.call(decision.key, undefined, literal, ctx);
294
+ return parent?.kind === JS.Kind.JsxAttribute ? {...embedded(call), prefix: literal.prefix} : {...call, prefix: literal.prefix};
295
+ }
296
+
297
+ override async visitTemplateExpression(expression: JS.TemplateExpression, ctx: ExecutionContext): Promise<J | undefined> {
298
+ const decision = this.decisions.keys.get(expression.id);
299
+ if (!decision) return super.visitTemplateExpression(expression, ctx);
300
+ return {...await this.call(decision.key, decision.values, expression, ctx), prefix: expression.prefix};
301
+ }
302
+
303
+ override async visitMethodDeclaration(method: J.MethodDeclaration, ctx: ExecutionContext): Promise<J | undefined> {
304
+ const visited = await super.visitMethodDeclaration(method, ctx) as J.MethodDeclaration;
305
+ return this.decisions.hooks.has(method.id) && visited.body ? {...visited, body: await this.withHook(visited.body, this.decisions.hooks.get(method.id))} as J.MethodDeclaration : visited;
306
+ }
307
+
308
+ override async visitArrowFunction(arrow: JS.ArrowFunction, ctx: ExecutionContext): Promise<J | undefined> {
309
+ const visited = await super.visitArrowFunction(arrow, ctx) as JS.ArrowFunction;
310
+ if (!this.decisions.hooks.has(arrow.id) || visited.lambda.body.kind !== J.Kind.Block) return visited;
311
+ const body = await this.withHook(visited.lambda.body as J.Block, this.decisions.hooks.get(arrow.id));
312
+ return {...visited, lambda: {...visited.lambda, body}} as JS.ArrowFunction;
313
+ }
314
+
315
+ private async call(key: string, values: Finding["values"], node: J, ctx: ExecutionContext): Promise<J> {
316
+ const object = values?.length ? `, {${values.map(({name, expression}) => name === expression ? name : `${name}: ${expression}`).join(", ")}}` : "";
317
+ return await template`t(${raw(JSON.stringify(key))}${raw(object)})`.apply(node, this.cursor) as J;
318
+ }
319
+
320
+ private readonly hookStatements = new Map<string, J.RightPadded<J>>();
321
+
322
+ /** The block with `const {t} = useTranslation()` as its first statement, indented as the statement it goes before. */
323
+ private async withHook(body: J.Block, namespace: string | undefined): Promise<J.Block> {
324
+ const argument = namespace === undefined ? "" : JSON.stringify(namespace);
325
+ const code = `const {t} = ${this.hookName}(${argument});`;
326
+ let statement = this.hookStatements.get(code);
327
+ if (!statement) {
328
+ const parsed = await new JavaScriptParser().parseOne({text: `function f() {\n ${code}\n}`, sourcePath: "hook.ts"}) as JS.CompilationUnit;
329
+ statement = ((parsed.statements[0].element as J.MethodDeclaration).body!).statements[0] as J.RightPadded<J>;
330
+ this.hookStatements.set(code, statement);
331
+ }
332
+ const first = body.statements[0]?.element;
333
+ // Only the indentation: the first statement keeps its own comments
334
+ const prefix = first ? {...first.prefix, comments: []} : statement.element.prefix;
335
+ return {...body, statements: [{...statement, element: {...statement.element, prefix, id: randomId()}}, ...body.statements]};
336
+ }
337
+ }
338
+
339
+ function embedded(expression: J): JSX.EmbeddedExpression {
340
+ return {
341
+ kind: JS.Kind.JsxEmbeddedExpression, id: randomId(), prefix: emptySpace, markers: emptyMarkers,
342
+ expression: {kind: J.Kind.RightPadded, element: {...expression, prefix: emptySpace} as J, after: emptySpace, markers: emptyMarkers}
343
+ } as JSX.EmbeddedExpression;
344
+ }
345
+
346
+ function textLiteral(text: string): J.Literal {
347
+ return {kind: J.Kind.Literal, id: randomId(), prefix: emptySpace, markers: emptyMarkers, value: text, valueSource: text, type: Type.Primitive.String} as J.Literal;
348
+ }
349
+
350
+ /** The function component around the cursor: the nearest enclosing function named in PascalCase, with a block body. */
351
+ function enclosingComponent(cursor: Cursor): Cursor | undefined {
352
+ for (let c: Cursor | undefined = cursor.parentTree(); c; c = c.parentTree()) {
353
+ const node = c.value as J;
354
+ if (!FUNCTION_KINDS.has(node.kind) || node.kind === J.Kind.Lambda) continue;
355
+ const name = functionName(c);
356
+ if (!name || !/^[A-Z]/.test(name)) continue;
357
+ // Hooks cannot run in an async component, such as a server component
358
+ if ((node as J.MethodDeclaration | JS.ArrowFunction).modifiers.some(modifier => modifier.keyword === "async")) return undefined;
359
+ const body = node.kind === J.Kind.MethodDeclaration ? (node as J.MethodDeclaration).body : (node as JS.ArrowFunction).lambda.body;
360
+ return body?.kind === J.Kind.Block ? c : undefined;
361
+ }
362
+ return undefined;
363
+ }
364
+
365
+ function bodyOf(component: J): J.Block | undefined {
366
+ const body = component.kind === J.Kind.MethodDeclaration ? (component as J.MethodDeclaration).body : (component as JS.ArrowFunction).lambda.body;
367
+ return body?.kind === J.Kind.Block ? body as J.Block : undefined;
368
+ }
369
+
370
+ /**
371
+ * The namespace of a `const {t} = useTranslation(...)` among the component's own statements, if it has one, or
372
+ * `"unsupported"` where it reads several namespaces or takes options such as `keyPrefix`, which change where keys go.
373
+ */
374
+ function existingHook(component: J): {namespace?: string} | "unsupported" | undefined {
375
+ const body = bodyOf(component);
376
+ for (const {element} of body?.statements ?? []) {
377
+ if (element.kind !== J.Kind.VariableDeclarations) continue;
378
+ for (const {element: variable} of (element as J.VariableDeclarations).variables) {
379
+ const call = variable.initializer?.element as J.MethodInvocation | undefined;
380
+ if (call?.kind !== J.Kind.MethodInvocation || call.name.simpleName !== "useTranslation" || !bindingNames(variable.name).some(binding => binding.name === "t")) continue;
381
+ const args = call.arguments.elements.map(({element}) => element).filter(argument => argument.kind !== J.Kind.Empty);
382
+ if (args.length > 1 || args.length === 1 && stringValue(args[0]) === undefined) return "unsupported";
383
+ return {namespace: args.length ? stringValue(args[0]) : undefined};
384
+ }
385
+ }
386
+ return undefined;
387
+ }
388
+
389
+ /** A template literal's text with `{{name}}` placeholders, where every interpolation is a name or a property chain. */
390
+ function templateText(template: JS.TemplateExpression): {text: string, values: {name: string, expression: string}[]} | undefined {
391
+ let text = stringValue(template.head) ?? "";
392
+ const values: {name: string, expression: string}[] = [];
393
+ for (const {element: span} of template.spans) {
394
+ const expression = isIdentifier(span.expression) ? span.expression.simpleName :
395
+ span.expression.kind === J.Kind.FieldAccess ? propertyPath(span.expression as J.FieldAccess) : undefined;
396
+ if (!expression) return undefined;
397
+ let name = expression.split(".").pop()!;
398
+ const taken = values.find(value => value.name === name);
399
+ if (taken && taken.expression !== expression) name = `${name}${values.length}`;
400
+ if (!values.some(value => value.name === name)) values.push({name, expression});
401
+ text += `{{${name}}}${stringValue(span.tail) ?? ""}`;
402
+ }
403
+ return {text: text.trim(), values};
404
+ }
405
+
406
+ /** Every string value of a JSON document by its dotted key, recording every member's key in `taken`. */
407
+ function flatten(value: Json, prefix = "", entries = new Map<string, string>(), taken = new Set<string>()): Map<string, string> {
408
+ if (value.kind === Json.Kind.Object) {
409
+ for (const {element} of (value as Json.Object).members) {
410
+ if (element.kind !== Json.Kind.Member) continue;
411
+ const member = (element as Json.Member).key.element;
412
+ const name = member.kind === Json.Kind.Literal ? String((member as Json.Literal).value) : (member as Json.Identifier).name;
413
+ const key = prefix ? `${prefix}.${name}` : name;
414
+ taken.add(key);
415
+ flatten((element as Json.Member).value, key, entries, taken);
416
+ }
417
+ } else if (value.kind === Json.Kind.Literal && typeof (value as Json.Literal).value === "string") {
418
+ entries.set(prefix, (value as Json.Literal).value as string);
419
+ }
420
+ return entries;
421
+ }
422
+
423
+ const ENTITIES: Record<string, string> = {
424
+ amp: "&", lt: "<", gt: ">", quot: "\"", apos: "'", nbsp: " ", copy: "©", reg: "®", trade: "™", hellip: "…",
425
+ mdash: "—", ndash: "–", lsquo: "‘", rsquo: "’", ldquo: "“", rdquo: "”", middot: "·", bull: "•"
426
+ };
427
+
428
+ /** JSX text with its HTML entities decoded, as React renders them; undefined for an entity this does not know. */
429
+ function decodeEntities(text: string): string | undefined {
430
+ let unknown = false;
431
+ const decoded = text.replace(/&(#\d+|#x[\da-f]+|[a-z][a-z\d]*);/gi, (entity, name: string) => {
432
+ if (name.startsWith("#")) {
433
+ const code = /^#x/i.test(name) ? parseInt(name.slice(2), 16) : parseInt(name.slice(1), 10);
434
+ if (code <= 0x10ffff) return String.fromCodePoint(code);
435
+ unknown = true;
436
+ return entity;
437
+ }
438
+ if (ENTITIES[name] === undefined) unknown = true;
439
+ return ENTITIES[name] ?? entity;
440
+ });
441
+ return unknown ? undefined : decoded;
442
+ }
package/src/index.ts CHANGED
@@ -75,6 +75,8 @@ import {FindDeprecatedLifecycles} from './search/find-deprecated-lifecycles';
75
75
  import {FindFunctionComponentDefaultProps} from './search/find-function-component-default-props';
76
76
  import {FindEffectsWithoutCleanup} from './search/find-effects-without-cleanup';
77
77
  import {FindMissingUseClientDirective} from './search/find-missing-use-client-directive';
78
+ import {FindHardCodedStrings} from './search/find-hard-coded-strings';
79
+ import {TranslateHardCodedStrings} from './i18n/translate-hard-coded-strings';
78
80
 
79
81
  // General
80
82
  import {SimplifyReactImports} from './simplify-react-imports';
@@ -84,6 +86,9 @@ import {ChangeComponentPropValue} from './migration/change-component-prop-value'
84
86
  // CRA to Vite
85
87
  import {CraToVite, craToViteRecipes} from './migration/cra-to-vite';
86
88
 
89
+ // Material UI
90
+ import * as mui from './mui';
91
+
87
92
  // Categories
88
93
  const React: CategoryDescriptor[] = [...JavaScript, {displayName: "React"}];
89
94
  const ReactMigrate: CategoryDescriptor[] = [...React, {displayName: "Migrate"}];
@@ -96,6 +101,8 @@ const ReactRefactoring: CategoryDescriptor[] = [...React, {displayName: "Refacto
96
101
  const CraToViteMigrate: CategoryDescriptor[] = [...ReactMigrate, {displayName: "Create React App to Vite"}];
97
102
  const ReactNative: CategoryDescriptor[] = [...React, {displayName: "React Native"}];
98
103
  const ReactSearch: CategoryDescriptor[] = [...React, {displayName: "Search"}];
104
+ const MaterialUi: CategoryDescriptor[] = [...React, {displayName: "Material UI"}];
105
+ const ReactI18n: CategoryDescriptor[] = [...React, {displayName: "Internationalization"}];
99
106
  const JavaScriptCleanup: CategoryDescriptor[] = [...JavaScript, {displayName: "Cleanup"}];
100
107
 
101
108
  export async function activate(marketplace: RecipeMarketplace) {
@@ -142,6 +149,9 @@ export async function activate(marketplace: RecipeMarketplace) {
142
149
  await marketplace.install(ReactToReactDom, React16);
143
150
  await marketplace.install(ReplaceCreateFactory, React16);
144
151
 
152
+ // Material UI: the primitives that the YAML recipes of mui-migrate.yml are composed from
153
+ for (const recipe of Object.values(mui)) await marketplace.install(recipe, MaterialUi);
154
+
145
155
  // Refactoring
146
156
  await marketplace.install(CreateClassToES6, ReactRefactoring);
147
157
  await marketplace.install(ClassToFunctional, ReactRefactoring);
@@ -173,6 +183,8 @@ export async function activate(marketplace: RecipeMarketplace) {
173
183
  await marketplace.install(FindFunctionComponentDefaultProps, ReactSearch);
174
184
  await marketplace.install(FindEffectsWithoutCleanup, ReactSearch);
175
185
  await marketplace.install(FindMissingUseClientDirective, ReactSearch);
186
+ await marketplace.install(FindHardCodedStrings, ReactSearch);
187
+ await marketplace.install(TranslateHardCodedStrings, ReactI18n);
176
188
 
177
189
  // CRA to Vite
178
190
  await marketplace.install(CraToVite, ReactMigrate);
@@ -250,10 +262,15 @@ export {FindDeprecatedLifecycles} from './search/find-deprecated-lifecycles';
250
262
  export {FindFunctionComponentDefaultProps} from './search/find-function-component-default-props';
251
263
  export {FindEffectsWithoutCleanup} from './search/find-effects-without-cleanup';
252
264
  export {FindMissingUseClientDirective} from './search/find-missing-use-client-directive';
265
+ export {FindHardCodedStrings} from './search/find-hard-coded-strings';
266
+ export {TranslateHardCodedStrings} from './i18n/translate-hard-coded-strings';
253
267
 
254
268
  // CRA to Vite
255
269
  export * from './migration/cra-to-vite';
256
270
 
271
+ // Material UI
272
+ export * from './mui';
273
+
257
274
  // General
258
275
  export {SimplifyReactImports} from './simplify-react-imports';
259
276
  export {SimplifyObjectPatternProperty} from './simplify-object-pattern-property';
@@ -0,0 +1,43 @@
1
+ import {ExecutionContext, Recipe, TreeVisitor, check, not} from "@openrewrite/rewrite";
2
+ import {JavaScriptVisitor, JS, isVendoredOrBundled, maybeAddImport, raw, template} from "@openrewrite/rewrite/javascript";
3
+ import {J} from "@openrewrite/rewrite/java";
4
+ import {importBindings} from "../util/module-imports";
5
+ import {MUI_PACKAGES} from "./mui-components";
6
+
7
+ /**
8
+ * Wraps the options of `createTheme` and `createMuiTheme` in `adaptV4Theme()`, which turns a v4 theme into a v5 one.
9
+ *
10
+ * Before: `createMuiTheme({ palette: { type: 'dark' } })`
11
+ * After: `createMuiTheme(adaptV4Theme({ palette: { type: 'dark' } }))`
12
+ *
13
+ * @see https://mui.com/material-ui/migration/v5-component-changes/#theme
14
+ */
15
+ export class AdaptV4Theme extends Recipe {
16
+ readonly name = "org.openrewrite.react.mui.adapt-v4-theme";
17
+ readonly displayName: string = "Wrap the theme options in `adaptV4Theme()`";
18
+ readonly description: string = "Wraps the options passed to `createTheme` or `createMuiTheme` in `adaptV4Theme()` and imports it, so a v4 theme keeps working on v5.";
19
+
20
+ async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
21
+ return check(not(isVendoredOrBundled()), new class extends JavaScriptVisitor<ExecutionContext> {
22
+ private themes = new Map<string, string>();
23
+
24
+ override async visitJsCompilationUnit(cu: JS.CompilationUnit, ctx: ExecutionContext): Promise<J | undefined> {
25
+ this.themes = new Map(importBindings(cu).filter(b => MUI_PACKAGES.test(b.module) && ["createTheme", "createMuiTheme"].includes(b.name))
26
+ .map(b => [b.local, b.module]));
27
+ return this.themes.size ? super.visitJsCompilationUnit(cu, ctx) : cu;
28
+ }
29
+
30
+ override async visitMethodInvocation(invocation: J.MethodInvocation, ctx: ExecutionContext): Promise<J | undefined> {
31
+ const visited = await super.visitMethodInvocation(invocation, ctx) as J.MethodInvocation;
32
+ const module = this.themes.get(visited.name.simpleName);
33
+ const [options] = visited.arguments.elements;
34
+ if (visited.select || !module || !options || visited.arguments.elements.length !== 1) return visited;
35
+ const argument = options.element;
36
+ if (argument.kind === J.Kind.MethodInvocation && (argument as J.MethodInvocation).name.simpleName === "adaptV4Theme") return visited;
37
+ maybeAddImport(this, {module: module.replace(/\/styles\/.*/, "/styles"), member: "adaptV4Theme", onlyIfReferenced: false});
38
+ const wrapped = await template`${raw(visited.name.simpleName)}(${raw("adaptV4Theme")}(${argument}))`.apply(visited, this.cursor);
39
+ return wrapped ? {...wrapped, prefix: visited.prefix} as J : visited;
40
+ }
41
+ }());
42
+ }
43
+ }
@@ -0,0 +1,43 @@
1
+ import {ExecutionContext, Option, Recipe, TreeVisitor} from "@openrewrite/rewrite";
2
+ import {appendAttribute, findAttribute, hasSpread, newAttribute} from "./jsx-attributes";
3
+ import {muiTagEditor} from "./mui-tag-visitor";
4
+
5
+ /**
6
+ * Adds a prop to a Material UI component that does not set it, for keeping a default that changed.
7
+ *
8
+ * Before: `<IconButton />`
9
+ * After: `<IconButton size="large" />`
10
+ *
11
+ * A tag with a spread attribute is left alone, since the spread may already set the prop.
12
+ *
13
+ * @see https://mui.com/material-ui/migration/v5-component-changes/#iconbutton
14
+ */
15
+ export class AddComponentProp extends Recipe {
16
+ readonly name = "org.openrewrite.react.mui.add-component-prop";
17
+ readonly displayName: string = "Add a Material UI component prop";
18
+ readonly description: string = "Adds a prop to a Material UI component that does not set it, keeping a default that changed. Tags with a spread attribute are left alone.";
19
+
20
+ @Option({displayName: "Component name", description: "The Material UI component, such as `IconButton`.", example: "IconButton"})
21
+ componentName!: string;
22
+
23
+ @Option({displayName: "Prop name", description: "The prop to add.", example: "size"})
24
+ propName!: string;
25
+
26
+ @Option({displayName: "Prop value", description: "The JSX source of the value, with its quotes or braces.", example: "\"large\""})
27
+ propValue!: string;
28
+
29
+ @Option({displayName: "Package name", description: "A package that re-exports Material UI, when the components are not imported from Material UI itself.", example: "@org/ui", required: false})
30
+ packageName?: string;
31
+
32
+ constructor(options?: { componentName?: string; propName?: string; propValue?: string; packageName?: string }) {
33
+ super(options);
34
+ }
35
+
36
+ async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
37
+ const {propName, propValue} = this;
38
+ return muiTagEditor(this.componentName, this.packageName, async (tag, cursor) => {
39
+ if (findAttribute(tag, propName) || hasSpread(tag)) return tag;
40
+ return appendAttribute(tag, await newAttribute(cursor, tag, propName, propValue));
41
+ });
42
+ }
43
+ }
@@ -0,0 +1,48 @@
1
+ import {ExecutionContext, Recipe, TreeVisitor, check, not} from "@openrewrite/rewrite";
2
+ import {JavaScriptVisitor, JS, isVendoredOrBundled} from "@openrewrite/rewrite/javascript";
3
+ import {J} from "@openrewrite/rewrite/java";
4
+ import {importBindings} from "../util/module-imports";
5
+ import {appendProperty, findProperty, isObjectLiteral, newPropertyFromSource} from "./jsx-attributes";
6
+
7
+ /**
8
+ * Adds `prepend: true` to the options of Emotion's `createCache`, so Emotion's styles come before other CSS and can be
9
+ * overridden, as they could in v4.
10
+ *
11
+ * Before: `createCache({ key: 'css' })`
12
+ * After: `createCache({ key: 'css', prepend: true })`
13
+ *
14
+ * @see https://mui.com/material-ui/migration/v5-style-changes/#if-you-are-using-emotion
15
+ */
16
+ export class AddEmotionPrepend extends Recipe {
17
+ readonly name = "org.openrewrite.react.mui.add-emotion-prepend";
18
+ readonly displayName: string = "Add `prepend: true` to Emotion's `createCache`";
19
+ readonly description: string = "Adds `prepend: true` to the options object of Emotion's `createCache`, and turns `prepend: false` into `true`.";
20
+
21
+ async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
22
+ return check(not(isVendoredOrBundled()), new class extends JavaScriptVisitor<ExecutionContext> {
23
+ private names = new Set<string>();
24
+
25
+ override async visitJsCompilationUnit(cu: JS.CompilationUnit, ctx: ExecutionContext): Promise<J | undefined> {
26
+ this.names = new Set(importBindings(cu).filter(b => b.module === "@emotion/cache" && b.name === "default").map(b => b.local));
27
+ return this.names.size ? super.visitJsCompilationUnit(cu, ctx) : cu;
28
+ }
29
+
30
+ override async visitMethodInvocation(invocation: J.MethodInvocation, ctx: ExecutionContext): Promise<J | undefined> {
31
+ const visited = await super.visitMethodInvocation(invocation, ctx) as J.MethodInvocation;
32
+ const options = visited.arguments.elements[0]?.element;
33
+ if (visited.select || !this.names.has(visited.name.simpleName) || !isObjectLiteral(options)) return visited;
34
+ const existing = findProperty(options, "prepend");
35
+ let updated: J.NewClass;
36
+ if (!existing) {
37
+ updated = appendProperty(options, await newPropertyFromSource(this.cursor, visited, "prepend", "true"));
38
+ } else {
39
+ const value = existing.initializer;
40
+ if (value?.kind !== J.Kind.Literal || (value as J.Literal).value !== false) return visited;
41
+ updated = {...options, body: {...options.body!, statements: options.body!.statements.map(s => s.element === existing
42
+ ? {...s, element: {...existing, initializer: {...value, value: true, valueSource: "true"}}} : s)}} as J.NewClass;
43
+ }
44
+ return {...visited, arguments: {...visited.arguments, elements: [{...visited.arguments.elements[0], element: updated}, ...visited.arguments.elements.slice(1)]}} as J.MethodInvocation;
45
+ }
46
+ }());
47
+ }
48
+ }