1 | const fs = require('fs');
|
2 | const slateConfig = require('@shopify/slate-config');
|
3 |
|
4 | const config = require('./slate-cssvar-loader.config');
|
5 |
|
6 | const STYLE_BLOCK_REGEX = /(?:<style>|\{% style %\})([\S\s]*?)(?:<\/style>|\{% endstyle %\})/g;
|
7 | const CSS_VAR_FUNC_REGEX = /var\(--(.*?)\)/g;
|
8 | const CSS_VAR_DECL_REGEX = /--(.*?):\s*(\{\{\s*.*?\s*\}\}.*?);/g;
|
9 |
|
10 | class SlateException {
|
11 | constructor(message) {
|
12 | this.message = message;
|
13 | this.name = 'SlateException';
|
14 | }
|
15 | }
|
16 |
|
17 | function parseCSSVariables(cssVariablesPaths) {
|
18 | const variables = {};
|
19 | let styleBlock;
|
20 | cssVariablesPaths.forEach(cssVariablesPath => {
|
21 | const themeFilePath = slateConfig.resolveTheme(cssVariablesPath);
|
22 | const content = fs.readFileSync(themeFilePath, 'utf8');
|
23 | while ((styleBlock = STYLE_BLOCK_REGEX.exec(content)) != null) {
|
24 | let cssVariableDecl;
|
25 | while ((cssVariableDecl = CSS_VAR_DECL_REGEX.exec(styleBlock)) != null) {
|
26 | const [, cssVariable, liquidVariable] = cssVariableDecl;
|
27 | variables[cssVariable] = escapeLiquidVariable(liquidVariable);
|
28 | }
|
29 | }
|
30 | });
|
31 | return variables;
|
32 | }
|
33 |
|
34 | function escapeLiquidVariable(variable) {
|
35 | return variable.replace(/"/g, '\\"');
|
36 | }
|
37 |
|
38 | function SlateCSSLoader(source) {
|
39 | if (!config.cssVarLoaderEnable) {
|
40 | return source;
|
41 | }
|
42 |
|
43 | const cssVariablesPaths = config.cssVarLoaderLiquidPath;
|
44 |
|
45 | cssVariablesPaths.forEach(filePath => this.addDependency(filePath));
|
46 | const variables = parseCSSVariables(cssVariablesPaths);
|
47 |
|
48 | const result = source.replace(CSS_VAR_FUNC_REGEX, (match, cssVariable) => {
|
49 | if (!variables[cssVariable]) {
|
50 | throw new SlateException(
|
51 | `Liquid variable not found for CSS variable ${cssVariable}`,
|
52 | );
|
53 | }
|
54 | return variables[cssVariable];
|
55 | });
|
56 |
|
57 | return result;
|
58 | }
|
59 |
|
60 | module.exports = SlateCSSLoader;
|