-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathindex.js
69 lines (56 loc) · 2.97 KB
/
index.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
module.exports = function({ types: t }) {
function getNodeForValue(value, tokens) {
if (value.match(/^\{.*?\}$/) && tokens[value]) {
return tokens[value];
}
return t.stringLiteral(value);
}
return {
visitor: {
CallExpression(path, state) {
const translationFunctionName = state.opts.functionName || 't';
const dictionary = state.opts.dictionary || {};
if (t.isIdentifier(path.node.callee) && path.node.callee.name === translationFunctionName) {
const firstArgument = path.node.arguments[0];
if (!firstArgument || !firstArgument.extra) {
return;
}
let string = firstArgument.extra.rawValue;
if (dictionary[string]) {
string = dictionary[string];
}
if (path.node.arguments.length > 1 && t.isObjectExpression(path.node.arguments[1])) {
const tokens = path.node.arguments[1].properties.reduce((previous, current) => {
previous[`{${current.key.name}}`] = current.value;
return previous;
}, {});
const replacementNode = string.split(/(\{.*?\})/g).filter((component) => {
return component !== '';
}).reduce((previous, current, i) => {
if (i === 1) {
previous = getNodeForValue(previous, tokens);
}
const currentNode = getNodeForValue(current, tokens);
if (t.isStringLiteral(currentNode)) {
// If the previous node is a StringLiteral, return a combined StringLiteral
if (t.isStringLiteral(previous)) {
return t.stringLiteral(`${previous.value}${currentNode.value}`);
}
// If the previous node is a BinaryExpression with a StringLiteral on the right side,
// update the BinaryExpression to have a combined StringLiteral on the right
if (t.isBinaryExpression(previous) && t.isStringLiteral(previous.right)) {
previous.right = t.stringLiteral(`${previous.right.value}${currentNode.value}`);
return previous;
}
}
return t.binaryExpression('+', previous, currentNode);
});
path.replaceWith(replacementNode);
return;
}
path.replaceWith(t.stringLiteral(string));
}
}
}
};
};