-
Notifications
You must be signed in to change notification settings - Fork 1
/
extract-translations-transform.ts
488 lines (428 loc) · 13.2 KB
/
extract-translations-transform.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
/*
Collects hardcoded strings and wraps them in translation hook
Useful resources:
1. https://ts-ast-viewer.com/
2. https://astexplorer.net/
*/
import {
Transform,
ASTPath,
JSCodeshift,
Collection,
} from "jscodeshift/src/core";
import fs from "fs";
import stringify from "json-stable-stringify";
import _ from "lodash";
import slugify from "slugify";
import { namedTypes } from "ast-types";
const CURRENCIES_SYMBOLS = ["$", "€", "£", "¥", "₽", "₺", "₹", "₩", "₪", "₴"];
const NUMBERS_STRING = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
const NUMBERS = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
const SPECIAL_CHARACTERS = [
"©",
"!",
"?",
".",
",",
":",
";",
"%",
"#",
"@",
"^",
"&",
"*",
"|",
"\\",
"/",
"<",
">",
"~",
"`",
"'",
'"',
" ",
"",
"-",
"_",
"=",
"+",
"(",
")",
"[",
"]",
"{",
"}",
"·",
];
/**
* If JSXText is any of the following, it won't be translated
*/
const TRANSLATION_BLACKLIST = [
...NUMBERS,
...NUMBERS_STRING,
...SPECIAL_CHARACTERS,
...CURRENCIES_SYMBOLS,
];
const isUpperCase = (s: string) => /^[A-Z].*$/.test(s);
const readTranslations = (path: string, translationRoot?: string) => {
try {
const data = fs.readFileSync(path, "utf8");
const parsedTranslations = JSON.parse(data);
return translationRoot
? parsedTranslations[translationRoot]
: parsedTranslations;
} catch (e) {
// does not exist
return {};
}
};
const writeTranslations = (
path: string,
translations: Record<string, any>,
translationRoot?: string
) => {
if (translationRoot) {
translations = { [translationRoot]: translations };
}
const result = stringify(translations, { space: 2 });
fs.writeFileSync(path, result);
};
const addTranslation = (
translations: Record<string, any>,
component: string,
key: string,
text: string
) => {
translations[component] = {
...translations[component],
[key]: text,
};
};
const getFunctionName = (j: JSCodeshift, fd: ASTPath) => {
if (j.ArrowFunctionExpression.check(fd.value))
return fd.parentPath?.value?.id?.name;
if (j.FunctionDeclaration.check(fd.value)) return fd.value?.id?.name;
return "UnknownFunction";
};
const getImportStatements = (
j: JSCodeshift,
root: Collection<any>,
importName: string
) => {
return root.find(j.ImportDeclaration, { source: { value: importName } });
};
const getClosestFunctionAST = (j: JSCodeshift, path: ASTPath) => {
if (!path) return null;
if (
j.FunctionDeclaration.check(path.value) ||
j.ArrowFunctionExpression.check(path.value)
)
return path;
return getClosestFunctionAST(j, path.parentPath);
};
const createUseTranslationImport = (j: JSCodeshift, importPackage: string) =>
j.importDeclaration(
[j.importSpecifier(j.identifier("useTranslation"))],
j.stringLiteral(importPackage)
);
const createTranslationHook = (j: JSCodeshift) =>
j.variableDeclaration.from({
kind: "const",
declarations: [
j.variableDeclarator.from({
id: j.objectPattern([
j.objectProperty.from({
key: j.identifier("t"),
value: j.identifier("t"),
shorthand: true,
}),
]),
init: j.callExpression.from({
callee: j.identifier("useTranslation"),
arguments: [],
}),
}),
],
});
const TRANSLATION_KEY_MAX_LENGTH = 40;
const createTranslationKey = (
text: string,
keyMaxLength: number = TRANSLATION_KEY_MAX_LENGTH
) => {
return slugify(text, {
remove: /[*+~.()'"!:@]/g,
lower: true,
strict: true,
trim: true,
}).slice(0, keyMaxLength);
};
const addTranslationPackageImport = (
j: JSCodeshift,
root: Collection<any>,
importPackage: string
) => {
const newUseTranslationImport = createUseTranslationImport(j, importPackage);
root.find(j.ImportDeclaration).at(0).insertBefore(newUseTranslationImport);
};
const findCallExpressions = (
j: JSCodeshift,
reactComponent: ASTPath<namedTypes.FunctionDeclaration>,
callExpressionName: string
) => {
return j(reactComponent)
.find(j.CallExpression)
.filter((path) => {
if (path.value.callee.type !== "Identifier") return false;
if (path.value.callee.name !== callExpressionName) return false;
return true;
});
};
const sanitizeText = (text: string) => {
return text.replace(/\s+/g, " ").trim();
};
const TEMPLATE_LITERAL_BLACKLIST = ["className", "href", "src", "key"];
/**
* Translates template literals like `Hello ${name}` used as children of JSX elements
* @param j
* @param root
* @param translations
* @param importPackage
*/
const translateTemplateLiterals = (
j: JSCodeshift,
root: Collection<any>,
translations: Record<string, any>,
importPackage: string
) => {
root
.find(j.TemplateLiteral)
.filter((path) => {
// if the template literal is inside a JSX attribute, check if it's not blacklisted
// for example <div className={`text-{color}`}"></div>
if (
j.JSXAttribute.check(path.parentPath.parentPath.value) &&
TEMPLATE_LITERAL_BLACKLIST.includes(
path.parentPath.parentPath.value.name.name
)
)
return false;
if (path.parentPath.value.type === "TaggedTemplateExpression")
return false;
return true;
})
.replaceWith((path) => {
// get the top level react component where the hardcoded text is
const functionAST = getClosestFunctionAST(j, path);
if (!functionAST) {
return path; // technically, should not happen as we are filtering for JSXAttribute, but just in case
}
const componentName = _.lowerFirst(getFunctionName(j, functionAST));
let text = "";
const expressions = j.objectExpression([]);
let i = 0;
for (; i < path.value.expressions.length; ++i) {
const expression = path.value.expressions[i];
const expressionKey = _.camelCase(j(expression).toSource());
text += `${path.value.quasis[i].value.cooked}{{${expressionKey}}}`;
expressions.properties.push(
j.objectProperty.from({
key: j.identifier(expressionKey),
value: expression,
shorthand:
expression.type === "Identifier" &&
expression.name === expressionKey,
})
);
}
text += path.value.quasis[i].value.cooked;
const value = sanitizeText(text);
const key = createTranslationKey(value);
addTranslation(translations, componentName, key, value);
// import translation package provided via `importPackage` option if needed
const translationPackageImports = getImportStatements(
j,
root,
importPackage
);
if (translationPackageImports.length === 0) {
addTranslationPackageImport(j, root, importPackage);
}
// add translation hook to the top of the component, if it's not already there
const useTranslationsCallExpressions = findCallExpressions(
j,
functionAST,
"useTranslation"
);
if (useTranslationsCallExpressions.length == 0) {
const hook = createTranslationHook(j);
functionAST.value.body.body.unshift(hook);
}
console.log(
`Found not translated template literal in "${componentName}": replacing "${value}" with "${componentName}.${key}".`
);
return j.callExpression.from({
callee: j.identifier("t"),
arguments: [j.literal(`${componentName}.${key}`), expressions],
});
});
};
const JSX_ATTRIBUTES_TO_TRANSLATE = ["alt", "title", "description"];
/**
* Translates React component props that are in the JSX_ATTRIBUTES_TO_TRANSLATE array
* for example:
* <img alt="Hello world" />
* will be translated to
* <img alt={t("imgAltHelloWorld")} />
* @param j
* @param root
* @param translations
* @param importPackage
*/
const translateJSXAttributes = (
j: JSCodeshift,
root: Collection<any>,
translations: Record<string, any>,
importPackage: string
) => {
root
.find(j.JSXAttribute)
.filter((path) => {
if (!j.StringLiteral.check(path.value.value)) return false;
const jsxAttrubute = path.value.name.name;
if (typeof jsxAttrubute !== "string") return false;
if (!JSX_ATTRIBUTES_TO_TRANSLATE.includes(jsxAttrubute)) return false;
return true;
})
.replaceWith((path) => {
// for some reason typescipt doesn't know that we are filtering for StringLiteral above
if (!j.StringLiteral.check(path.value.value)) return false;
// get the top level react component where the hardcoded text is
const functionAST = getClosestFunctionAST(j, path);
if (!functionAST) {
return path; // technically, should not happen as we are filtering for JSXAttribute, but just in case
}
const componentName = _.lowerFirst(getFunctionName(j, functionAST));
const value = sanitizeText(path.value.value.value); // o_O
const key = createTranslationKey(value);
addTranslation(translations, componentName, key, value);
// import translation package provided via `importPackage` option if needed
const translationPackageImports = getImportStatements(
j,
root,
importPackage
);
if (translationPackageImports.length === 0) {
addTranslationPackageImport(j, root, importPackage);
}
// add translation hook to the top of the component, if it's not already there
const useTranslationsCallExpressions = findCallExpressions(
j,
functionAST,
"useTranslation"
);
if (useTranslationsCallExpressions.length == 0) {
const hook = createTranslationHook(j);
functionAST.value.body.body.unshift(hook);
}
console.log(
`Found not translated prop in "${componentName}": replacing "${value}" with "${componentName}.${key}".`
);
// replace hardcoded text with t('key') call
return j.jsxAttribute.from({
name: path.value.name,
value: j.jsxExpressionContainer.from({
expression: j.callExpression.from({
callee: j.identifier("t"),
arguments: [j.literal(`${componentName}.${key}`)],
}),
}),
});
});
};
/**
* Translates <p>text</p> to <p>{t('text')}</p>
* @param j jscodeshift
* @param root parsed AST of provideded source code
* @param translations parsed translation file content (JSON)
* @param importPackage name of the import package (e.g. react-i18next) to add when translation is added
*/
const translateJSXTextContent = (
j: JSCodeshift,
root: Collection<any>,
translations: Record<string, any>,
importPackage: string
) => {
root
.find(j.JSXText)
.filter((path) => !TRANSLATION_BLACKLIST.includes(path.node.value.trim()))
.replaceWith((path) => {
// get the top level react component where the hardcoded text is
const functionAST = getClosestFunctionAST(j, path);
if (!functionAST) {
return path; // technically, should not happen as we are filtering for JSXText, but just in case
}
const componentName = _.lowerFirst(getFunctionName(j, functionAST));
const value = sanitizeText(path.node.value);
const key = createTranslationKey(value);
addTranslation(translations, componentName, key, value);
// import translation package provided via `importPackage` option if needed
const translationPackageImports = getImportStatements(
j,
root,
importPackage
);
if (translationPackageImports.length === 0) {
addTranslationPackageImport(j, root, importPackage);
}
// add translation hook to the top of the component, if it's not already there
const useTranslationCallExpressions = findCallExpressions(
j,
functionAST,
"useTranslation"
);
if (useTranslationCallExpressions.length === 0) {
const hook = createTranslationHook(j);
functionAST.value.body.body.unshift(hook);
}
console.log(
`Found not translated text in "${componentName}": replacing "${value}" with "${componentName}.${key}".`
);
// replace hardcoded text with t('key') call
return j.jsxExpressionContainer(
j.callExpression(j.identifier("t"), [
j.literal(`${componentName}.${key}`),
])
);
});
};
/**
* Called by jscodeshift when running the transform
* @param fileInfo
* @param api
* @param options
*/
const transform: Transform = (fileInfo, api, options) => {
const j = api.jscodeshift;
const { source } = fileInfo;
const { translationFilePath, translationRoot, importName } = options;
if (!translationFilePath) {
throw new Error("No translation file path provided! Aborting.");
}
if (!importName) {
throw new Error(
"No import name provided (e.g. react-i18next, i18next, next-i18next)! Aborting."
);
}
const translations = readTranslations(translationFilePath, translationRoot);
const root = j(source);
translateJSXTextContent(j, root, translations, importName);
translateJSXAttributes(j, root, translations, importName);
translateTemplateLiterals(j, root, translations, importName);
writeTranslations(translationFilePath, translations, translationRoot);
return root.toSource({
quote: "single",
});
};
module.exports = transform;
module.exports.parser = "tsx";