1 |
|
2 | import { list } from 'postcss';
|
3 | import transformNode from './transform-node';
|
4 | import getReplacedString from './get-replaced-string';
|
5 |
|
6 |
|
7 | export default function transformIfAtrule(rule, opts) {
|
8 |
|
9 | const isTruthy = isIfTruthy(rule, opts);
|
10 | const next = rule.next();
|
11 |
|
12 |
|
13 | if (opts.transform.includes('@if')) {
|
14 |
|
15 | if (isTruthy) {
|
16 |
|
17 | transformNode(rule, opts);
|
18 |
|
19 |
|
20 | rule.parent.insertBefore(rule, rule.nodes);
|
21 | }
|
22 |
|
23 |
|
24 | rule.remove();
|
25 | }
|
26 |
|
27 |
|
28 | if (opts.transform.includes('@else') && isElseRule(next)) {
|
29 |
|
30 | if (!isTruthy) {
|
31 |
|
32 | transformNode(next, opts);
|
33 |
|
34 |
|
35 | next.parent.insertBefore(next, next.nodes);
|
36 | }
|
37 |
|
38 |
|
39 | next.remove();
|
40 | }
|
41 | }
|
42 |
|
43 |
|
44 | const isIfTruthy = (node, opts) => {
|
45 |
|
46 | const params = list.space(node.params);
|
47 | const left = getInterprettedString(getReplacedString(params[0] || '', node, opts));
|
48 | const operator = params[1];
|
49 | const right = getInterprettedString(getReplacedString(params[2] || '', node, opts));
|
50 |
|
51 |
|
52 | const isTruthy = !operator && left ||
|
53 | operator === '==' && left === right ||
|
54 | operator === '!=' && left !== right ||
|
55 | operator === '<' && left < right ||
|
56 | operator === '<=' && left <= right ||
|
57 | operator === '>' && left > right ||
|
58 | operator === '>=' && left >= right;
|
59 |
|
60 | return isTruthy;
|
61 | };
|
62 |
|
63 |
|
64 | const getInterprettedString = value => 'true' === value
|
65 | ? true
|
66 | : 'false' === value
|
67 | ? false
|
68 | : isNaN(value)
|
69 | ? value
|
70 | : Number(value);
|
71 |
|
72 |
|
73 | const isElseRule = node => Object(node) === node && 'atrule' === node.type && 'else' === node.name;
|