UNPKG

1.9 kBJavaScriptView Raw
1var _ = require('lodash');
2var parseDwayneHTML = require('parse-dwayne-html');
3var babelTemplate = require('babel-template');
4
5var template = babelTemplate('var VAR;\n\n');
6var templateThis = babelTemplate('var VAR = this;\n\n');
7
8module.exports = function (opts) {
9 var t = opts.types;
10
11 return {
12 visitor: {
13 TaggedTemplateExpression: function (path, state) {
14 var node = path.node;
15 var quasi = node.quasi;
16 var opts = state.opts;
17 var taggedHtmlFuncName = opts.taggedHtmlFuncName || 'html';
18 var taggedHtmlScopelessFuncName = opts.taggedHtmlScopelessFuncName || 'htmlScopeless';
19
20 if (
21 quasi.quasis.length !== 1
22 || quasi.expressions.length
23 || (node.tag.name !== taggedHtmlFuncName && node.tag.name !== taggedHtmlScopelessFuncName)
24 ) {
25 return;
26 }
27
28 var value = quasi.quasis[0].value.cooked;
29 var unique = path.scope.generateUid(_.get(opts, 'funcName', 'func'));
30 var uniqueThisUid = path.scope.generateUid('this');
31 var parserOpts = _.assign({}, opts, {
32 funcName: unique,
33 keepOriginal: _.get(opts, 'keepOriginal', true),
34 __keepScope__: node.tag.name === taggedHtmlScopelessFuncName,
35 __thisUid__: uniqueThisUid
36 });
37 var parsed = parseDwayneHTML(value, parserOpts);
38
39 path.replaceWithSourceString(parsed.html);
40 path.insertBefore(
41 template({
42 VAR: t.identifier(parsed.tmplVar)
43 })
44 );
45
46 if (parserOpts.keepOriginal) {
47 path.insertBefore(
48 template({
49 VAR: t.identifier(unique)
50 })
51 );
52 }
53
54 if (parserOpts.__keepScope__) {
55 path.insertBefore(
56 templateThis({
57 VAR: t.identifier(uniqueThisUid)
58 })
59 );
60 }
61 }
62 }
63 };
64};