@openrewrite/recipes-react 0.20.0 → 0.21.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 +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +10 -1
- package/dist/index.js.map +1 -1
- package/dist/search/find-enzyme-usage.d.ts +4 -0
- package/dist/search/find-enzyme-usage.d.ts.map +1 -1
- package/dist/search/find-enzyme-usage.js +30 -3
- 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-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 +10 -0
- package/dist/testing/enzyme-render-blockers.d.ts.map +1 -0
- package/dist/testing/enzyme-render-blockers.js +119 -0
- package/dist/testing/enzyme-render-blockers.js.map +1 -0
- package/dist/testing/enzyme-to-react-testing-library.d.ts +9 -2
- package/dist/testing/enzyme-to-react-testing-library.d.ts.map +1 -1
- package/dist/testing/enzyme-to-react-testing-library.js +80 -17
- package/dist/testing/enzyme-to-react-testing-library.js.map +1 -1
- package/dist/testing/enzyme-usage.d.ts +2 -0
- package/dist/testing/enzyme-usage.d.ts.map +1 -1
- package/dist/testing/enzyme-usage.js +29 -3
- package/dist/testing/enzyme-usage.js.map +1 -1
- package/dist/testing/enzyme-wrapper-scope.d.ts +5 -1
- package/dist/testing/enzyme-wrapper-scope.d.ts.map +1 -1
- package/dist/testing/enzyme-wrapper-scope.js +12 -3
- 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 +5 -4
- package/dist/zustand/redux-stores.d.ts.map +1 -1
- package/dist/zustand/redux-stores.js +8 -5
- 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 +137 -42
- package/dist/zustand/redux-to-zustand.js.map +1 -1
- package/dist/zustand/zustand-plan.d.ts +7 -5
- package/dist/zustand/zustand-plan.d.ts.map +1 -1
- package/dist/zustand/zustand-plan.js +87 -33
- 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 +7 -0
- package/src/search/find-enzyme-usage.ts +30 -6
- 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-portals.ts +4 -44
- package/src/testing/enzyme-render-blockers.ts +113 -0
- package/src/testing/enzyme-to-react-testing-library.ts +90 -18
- package/src/testing/enzyme-usage.ts +35 -2
- package/src/testing/enzyme-wrapper-scope.ts +13 -2
- 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 +12 -7
- package/src/zustand/redux-to-zustand.ts +168 -48
- package/src/zustand/zustand-plan.ts +98 -32
|
@@ -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';
|
|
@@ -96,6 +98,7 @@ const ReactRefactoring: CategoryDescriptor[] = [...React, {displayName: "Refacto
|
|
|
96
98
|
const CraToViteMigrate: CategoryDescriptor[] = [...ReactMigrate, {displayName: "Create React App to Vite"}];
|
|
97
99
|
const ReactNative: CategoryDescriptor[] = [...React, {displayName: "React Native"}];
|
|
98
100
|
const ReactSearch: CategoryDescriptor[] = [...React, {displayName: "Search"}];
|
|
101
|
+
const ReactI18n: CategoryDescriptor[] = [...React, {displayName: "Internationalization"}];
|
|
99
102
|
const JavaScriptCleanup: CategoryDescriptor[] = [...JavaScript, {displayName: "Cleanup"}];
|
|
100
103
|
|
|
101
104
|
export async function activate(marketplace: RecipeMarketplace) {
|
|
@@ -173,6 +176,8 @@ export async function activate(marketplace: RecipeMarketplace) {
|
|
|
173
176
|
await marketplace.install(FindFunctionComponentDefaultProps, ReactSearch);
|
|
174
177
|
await marketplace.install(FindEffectsWithoutCleanup, ReactSearch);
|
|
175
178
|
await marketplace.install(FindMissingUseClientDirective, ReactSearch);
|
|
179
|
+
await marketplace.install(FindHardCodedStrings, ReactSearch);
|
|
180
|
+
await marketplace.install(TranslateHardCodedStrings, ReactI18n);
|
|
176
181
|
|
|
177
182
|
// CRA to Vite
|
|
178
183
|
await marketplace.install(CraToVite, ReactMigrate);
|
|
@@ -250,6 +255,8 @@ export {FindDeprecatedLifecycles} from './search/find-deprecated-lifecycles';
|
|
|
250
255
|
export {FindFunctionComponentDefaultProps} from './search/find-function-component-default-props';
|
|
251
256
|
export {FindEffectsWithoutCleanup} from './search/find-effects-without-cleanup';
|
|
252
257
|
export {FindMissingUseClientDirective} from './search/find-missing-use-client-directive';
|
|
258
|
+
export {FindHardCodedStrings} from './search/find-hard-coded-strings';
|
|
259
|
+
export {TranslateHardCodedStrings} from './i18n/translate-hard-coded-strings';
|
|
253
260
|
|
|
254
261
|
// CRA to Vite
|
|
255
262
|
export * from './migration/cra-to-vite';
|
|
@@ -1,10 +1,32 @@
|
|
|
1
1
|
import {and, check, not, or, DataTable, ExecutionContext, foundSearchResult, Recipe, RecipeRef, TreeVisitor} from "@openrewrite/rewrite";
|
|
2
2
|
import {isObjectLiteral, isVendoredOrBundled, JavaScriptVisitor, JS, usesMethod, usesType} from "@openrewrite/rewrite/javascript";
|
|
3
3
|
import {isIdentifier, J, Type, TypedTree} from "@openrewrite/rewrite/java";
|
|
4
|
-
import {enclosingScope, ENZYME_GUIDE, ENZYME_USAGE_TABLE, enzymeMethod, enzymeModule, enzymeWrapper, EnzymeUsageRow, EventKind, migrationReason, SelectorKind} from "../testing/enzyme-usage";
|
|
4
|
+
import {enclosingScope, ENZYME_GUIDE, ENZYME_USAGE_TABLE, enzymeMethod, enzymeModule, enzymeWrapper, EnzymeUsageRow, EventKind, FILE_BLOCKER, migrationReason, RENDER_BLOCKERS, SelectorKind} from "../testing/enzyme-usage";
|
|
5
5
|
import {domSelector, objectProperties, simulatedEvent} from "../testing/enzyme-wrapper-scope";
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
const LENGTH_ACTION = "Use the `length` of the `querySelectorAll` or `getAllBy*` result. For a component selector, count the elements the component renders.";
|
|
8
|
+
|
|
9
|
+
/** What to do with a wrapper that leaves the reads the converter follows, by where it goes. */
|
|
10
|
+
function escapeAction(identifier: J.Identifier, parent: J | undefined): string {
|
|
11
|
+
const callee = parent?.kind === J.Kind.MethodInvocation ? (parent as J.MethodInvocation).name.simpleName :
|
|
12
|
+
parent?.kind === JS.Kind.FunctionCall ? undefined : null;
|
|
13
|
+
if (callee === "expect") {
|
|
14
|
+
return "`expect(wrapper)` asserts on the Enzyme wrapper itself. Assert on what it renders instead, " +
|
|
15
|
+
"such as `expect(container).toMatchSnapshot()` or `expect(container.querySelector(selector)).not.toBeNull()`.";
|
|
16
|
+
}
|
|
17
|
+
if (callee !== null) {
|
|
18
|
+
return "The wrapper is passed to a function. Change the function to take RTL's render result or the element it queries, " +
|
|
19
|
+
"and convert the reads inside it with this test's.";
|
|
20
|
+
}
|
|
21
|
+
if (parent?.kind === J.Kind.Return) return "A function returns the wrapper. Return RTL's render result instead, and convert its callers' reads with it.";
|
|
22
|
+
if (parent?.kind === J.Kind.NamedVariable && (parent as J.VariableDeclarations.NamedVariable).initializer?.element === identifier ||
|
|
23
|
+
parent?.kind === J.Kind.Assignment && (parent as J.Assignment).assignment.element === identifier) {
|
|
24
|
+
return "The wrapper is copied to another name. Read it through one name, so the recipe follows every read of it.";
|
|
25
|
+
}
|
|
26
|
+
return "Trace this wrapper alias, argument, assignment, or return value before migrating its connected scope.";
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function eventKind(api: string, [name, mock]: J[]): EventKind | undefined {
|
|
8
30
|
if (api !== "simulate" || name?.kind !== J.Kind.Literal || typeof (name as J.Literal).value !== "string") return undefined;
|
|
9
31
|
const event = simulatedEvent((name as J.Literal).value as string);
|
|
10
32
|
if (!event) return "other";
|
|
@@ -17,7 +39,7 @@ function eventKind(api: string, [name, mock]: J[]): EventKind | undefined {
|
|
|
17
39
|
return ["mouseEnter", "mouseLeave", "mouseOver", "mouseOut"].includes(event) ? "hover" : "event";
|
|
18
40
|
}
|
|
19
41
|
|
|
20
|
-
function selectorKind(api: string, selector: J | undefined): SelectorKind | undefined {
|
|
42
|
+
export function selectorKind(api: string, selector: J | undefined): SelectorKind | undefined {
|
|
21
43
|
if (api === "findWhere" || api === "filterWhere") return "predicate";
|
|
22
44
|
if (api !== "find" || !selector) return undefined;
|
|
23
45
|
if (selector.kind === J.Kind.Literal) {
|
|
@@ -100,6 +122,9 @@ export class FindEnzymeUsage extends Recipe {
|
|
|
100
122
|
const api = enzymeMethod(method);
|
|
101
123
|
if (!api) return result;
|
|
102
124
|
const {reason, suggestedAction} = migrationReason(api, selectorKind(api, args[0]), eventKind(api, args));
|
|
125
|
+
// The converter, run before this, says what kept a render it left on Enzyme
|
|
126
|
+
const blocker = reason === "RENDER_REVIEW" || reason === "SHALLOW_RENDERING" ? (RENDER_BLOCKERS.get(this.sourcePath)?.get(method.id) ?? RENDER_BLOCKERS.get(this.sourcePath)?.get(FILE_BLOCKER)) : undefined;
|
|
127
|
+
if (blocker) return this.report(result, api, reason, blocker, ctx);
|
|
103
128
|
return this.report(result, api, reason, suggestedAction, ctx);
|
|
104
129
|
}
|
|
105
130
|
|
|
@@ -119,7 +144,7 @@ export class FindEnzymeUsage extends Recipe {
|
|
|
119
144
|
const result = await super.visitFieldAccess(field, ctx) as J.FieldAccess;
|
|
120
145
|
if (!enzymeWrapper(TypedTree.getType(field.target))) return result;
|
|
121
146
|
const api = field.name.element.simpleName;
|
|
122
|
-
return this.report(result, api, "WRAPPER_FIELD",
|
|
147
|
+
return this.report(result, api, "WRAPPER_FIELD", api === "length" ? LENGTH_ACTION :
|
|
123
148
|
"Preserve assertion cardinality and wrapper semantics when replacing this Enzyme field.", ctx);
|
|
124
149
|
}
|
|
125
150
|
|
|
@@ -132,8 +157,7 @@ export class FindEnzymeUsage extends Recipe {
|
|
|
132
157
|
if (parent?.kind === J.Kind.MethodInvocation &&
|
|
133
158
|
(parent as J.MethodInvocation).select?.element === identifier) return result;
|
|
134
159
|
if (parent?.kind === J.Kind.FieldAccess && (parent as J.FieldAccess).target === identifier) return result;
|
|
135
|
-
return this.report(result, identifier.simpleName, "WRAPPER_ESCAPE",
|
|
136
|
-
"Trace this wrapper alias, argument, assignment, or return value before migrating its connected scope.", ctx);
|
|
160
|
+
return this.report(result, identifier.simpleName, "WRAPPER_ESCAPE", escapeAction(identifier, parent), ctx);
|
|
137
161
|
}
|
|
138
162
|
|
|
139
163
|
private report<T extends J>(node: T, api: string, reason: string, suggestedAction: string, ctx: ExecutionContext): T {
|