UNPKG

2.07 kBJavaScriptView Raw
1// tooling
2import { list } from 'postcss';
3import getClosestVariable from './get-closest-variable';
4import getReplacedString from './get-replaced-string';
5import setVariable from './set-variable';
6import transformNode from './transform-node';
7
8// transform @include at-rules
9export default function transformIncludeAtrule(atrule, result, opts) {
10 // @include name and args
11 const [ name, sourceArgs ] = atrule.params.split(matchOpeningParen, 2);
12 const args = sourceArgs
13 ? list.comma(sourceArgs.slice(0, -1))
14 : [];
15
16 // @mixin params and atrule
17 const mixin = getClosestVariable(name, atrule.parent, opts);
18
19 // if a matching @mixin is found
20 if (mixin) {
21 // set variables from params and args
22 mixin.params.forEach(
23 (param, index) => {
24 const arg = index in args
25 ? getReplacedString(args[index], atrule, result, opts)
26 : param.value;
27
28 setVariable(atrule, param.name, arg, opts);
29 }
30 );
31
32 // clone the mixin at-rule
33 const clone = mixin.atrule.clone({
34 original: atrule,
35 parent: atrule.parent,
36 variables: atrule.variables
37 });
38
39 // transform the clone
40 transformNode(clone, result, opts);
41
42 // insert the children of the clone before the @include at-rule
43 atrule.parent.insertBefore(atrule, clone.nodes);
44 } else {
45 // otherwise, if a mixin has not been resolved
46 const unresolvedOption = getUnresolvedOption(opts);
47 const message = `Could not resolve the mixin "${name}"`;
48
49 // conditionally throw or warn the user of the unresolved variable
50 if ('throw' === unresolvedOption) {
51 throw atrule.error(message, { word: name });
52 } else if ('warn' === unresolvedOption) {
53 atrule.warn(result, message, { word: name });
54 }
55 }
56
57 // remove the @include at-rule
58 atrule.remove();
59}
60
61// match an opening parenthesis
62const matchOpeningParen = '(';
63
64// get the unresolved variables option
65const getUnresolvedOption = opts => matchUnresolvedOptions.test(Object(opts).unresolved) ? String(opts.unresolved).toLowerCase() : 'throw'
66
67// match unresolved variables options
68const matchUnresolvedOptions = /^(ignore|throw|warn)$/i;