UNPKG

1.48 kBJavaScriptView Raw
1// tooling
2import getArrayedString from './get-arrayed-string';
3import getReplacedString from './get-replaced-string';
4import transformNode from './transform-node';
5import setVariable from './set-variable';
6
7// transform @each at-rules
8export default function transformEachAtrule(atrule, result, opts) {
9 // params as an array
10 const params = atrule.params.split(matchInOperator);
11
12 // the statement parts (@each NAME in ARRAY, @each NAME ITERATOR in ARRAY)
13 const args = (params[0] || '').trim().split(' ');
14 const name = args[0].trim().slice(1);
15 const itername = args.length > 1 ? args[1].trim().slice(1) : null;
16 const array = getArrayedString(getReplacedString(params.slice(1).join(matchInOperator), atrule, result, opts), true);
17 const end = array.length;
18
19 // for each item
20 for (let incrementor = 0; incrementor < end; ++incrementor) {
21 // set the current iterating variable
22 setVariable(atrule, name, array[incrementor], opts);
23
24 // conditionally set the current iterator variable
25 if (itername) {
26 setVariable(atrule, itername, incrementor, opts);
27 }
28
29 // clone the current at-rule
30 const clone = atrule.clone({
31 parent: atrule.parent,
32 variables: atrule.variables
33 });
34
35 // transform the cloned children
36 transformNode(clone, result, opts);
37
38 // insert the cloned children before the current at-rule
39 atrule.parent.insertBefore(atrule, clone.nodes);
40 }
41
42 // remove the current atrule
43 atrule.remove();
44}
45
46const matchInOperator = ' in ';