-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
89 lines (75 loc) · 2.44 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
'use strict';
const emMediaQuery = require('em-media-query');
const PROCESSED_MEDIA_QUERY_ID = '_em-media-query-processed';
module.exports = ( opts ) => {
const t = opts.types;
function getParent ( path ) {
const parent = path.parentPath;
if ( t.isCallExpression(parent.node) ) {
return parent;
}
return getParent(parent);
}
function isMediaQueryComment ( value ) {
return value.indexOf('@media') !== -1;
}
function isMediaQueryCommentProcessed ( value ) {
return value.indexOf(PROCESSED_MEDIA_QUERY_ID) !== -1;
}
function transformMediaQueryComment ( path, state ) {
if (
path.node.leadingComments === null ||
typeof path.node.leadingComments === 'undefined' ||
(path.node.leadingComments && path.node.leadingComments.length === 0)
) {
return;
}
const mediaQueryComments = path.node.leadingComments
.filter(( comment ) => {
return isMediaQueryComment(comment.value) && !isMediaQueryCommentProcessed(comment.value);
});
if ( mediaQueryComments.length !== 0 ) {
mediaQueryComments
.forEach(() => {
if ( t.isStringLiteral(path) ) {
path.replaceWith(t.stringLiteral(emMediaQuery(path.node.value, state.opts)));
} else if ( t.isTemplateLiteral(path) && path.node.quasis.length === 1 ) {
path.replaceWith(t.stringLiteral(emMediaQuery(path.node.quasis[0].value.raw, state.opts)));
}
path.node.comments = (path.node.comments || []).concat(path.node.leadingComments);
});
path.node.leadingComments = path.node.leadingComments
.map(( comment ) => {
if ( isMediaQueryComment(comment.value) ) {
const commentValue =
[comment.value, PROCESSED_MEDIA_QUERY_ID]
.map(( value ) => {
return value.trim();
})
.join(' ');
comment.value = ` ${commentValue} `;
}
return comment;
});
}
}
return {
visitor: {
Identifier: ( path, state ) => {
if ( t.isIdentifier(path.node, { name: 'matchMedia' }) ) {
const parent = getParent(path);
parent.node.arguments = parent.node.arguments.map(( arg ) => {
if ( t.isStringLiteral(arg) ) {
return t.stringLiteral(emMediaQuery(arg.value, state.opts));
} else if ( t.isTemplateLiteral(arg) && arg.quasis.length === 1 ) {
return t.stringLiteral(emMediaQuery(arg.quasis[0].value.raw, state.opts));
}
return arg;
});
}
},
StringLiteral: transformMediaQueryComment,
TemplateLiteral: transformMediaQueryComment
}
};
};