UNPKG

1.86 kBJavaScriptView Raw
1// tooling
2import { list } from 'postcss';
3import getClosestVariable from './get-closest-variable';
4import getReplacedString from './get-replaced-string';
5import manageUnresolved from './manage-unresolved';
6import setVariable from './set-variable';
7import transformNode from './transform-node';
8
9// transform @include at-rules
10export default function transformIncludeAtrule(rule, opts) {
11 // if @include is supported
12 if (opts.transform.includes('@include')) {
13 // @include options
14 const { name, args } = getIncludeOpts(rule);
15
16 // the closest @mixin variable
17 const mixin = getClosestVariable(`@mixin ${name}`, rule.parent, opts);
18
19 // if the @mixin variable exists
20 if (mixin) {
21 // set @mixin variables on the @include at-rule
22 mixin.params.forEach(
23 (param, index) => {
24 const arg = index in args
25 ? getReplacedString(args[index], rule, opts)
26 : param.value;
27
28 setVariable(rule, param.name, arg, opts);
29 }
30 );
31
32 // clone the @mixin at-rule
33 const clone = mixin.rule.clone({
34 original: rule,
35 parent: rule.parent,
36 variables: rule.variables
37 });
38
39 // transform the clone children
40 return transformNode(clone, opts).then(() => {
41 // replace the @include at-rule with the clone children
42 rule.parent.insertBefore(rule, clone.nodes);
43
44 rule.remove();
45 })
46 } else {
47 // otherwise, if the @mixin variable does not exist
48 manageUnresolved(rule, opts, name, `Could not resolve the mixin for "${name}"`);
49 }
50 }
51}
52
53// return the @include statement options (@include NAME, @include NAME(ARGS))
54const getIncludeOpts = node => {
55 // @include name and args
56 const [ name, sourceArgs ] = node.params.split(matchOpeningParen, 2);
57 const args = sourceArgs
58 ? list.comma(sourceArgs.slice(0, -1))
59 : [];
60
61 return { name, args };
62};
63
64// match an opening parenthesis
65const matchOpeningParen = '(';