/
conditional-comment.js
80 lines (72 loc) · 2.33 KB
/
conditional-comment.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
"use strict";
// https://css-tricks.com/how-to-create-an-ie-only-stylesheet
// <!--[if ... ]> ... <![endif]-->
const IE_CONDITIONAL_START_END_COMMENT_REGEX = /^(\[if([^\]]*?)\]>)([\s\S]*?)<!\s*\[endif\]$/;
// <!--[if ... ]><!-->
const IE_CONDITIONAL_START_COMMENT_REGEX = /^\[if([^\]]*?)\]><!$/;
// <!--<![endif]-->
const IE_CONDITIONAL_END_COMMENT_REGEX = /^<!\s*\[endif\]$/;
const REGEX_PARSE_TUPLES = [
[IE_CONDITIONAL_START_END_COMMENT_REGEX, parseIeConditionalStartEndComment],
[IE_CONDITIONAL_START_COMMENT_REGEX, parseIeConditionalStartComment],
[IE_CONDITIONAL_END_COMMENT_REGEX, parseIeConditionalEndComment]
];
function parseIeConditionalComment(node, parseHtml) {
if (node.value) {
let match;
for (const [regex, parse] of REGEX_PARSE_TUPLES) {
if ((match = node.value.match(regex))) {
return parse(node, parseHtml, match);
}
}
}
return null;
}
function parseIeConditionalStartEndComment(node, parseHtml, match) {
const [, openingTagSuffix, condition, data] = match;
const offset = "<!--".length + openingTagSuffix.length;
const contentStartSpan = node.sourceSpan.start.moveBy(offset);
const contentEndSpan = contentStartSpan.moveBy(data.length);
const ParseSourceSpan = node.sourceSpan.constructor;
const [complete, children] = (() => {
try {
return [true, parseHtml(data, contentStartSpan).children];
} catch (e) {
const text = {
type: "text",
value: data,
sourceSpan: new ParseSourceSpan(contentStartSpan, contentEndSpan)
};
return [false, [text]];
}
})();
return {
type: "ieConditionalComment",
complete,
children,
condition: condition.trim().replace(/\s+/g, " "),
sourceSpan: node.sourceSpan,
startSourceSpan: new ParseSourceSpan(
node.sourceSpan.start,
contentStartSpan
),
endSourceSpan: new ParseSourceSpan(contentEndSpan, node.sourceSpan.end)
};
}
function parseIeConditionalStartComment(node, parseHtml, match) {
const [, condition] = match;
return {
type: "ieConditionalStartComment",
condition: condition.trim().replace(/\s+/g, " "),
sourceSpan: node.sourceSpan
};
}
function parseIeConditionalEndComment(node /*, parseHtml, match */) {
return {
type: "ieConditionalEndComment",
sourceSpan: node.sourceSpan
};
}
module.exports = {
parseIeConditionalComment
};