-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
63 lines (62 loc) · 3.53 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
const defaultConfigLength = require("./PhoneticConstants").defaultConfigLength;
const PseudoLangMap = require("./PhoneticConstants").PseudoLangMap;
const template = require("@babel/template").default;
const convertToPhonetics = require('./PhoneticConverter');
module.exports = function (api, options) {
const {types: t} = api;
const extraLength = options.extraLength || defaultConfigLength;
const languageMap = options.customLanguageMap || PseudoLangMap;
const languageMapString = JSON.stringify(languageMap);
let root;
return {
visitor: {
Program(path) {
root = path;
const code = `if(!global.convertToPhonetics){global.convertToPhonetics = ${convertToPhonetics};}`;
path.node.body.unshift(template.ast(code));
},
JSXOpeningElement(path) {
const node = path.node;
if (t.isJSXOpeningElement(node)) {
// @TODO: Add NodeList as plugin input
if (node && node.name && node.name.name && (node.name.name === 'Text')) {
const parentPath = path.findParent((path) => path.isJSXElement());
let children = parentPath && parentPath.node && parentPath.node.children;
let newChildren =
children &&
children.map((child) => {
if (child.type === 'JSXExpressionContainer') {
switch (child.expression.type) {
case 'MemberExpression':
case 'ConditionalExpression':
case 'OptionalMemberExpression':
case 'ChainExpression':
case 'StringLiteral':
case 'Identifier':
const injectFunction = t.CallExpression(t.identifier('convertToPhonetics'), [child.expression, t.NumericLiteral(extraLength), t.StringLiteral(languageMapString)]);
child = t.JSXExpressionContainer(injectFunction);
break;
case 'CallExpression':
if (child.expression.callee.name !== 'convertToPhonetics') {
const injectFunction = t.CallExpression(t.identifier('convertToPhonetics'), [child.expression, t.NumericLiteral(extraLength), t.StringLiteral(languageMapString)]);
child = t.JSXExpressionContainer(injectFunction);
}
break;
}
return child;
}
if (child.type === 'JSXText') {
if (child.value.trim().length > 0) {
return t.JSXText(convertToPhonetics(child.value, extraLength, languageMapString));
}
return child;
}
return child;
});
parentPath.node.children = newChildren;
}
}
}
}
};
};