-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
61 lines (45 loc) · 1.74 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
const Typograf = require('typograf');
const restrictedDefaultRules = require('./restricted-default-rules');
const placeholder = '__BABEL_PLUGIN_TYPOGRAF__';
function compile(str, opts) {
const locale = opts.locale || ['ru', 'en-US'];
const htmlEntity = opts.htmlEntity || undefined;
const enableRules = opts.enableRules || [];
const ruleSettings = opts.ruleSettings || [];
const disableRules = [
...restrictedDefaultRules.filter(rule => !enableRules.includes(rule)),
...(opts.disableRules || []),
];
const tp = new Typograf({ htmlEntity, locale });
enableRules.forEach(rule => tp.enableRule(rule));
disableRules.forEach(rule => tp.disableRule(rule));
ruleSettings.forEach(settings => tp.setSetting(...settings));
return tp.execute(str);
}
module.exports = ({ types }) => ({
visitor: {
TaggedTemplateExpression(path, state) {
if (!types.isIdentifier(path.node.tag, { name: 'T' })) {
return;
}
const quasis = [];
let rawQuasis = [];
let cookedQuasis = [];
path.get('quasi').get('quasis')
.forEach((el) => {
rawQuasis.push(el.node.value.raw);
cookedQuasis.push(el.node.value.cooked);
});
rawQuasis = compile(rawQuasis.join(placeholder), state.opts).split(placeholder);
cookedQuasis = compile(cookedQuasis.join(placeholder), state.opts).split(placeholder);
if (rawQuasis.length !== cookedQuasis.length) {
throw new Error('Raw and Cooked values diverge.');
}
rawQuasis.forEach((raw, index) => {
const cooked = cookedQuasis[index];
quasis.push(types.templateElement({ cooked, raw }));
});
path.replaceWith(types.templateLiteral(quasis, path.get('quasi').node.expressions));
},
},
});