diff --git a/scripts/postcss/css-url-to-variables.js b/scripts/postcss/css-url-to-variables.js index 1d4666f4..82ddae82 100644 --- a/scripts/postcss/css-url-to-variables.js +++ b/scripts/postcss/css-url-to-variables.js @@ -20,11 +20,9 @@ const valueParser = require("postcss-value-parser"); * This plugin extracts content inside url() into css variables and adds the variables to the root section. * This plugin is used in conjunction with css-url-processor plugin to colorize svg icons. */ -let counter; -let urlVariables; const idToPrepend = "icon-url"; -function findAndReplaceUrl(decl) { +function findAndReplaceUrl(decl, urlVariables, counter) { const value = decl.value; const parsed = valueParser(value); parsed.walk(node => { @@ -35,7 +33,8 @@ function findAndReplaceUrl(decl) { if (!url.match(/\.svg\?primary=.+/)) { return; } - const variableName = `${idToPrepend}-${counter++}`; + const count = counter.next().value; + const variableName = `${idToPrepend}-${count}`; urlVariables.set(variableName, url); node.value = "var"; node.nodes = [{ type: "word", value: `--${variableName}` }]; @@ -43,7 +42,7 @@ function findAndReplaceUrl(decl) { decl.assign({prop: decl.prop, value: parsed.toString()}) } -function addResolvedVariablesToRootSelector(root, { Rule, Declaration }) { +function addResolvedVariablesToRootSelector(root, { Rule, Declaration }, urlVariables) { const newRule = new Rule({ selector: ":root", source: root.source }); // Add derived css variables to :root urlVariables.forEach((value, key) => { @@ -53,29 +52,35 @@ function addResolvedVariablesToRootSelector(root, { Rule, Declaration }) { root.append(newRule); } -function populateMapWithIcons(map, cssFileLocation) { +function populateMapWithIcons(map, cssFileLocation, urlVariables) { const location = cssFileLocation.match(/(.+)\/.+\.css/)?.[1]; const sharedObject = map.get(location); sharedObject["icon"] = Object.fromEntries(urlVariables); } +function *createCounter() { + for (let i = 0; ; ++i) { + yield i; + } +} + /* * * @type {import('postcss').PluginCreator} */ module.exports = (opts = {}) => { - urlVariables = new Map(); - counter = 0; return { postcssPlugin: "postcss-url-to-variable", Once(root, { Rule, Declaration }) { - root.walkDecls(decl => findAndReplaceUrl(decl)); + const urlVariables = new Map(); + const counter = createCounter(); + root.walkDecls(decl => findAndReplaceUrl(decl, urlVariables, counter)); if (urlVariables.size) { - addResolvedVariablesToRootSelector(root, { Rule, Declaration }); + addResolvedVariablesToRootSelector(root, { Rule, Declaration }, urlVariables); } if (opts.compiledVariables){ const cssFileLocation = root.source.input.from; - populateMapWithIcons(opts.compiledVariables, cssFileLocation); + populateMapWithIcons(opts.compiledVariables, cssFileLocation, urlVariables); } }, };