forked from i18next/react-i18next
-
Notifications
You must be signed in to change notification settings - Fork 0
/
icu.macro.js
400 lines (343 loc) · 14.1 KB
/
icu.macro.js
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
const { createMacro } = require('babel-plugin-macros');
// copy to:
// https://astexplorer.net/#/gist/642aebbb9e449e959f4ad8907b4adf3a/4a65742e2a3e926eb55eaa3d657d1472b9ac7970
module.exports = createMacro(ICUMacro);
function ICUMacro({ references, state, babel }) {
const t = babel.types;
const { Trans = [], Plural = [], Select = [], SelectOrdinal = [] } = references;
// assert we have the react-i18next Trans component imported
addNeededImports(state, babel);
// transform Plural and SelectOrdinal
[...Plural, ...SelectOrdinal].forEach(referencePath => {
if (referencePath.parentPath.type === 'JSXOpeningElement') {
pluralAsJSX(
referencePath.parentPath,
{
attributes: referencePath.parentPath.get('attributes'),
children: referencePath.parentPath.parentPath.get('children'),
},
babel,
);
} else {
// throw a helpful error message or something :)
}
});
// transform Select
Select.forEach(referencePath => {
if (referencePath.parentPath.type === 'JSXOpeningElement') {
selectAsJSX(
referencePath.parentPath,
{
attributes: referencePath.parentPath.get('attributes'),
children: referencePath.parentPath.parentPath.get('children'),
},
babel,
);
} else {
// throw a helpful error message or something :)
}
});
// transform Trans
Trans.forEach(referencePath => {
if (referencePath.parentPath.type === 'JSXOpeningElement') {
transAsJSX(
referencePath.parentPath,
{
attributes: referencePath.parentPath.get('attributes'),
children: referencePath.parentPath.parentPath.get('children'),
},
babel,
);
} else {
// throw a helpful error message or something :)
}
});
}
function pluralAsJSX(parentPath, { attributes }, babel) {
const t = babel.types;
const toObjectProperty = (name, value) =>
t.objectProperty(t.identifier(name), t.identifier(name), false, !value);
// plural or selectordinal
const nodeName = parentPath.node.name.name.toLocaleLowerCase();
// will need to merge count attribute with existing values attribute in some cases
const existingValuesAttribute = findAttribute('values', attributes);
const existingValues = existingValuesAttribute
? existingValuesAttribute.node.value.expression.properties
: [];
let componentStartIndex = 0;
const extracted = attributes.reduce(
(mem, attr) => {
if (attr.node.name.name === 'i18nKey') {
// copy the i18nKey
mem.attributesToCopy.push(attr.node);
} else if (attr.node.name.name === 'count') {
// take the count for element
let exprName = attr.node.value.expression.name;
if (!exprName) {
exprName = 'count';
}
if (exprName === 'count') {
// if the prop expression name is also "count", copy it instead: <Plural count={count} --> <Trans count={count}
mem.attributesToCopy.push(attr.node);
} else {
mem.values.unshift(toObjectProperty(exprName));
}
mem.defaults = `{${exprName}, ${nodeName}, ${mem.defaults}`;
} else if (attr.node.name.name === 'values') {
// skip the values attribute, as it has already been processed into mem from existingValues
} else if (attr.node.value.type === 'StringLiteral') {
// take any string node as plural option
let pluralForm = attr.node.name.name;
if (pluralForm.indexOf('$') === 0) pluralForm = pluralForm.replace('$', '=');
mem.defaults = `${mem.defaults} ${pluralForm} {${attr.node.value.value}}`;
} else if (attr.node.value.type === 'JSXExpressionContainer') {
// convert any Trans component to plural option extracting any values and components
const children = attr.node.value.expression.children || [];
const thisTrans = processTrans(children, babel, componentStartIndex);
let pluralForm = attr.node.name.name;
if (pluralForm.indexOf('$') === 0) pluralForm = pluralForm.replace('$', '=');
mem.defaults = `${mem.defaults} ${pluralForm} {${thisTrans.defaults}}`;
mem.components = mem.components.concat(thisTrans.components);
componentStartIndex += thisTrans.components.length;
}
return mem;
},
{ attributesToCopy: [], values: existingValues, components: [], defaults: '' },
);
// replace the node with the new Trans
parentPath.replaceWith(buildTransElement(extracted, extracted.attributesToCopy, t, true));
}
function selectAsJSX(parentPath, { attributes }, babel) {
const t = babel.types;
const toObjectProperty = (name, value) =>
t.objectProperty(t.identifier(name), t.identifier(name), false, !value);
// will need to merge switch attribute with existing values attribute
const existingValuesAttribute = findAttribute('values', attributes);
const existingValues = existingValuesAttribute
? existingValuesAttribute.node.value.expression.properties
: [];
let componentStartIndex = 0;
const extracted = attributes.reduce(
(mem, attr) => {
if (attr.node.name.name === 'i18nKey') {
// copy the i18nKey
mem.attributesToCopy.push(attr.node);
} else if (attr.node.name.name === 'switch') {
// take the switch for select element
let exprName = attr.node.value.expression.name;
if (!exprName) {
exprName = 'selectKey';
mem.values.unshift(t.objectProperty(t.identifier(exprName), attr.node.value.expression));
} else {
mem.values.unshift(toObjectProperty(exprName));
}
mem.defaults = `{${exprName}, select, ${mem.defaults}`;
} else if (attr.node.name.name === 'values') {
// skip the values attribute, as it has already been processed into mem as existingValues
} else if (attr.node.value.type === 'StringLiteral') {
// take any string node as select option
mem.defaults = `${mem.defaults} ${attr.node.name.name} {${attr.node.value.value}}`;
} else if (attr.node.value.type === 'JSXExpressionContainer') {
// convert any Trans component to select option extracting any values and components
const children = attr.node.value.expression.children || [];
const thisTrans = processTrans(children, babel, componentStartIndex);
mem.defaults = `${mem.defaults} ${attr.node.name.name} {${thisTrans.defaults}}`;
mem.components = mem.components.concat(thisTrans.components);
componentStartIndex += thisTrans.components.length;
}
return mem;
},
{ attributesToCopy: [], values: existingValues, components: [], defaults: '' },
);
// replace the node with the new Trans
parentPath.replaceWith(buildTransElement(extracted, extracted.attributesToCopy, t, true));
}
function transAsJSX(parentPath, { attributes, children }, babel) {
const defaultsAttr = findAttribute('defaults', attributes);
const componentsAttr = findAttribute('components', attributes);
// if there is "defaults" attribute and no "components" attribute, parse defaults and extract from the parsed defaults instead of children
// if a "components" attribute has been provided, we assume they have already constructed a valid "defaults" and it does not need to be parsed
const parseDefaults = defaultsAttr && !componentsAttr;
let extracted;
if (parseDefaults) {
const defaultsExpression = defaultsAttr.node.value.value;
const parsed = babel.parse(`<>${defaultsExpression}</>`, {
presets: ['@babel/react'],
}).program.body[0].expression.children;
extracted = processTrans(parsed, babel);
} else {
extracted = processTrans(children, babel);
}
let clonedAttributes = cloneExistingAttributes(attributes);
if (parseDefaults) {
// remove existing defaults so it can be replaced later with the new parsed defaults
clonedAttributes = clonedAttributes.filter(node => node.name.name !== 'defaults');
}
// replace the node with the new Trans
const replacePath = children.length ? children[0].parentPath : parentPath;
replacePath.replaceWith(
buildTransElement(extracted, clonedAttributes, babel.types, false, !!children.length),
);
}
function buildTransElement(
extracted,
finalAttributes,
t,
closeDefaults = false,
wasElementWithChildren = false,
) {
const nodeName = t.jSXIdentifier('Trans');
// plural, select open { but do not close it while reduce
if (closeDefaults) extracted.defaults += '}';
// convert arrays into needed expressions
extracted.components = t.arrayExpression(extracted.components);
extracted.values = t.objectExpression(extracted.values);
// add generated Trans attributes
if (!attributeExistsAlready('defaults', finalAttributes))
finalAttributes.push(
t.jSXAttribute(t.jSXIdentifier('defaults'), t.StringLiteral(extracted.defaults)),
);
if (!attributeExistsAlready('components', finalAttributes))
finalAttributes.push(
t.jSXAttribute(t.jSXIdentifier('components'), t.jSXExpressionContainer(extracted.components)),
);
if (!attributeExistsAlready('values', finalAttributes))
finalAttributes.push(
t.jSXAttribute(t.jSXIdentifier('values'), t.jSXExpressionContainer(extracted.values)),
);
// create selfclosing Trans component
const openElement = t.jSXOpeningElement(nodeName, finalAttributes, true);
if (!wasElementWithChildren) return openElement;
return t.jSXElement(openElement, null, [], true);
}
function cloneExistingAttributes(attributes) {
return attributes.reduce((mem, attr) => {
mem.push(attr.node);
return mem;
}, []);
}
function findAttribute(name, attributes) {
return attributes.find(child => {
const ele = child.node ? child.node : child;
return ele.name.name === name;
});
}
function attributeExistsAlready(name, attributes) {
return !!findAttribute(name, attributes);
}
function processTrans(children, babel, componentStartIndex = 0) {
const res = {};
res.defaults = mergeChildren(children, babel, componentStartIndex);
res.components = getComponents(children, babel);
res.values = getValues(children, babel);
return res;
}
// eslint-disable-next-line no-control-regex
const leadingNewLineAndWhitespace = new RegExp('^\n\\s+', 'g');
// eslint-disable-next-line no-control-regex
const trailingNewLineAndWhitespace = new RegExp('\n\\s+$', 'g');
function trimIndent(text) {
const newText = text
.replace(leadingNewLineAndWhitespace, '')
.replace(trailingNewLineAndWhitespace, '');
return newText;
}
function mergeChildren(children, babel, componentStartIndex = 0) {
const t = babel.types;
let componentFoundIndex = componentStartIndex;
return children.reduce((mem, child) => {
const ele = child.node ? child.node : child;
// add text, but trim indentation whitespace
if (t.isJSXText(ele) && ele.value) mem += trimIndent(ele.value);
// add ?!? forgot
if (ele.expression && ele.expression.value) mem += ele.expression.value;
// add `{ val }`
if (ele.expression && ele.expression.name) mem += `{${ele.expression.name}}`;
// add `{ val, number }`
if (ele.expression && ele.expression.expressions) {
mem += `{${ele.expression.expressions
.reduce((m, i) => {
m.push(i.name || i.value);
return m;
}, [])
.join(', ')}}`;
}
// add <strong>...</strong> with replace to <0>inner string</0>
if (t.isJSXElement(ele)) {
mem += `<${componentFoundIndex}>${mergeChildren(
ele.children,
babel,
)}</${componentFoundIndex}>`;
componentFoundIndex++;
}
return mem;
}, '');
}
function getValues(children, babel) {
const t = babel.types;
const toObjectProperty = (name, value) =>
t.objectProperty(t.identifier(name), t.identifier(name), false, !value);
return children.reduce((mem, child) => {
const ele = child.node ? child.node : child;
// add `{ var }` to values
if (ele.expression && ele.expression.name) mem.push(toObjectProperty(ele.expression.name));
// add `{ var, number }` to values
if (ele.expression && ele.expression.expressions)
mem.push(
toObjectProperty(ele.expression.expressions[0].name || ele.expression.expressions[0].value),
);
// add `{ var: 'bar' }` to values
if (ele.expression && ele.expression.properties) mem = mem.concat(ele.expression.properties);
// recursive add inner elements stuff to values
if (t.isJSXElement(ele)) {
mem = mem.concat(getValues(ele.children, babel));
}
return mem;
}, []);
}
function getComponents(children, babel) {
const t = babel.types;
return children.reduce((mem, child) => {
const ele = child.node ? child.node : child;
if (t.isJSXElement(ele)) {
const clone = t.clone(ele);
clone.children = clone.children.reduce((clonedMem, clonedChild) => {
const clonedEle = clonedChild.node ? clonedChild.node : clonedChild;
// clean out invalid definitions by replacing `{ catchDate, date, short }` with `{ catchDate }`
if (clonedEle.expression && clonedEle.expression.expressions)
clonedEle.expression.expressions = [clonedEle.expression.expressions[0]];
clonedMem.push(clonedChild);
return clonedMem;
}, []);
mem.push(ele);
}
return mem;
}, []);
}
function addNeededImports(state, babel) {
const t = babel.types;
const importsToAdd = ['Trans'];
// check if there is an existing react-i18next import
const existingImport = state.file.path.node.body.find(
importNode => t.isImportDeclaration(importNode) && importNode.source.value === 'react-i18next',
);
// append Trans to existing or add a new react-i18next import for the Trans
if (existingImport) {
importsToAdd.forEach(name => {
if (
existingImport.specifiers.findIndex(
specifier => specifier.imported && specifier.imported.name === name,
) === -1
) {
existingImport.specifiers.push(t.importSpecifier(t.identifier(name), t.identifier(name)));
}
});
} else {
state.file.path.node.body.unshift(
t.importDeclaration(
importsToAdd.map(name => t.importSpecifier(t.identifier(name), t.identifier(name))),
t.stringLiteral('react-i18next'),
),
);
}
}