UNPKG

1.46 kBJavaScriptView Raw
1// tooling
2import getClosestVariable from './get-closest-variable';
3import manageUnresolved from './manage-unresolved';
4
5// return content with its variables replaced by the corresponding values of a node
6export default function getReplacedString(string, node, opts) {
7 const replacedString = string.replace(
8 matchVariables,
9 (match, before, name1, name2, name3) => {
10 // conditionally return an (unescaped) match
11 if (before === '\\') {
12 return match.slice(1);
13 }
14
15 // the first matching variable name
16 const name = name1 || name2 || name3;
17
18 // the closest variable value
19 const value = getClosestVariable(name, node.parent, opts);
20
21 // if a variable has not been resolved
22 if (undefined === value) {
23 manageUnresolved(node, opts, name, `Could not resolve the variable "$${name}" within "${string}"`);
24
25 return match;
26 }
27
28 // the stringified value
29 const stringifiedValue = `${before}${stringify(value)}`;
30
31 return stringifiedValue;
32 }
33 );
34
35 return replacedString;
36}
37
38// match all $name, $(name), and #{$name} variables (and catch the character before it)
39const matchVariables = /(.?)(?:\$([A-z][\w-]*)|\$\(([A-z][\w-]*)\)|#\{\$([A-z][\w-]*)\})/g;
40
41// return a sass stringified variable
42const stringify = object => Array.isArray(object)
43 ? `(${object.map(stringify).join(',')})`
44: Object(object) === object
45 ? `(${Object.keys(object).map(
46 key => `${key}:${stringify(object[key])}`
47 ).join(',')})`
48: String(object);