forked from i18next/react-i18next
-
Notifications
You must be signed in to change notification settings - Fork 0
/
icu.macro.js
331 lines (281 loc) · 11 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
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 = [] } = references;
// assert we have the react-i18next Trans component imported
addNeededImports(state, babel);
// transform Plural
Plural.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);
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 plural element
mem.values.push(toObjectProperty(attr.node.value.expression.name));
mem.defaults = `{${attr.node.value.expression.name}, plural, ${mem.defaults}`;
} 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);
mem.values = mem.values.concat(thisTrans.values);
componentStartIndex += thisTrans.components.length;
}
return mem;
},
{ attributesToCopy: [], values: [], 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);
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 plural element
mem.values.push(toObjectProperty(attr.node.value.expression.name));
mem.defaults = `{${attr.node.value.expression.name}, select, ${mem.defaults}`;
} 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);
mem.values = mem.values.concat(thisTrans.values);
componentStartIndex += thisTrans.components.length;
}
return mem;
},
{ attributesToCopy: [], values: [], components: [], defaults: '' },
);
// replace the node with the new Trans
parentPath.replaceWith(buildTransElement(extracted, extracted.attributesToCopy, t, true));
}
function transAsJSX(parentPath, { attributes, children }, babel) {
const extracted = processTrans(children, babel);
// replace the node with the new Trans
children[0].parentPath.replaceWith(
buildTransElement(extracted, cloneExistingAttributes(attributes), babel.types, false, true),
);
}
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 attributeExistsAlready(name, attributes) {
const found = attributes.find(child => {
const ele = child.node ? child.node : child;
return ele.name.name === name;
});
return !!found;
}
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;
}
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
if (t.isJSXText(ele) && ele.value) mem += 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((mem, child) => {
const ele = child.node ? child.node : child;
// clean out invalid definitions by replacing `{ catchDate, date, short }` with `{ catchDate }`
if (ele.expression && ele.expression.expressions)
ele.expression.expressions = [ele.expression.expressions[0]];
mem.push(child);
}, []);
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'),
),
);
}
}