UNPKG

1.85 kBJavaScriptView Raw
1// tooling
2import { list } from 'postcss';
3import transformNode from './transform-node';
4import getReplacedString from './get-replaced-string';
5
6// transform @if at-rules
7export default function transformIfAtrule(atrule, result, opts) {
8 // params as an array
9 const params = list.space(atrule.params);
10
11 // the statement parts (@if LEFT OPERATOR RIGHT)
12 const left = getInterprettedString(getReplacedString(params[0] || '', atrule, result, opts));
13 const operator = params[1];
14 const right = getInterprettedString(getReplacedString(params[2] || '', atrule, result, opts));
15
16 // the next node
17 const next = Object(atrule.next());
18
19 // evaluate the expression
20 if (
21 !operator && left ||
22 operator === '==' && left === right ||
23 operator === '!=' && left !== right ||
24 operator === '<' && left < right ||
25 operator === '<=' && left <= right ||
26 operator === '>' && left > right ||
27 operator === '>=' && left >= right
28 ) {
29 // transform the current children
30 transformNode(atrule, result, opts);
31
32 // insert the current children before the current at-rule
33 atrule.parent.insertBefore(atrule, atrule.nodes);
34
35 // conditionally remove the @else statement
36 if (isElseAtrule(next)) {
37 next.remove();
38 }
39 } else if (isElseAtrule(next)) {
40 // transform the next node children
41 transformNode(next, result, opts);
42
43 // insert the next node children before the current at-rule
44 atrule.parent.insertBefore(atrule, next.nodes);
45
46 // remove the next node
47 next.remove();
48 }
49
50 // remove the current at-rule
51 atrule.remove();
52}
53
54// return whether the node is an else at-rule
55const isElseAtrule = node => 'atrule' === node.type && 'else' === node.name;
56
57// return the value as a boolean, number, or string
58const getInterprettedString = value => 'true' === value
59 ? true
60: 'false' === value
61 ? false
62: isNaN(value)
63 ? value
64: Number(value);