-
Notifications
You must be signed in to change notification settings - Fork 3
/
extract.js
114 lines (97 loc) · 2.53 KB
/
extract.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
"use strict";
const loadSyntax = require("postcss-syntax/load-syntax");
function literalParser (source, opts, styles) {
styles = styles || [];
let index = 0;
literal(source, (startIndex, endIndex, quote) => {
if (quote !== "`") {
return;
}
const strSource = source.slice(startIndex, endIndex);
if (!strSource.trim()) {
return;
}
const style = {
startIndex: startIndex,
content: strSource,
ignoreErrors: !/(?:^|\s+)styled(?:\.\w+|\(+[^()]*?\)+)*$/.test(source.slice(index, startIndex - 1)),
};
index = endIndex;
if (/(\\*)\${.*?}/.test(strSource) && !(RegExp.$1.length % 2)) {
style.syntax = loadSyntax(opts, __dirname);
style.lang = "template-literal";
} else {
style.lang = "css";
}
styles.push(style);
});
return styles;
};
function literal (source, callback) {
let insideString = false;
let insideComment = false;
let insideSingleLineComment = false;
let strStartIndex;
let openingQuote;
for (let i = 0, l = source.length; i < l; i++) {
const currentChar = source[i];
// Register the beginning of a comment
if (
!insideString && !insideComment &&
currentChar === "/" &&
source[i - 1] !== "\\" // escaping
) {
// standard comments
if (source[i + 1] === "*") {
insideComment = true;
continue;
}
// single-line comments
if (source[i + 1] === "/") {
insideComment = true;
insideSingleLineComment = true;
continue;
}
}
if (insideComment) {
// Register the end of a standard comment
if (
!insideSingleLineComment &&
currentChar === "*" &&
source[i - 1] !== "\\" && // escaping
source[i + 1] === "/" &&
source[i - 1] !== "/" // don't end if it's /*/
) {
insideComment = false;
continue;
}
// Register the end of a single-line comment
if (
insideSingleLineComment &&
currentChar === "\n"
) {
insideComment = false;
insideSingleLineComment = false;
continue;
}
}
// Register the beginning of a string
if (!insideComment && !insideString && (currentChar === "\"" || currentChar === "'" || currentChar === "`")) {
if (source[i - 1] === "\\") continue; // escaping
openingQuote = currentChar;
insideString = true;
strStartIndex = i + openingQuote.length;
continue;
}
// Register the end of a string
if (insideString && currentChar === openingQuote) {
if (source[i - 1] === "\\") continue; // escaping
insideString = false;
if ((i - strStartIndex) > 1) {
callback(strStartIndex, i, openingQuote);
}
continue;
}
}
}
module.exports = literalParser;