Skip to content

Commit c29a2aa

Browse files
committed
Added support for recursive variable values
1 parent e97a671 commit c29a2aa

1 file changed

Lines changed: 29 additions & 3 deletions

File tree

lib/postcss-plugins.js

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
const postcss = require('postcss');
22

33
const THEME_VAR_PREFIX = 'theme-var';
4+
const VAR_REGEX = /var\((--.+?)\)/;
45

56
module.exports.extractThemeRulesPlugin = postcss.plugin('postcss-extract-theme-rules', (options = {}) => {
67
const prefix = options.prefix || THEME_VAR_PREFIX;
@@ -42,6 +43,29 @@ module.exports.extractVariablesPlugin = postcss.plugin('postcss-extract-variable
4243
};
4344
});
4445

46+
const getVariableValue = (variables, name, recursiveSeenMap = {}) => {
47+
if (!variables.hasOwnProperty(name)) {
48+
return [`Missing value for variable '${name}'`];
49+
}
50+
51+
// Circular dependency check
52+
if (recursiveSeenMap.hasOwnProperty(name)) {
53+
return [`Found circular dependency in CSS theme variables for '${name}'`];
54+
}
55+
56+
let value = variables[name];
57+
58+
// value is a variable, recursively lookup value
59+
if (value.indexOf('var(--') === 0) {
60+
value = VAR_REGEX.exec(value)[1];
61+
recursiveSeenMap[name] = true;
62+
63+
return getVariableValue(variables, value, recursiveSeenMap);
64+
}
65+
66+
return [null, value];
67+
};
68+
4569
module.exports.replaceThemeVars = postcss.plugin('postcss-replace-theme-vars', (options = {}) => {
4670
const regex = new RegExp(THEME_VAR_PREFIX + '\\((.+?)\\)');
4771
const variables = options.variables;
@@ -52,12 +76,14 @@ module.exports.replaceThemeVars = postcss.plugin('postcss-replace-theme-vars', (
5276
if (!match) return;
5377

5478
const varName = match[1];
79+
const [err, value] = getVariableValue(variables, varName);
5580

56-
if (!variables.hasOwnProperty(varName)) {
57-
console.error(`Missing theme-var '${varName}'`);
81+
if (err) {
82+
console.error(err);
83+
return;
5884
}
5985

60-
decl.value = variables[varName];
86+
decl.value = value;
6187
});
6288
};
6389
});

0 commit comments

Comments
 (0)