-
Notifications
You must be signed in to change notification settings - Fork 6
/
resolveVariableDependencies.js
58 lines (48 loc) · 1.62 KB
/
resolveVariableDependencies.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// @flow
/*
CAUTION!
This file could be included even after running the babel plugin.
Make sure you don't import large libraries.
*/
/* eslint-disable no-param-reassign */
const { DepGraph } = require("dependency-graph");
const { varRegExp, varRegExpNonGlobal } = require("../../util/cssRegExp");
module.exports = (
definedVariables /*: { [key:string]: string } */,
variablesFromScope /*: { [key:string]: string } */
) /*: { [key:string]: string } */ => {
const graph = new DepGraph();
const variableNames = Object.keys(definedVariables);
variableNames.forEach(variableName => {
graph.addNode(variableName);
});
variableNames.forEach(variableName => {
const referencedVariableMatches = definedVariables[variableName].match(
varRegExp
);
if (referencedVariableMatches == null) return;
const referencedVariables = referencedVariableMatches
.map(match => {
const matchedVariable = match.match(varRegExpNonGlobal);
return matchedVariable ? matchedVariable[1] : null;
})
.filter(Boolean);
referencedVariables.forEach(referencedVariableName => {
if (referencedVariableName in definedVariables) {
graph.addDependency(variableName, referencedVariableName);
}
});
});
const appliedVariables = graph
.overallOrder(false)
.reduce((accum, variableName) => {
const value = definedVariables[variableName].replace(
varRegExp,
(m, reference, fallback) =>
accum[reference] || variablesFromScope[reference] || fallback
);
accum[variableName] = value;
return accum;
}, {});
return appliedVariables;
};