|
1 | 1 | const postcss = require('postcss'); |
2 | 2 | const fs = require('fs'); |
| 3 | +const path = require('path'); |
| 4 | + |
| 5 | +function extractCssVars(cssFilePath, processedFiles = new Set()) { |
| 6 | + // avoid infinite recursion by tracking processed files |
| 7 | + const absolutePath = path.resolve(cssFilePath); |
| 8 | + if (processedFiles.has(absolutePath)) { |
| 9 | + return {}; |
| 10 | + } |
| 11 | + processedFiles.add(absolutePath); |
3 | 12 |
|
4 | | -function extractCssVars(cssFilePath) { |
5 | 13 | const cssContent = fs.readFileSync(cssFilePath, 'utf8'); |
6 | 14 | const root = postcss.parse(cssContent); |
7 | | - const vars = {}; |
| 15 | + let vars = {}; |
| 16 | + |
| 17 | + // process @import rules first |
| 18 | + root.walkAtRules('import', (rule) => { |
| 19 | + let importPath = rule.params.replace(/['"]/g, ''); // remove quotes |
| 20 | + |
| 21 | + // handle url() syntax |
| 22 | + if (importPath.startsWith('url(')) { |
| 23 | + importPath = importPath.slice(4, -1).replace(/['"]/g, ''); |
| 24 | + } |
| 25 | + |
| 26 | + // resolve relative paths |
| 27 | + if (!path.isAbsolute(importPath)) { |
| 28 | + importPath = path.resolve(path.dirname(cssFilePath), importPath); |
| 29 | + } |
8 | 30 |
|
| 31 | + // check if file exists before trying to process it |
| 32 | + if (fs.existsSync(importPath)) { |
| 33 | + const importedVars = extractCssVars(importPath, processedFiles); |
| 34 | + vars = mergeVars(vars, importedVars); |
| 35 | + } |
| 36 | + }); |
| 37 | + |
| 38 | + // process css variables in this file |
9 | 39 | root.walkRules((rule) => { |
10 | 40 | if (rule.selector === ':root') { |
11 | 41 | rule.walkDecls((decl) => { |
@@ -38,6 +68,18 @@ function extractCssVars(cssFilePath) { |
38 | 68 | return vars; |
39 | 69 | } |
40 | 70 |
|
| 71 | +function mergeVars(target, source) { |
| 72 | + for (const [key, value] of Object.entries(source)) { |
| 73 | + if (typeof value === 'object' && !Array.isArray(value)) { |
| 74 | + if (!target[key]) target[key] = {}; |
| 75 | + target[key] = { ...target[key], ...value }; |
| 76 | + } else { |
| 77 | + target[key] = value; |
| 78 | + } |
| 79 | + } |
| 80 | + return target; |
| 81 | +} |
| 82 | + |
41 | 83 | const cssVars = extractCssVars('./resources/scripts/blueprint/css/BlueprintStylesheet.css'); |
42 | 84 |
|
43 | 85 | module.exports = { |
|
0 commit comments