1 | "use strict"
|
2 |
|
3 | const base64EncodedConditionalImport = require("./base64-encoded-import")
|
4 |
|
5 | module.exports = function applyConditions(bundle, atRule) {
|
6 | bundle.forEach(stmt => {
|
7 | if (
|
8 | stmt.type === "charset" ||
|
9 | stmt.type === "warning" ||
|
10 | !stmt.conditions?.length
|
11 | ) {
|
12 | return
|
13 | }
|
14 |
|
15 | if (stmt.type === "import") {
|
16 | stmt.node.params = base64EncodedConditionalImport(
|
17 | stmt.fullUri,
|
18 | stmt.conditions,
|
19 | )
|
20 | return
|
21 | }
|
22 |
|
23 | const { nodes } = stmt
|
24 | const { parent } = nodes[0]
|
25 |
|
26 | const atRules = []
|
27 |
|
28 |
|
29 | for (const condition of stmt.conditions) {
|
30 | if (typeof condition.media !== "undefined") {
|
31 | const mediaNode = atRule({
|
32 | name: "media",
|
33 | params: condition.media,
|
34 | source: parent.source,
|
35 | })
|
36 |
|
37 | atRules.push(mediaNode)
|
38 | }
|
39 |
|
40 | if (typeof condition.supports !== "undefined") {
|
41 | const supportsNode = atRule({
|
42 | name: "supports",
|
43 | params: `(${condition.supports})`,
|
44 | source: parent.source,
|
45 | })
|
46 |
|
47 | atRules.push(supportsNode)
|
48 | }
|
49 |
|
50 | if (typeof condition.layer !== "undefined") {
|
51 | const layerNode = atRule({
|
52 | name: "layer",
|
53 | params: condition.layer,
|
54 | source: parent.source,
|
55 | })
|
56 |
|
57 | atRules.push(layerNode)
|
58 | }
|
59 | }
|
60 |
|
61 |
|
62 | const outerAtRule = atRules.shift()
|
63 | const innerAtRule = atRules.reduce((previous, next) => {
|
64 | previous.append(next)
|
65 | return next
|
66 | }, outerAtRule)
|
67 |
|
68 | parent.insertBefore(nodes[0], outerAtRule)
|
69 |
|
70 |
|
71 | nodes.forEach(node => {
|
72 | node.parent = undefined
|
73 | })
|
74 |
|
75 |
|
76 | nodes[0].raws.before = nodes[0].raws.before || "\n"
|
77 |
|
78 |
|
79 | innerAtRule.append(nodes)
|
80 |
|
81 | stmt.type = "nodes"
|
82 | stmt.nodes = [outerAtRule]
|
83 | delete stmt.node
|
84 | })
|
85 | }
|