From cd4fce0c6ff94b53b58d820f16c8b46597535fe3 Mon Sep 17 00:00:00 2001 From: RMidhunSuresh Date: Sat, 2 Apr 2022 23:09:20 +0530 Subject: [PATCH] Populate shared map with collected icons --- scripts/postcss/css-url-to-variables.js | 18 ++++++++++++++++++ .../postcss/tests/css-url-to-variables.test.js | 16 ++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/scripts/postcss/css-url-to-variables.js b/scripts/postcss/css-url-to-variables.js index 2a2937c0..ddc65bed 100644 --- a/scripts/postcss/css-url-to-variables.js +++ b/scripts/postcss/css-url-to-variables.js @@ -53,6 +53,19 @@ function addResolvedVariablesToRootSelector(root, { Rule, Declaration }) { root.append(newRule); } +function populateMapWithDerivedVariables(map, cssFileLocation) { + const location = cssFileLocation.match(/(.+)\/.+\.css/)?.[1]; + if (map.has(location)) { + /** + * This postcss plugin is going to run on all theme variants of a single theme. + * But we only really need to populate the map once since theme variants only differ + * by the values of the base-variables and we don't care about values here. + */ + return; + } + map.set(location, { "icon": Object.fromEntries(urlVariables) }); +} + /* * * @type {import('postcss').PluginCreator} */ @@ -67,6 +80,11 @@ module.exports = (opts = {}) => { if (urlVariables.size) { addResolvedVariablesToRootSelector(root, { Rule, Declaration }); } + if (opts.compiledVariables){ + const cssFileLocation = root.source.input.from; + populateMapWithDerivedVariables(opts.compiledVariables, cssFileLocation); + } + console.log(opts.compiledVariables); }, }; }; diff --git a/scripts/postcss/tests/css-url-to-variables.test.js b/scripts/postcss/tests/css-url-to-variables.test.js index cc7d9cd2..e298599d 100644 --- a/scripts/postcss/tests/css-url-to-variables.test.js +++ b/scripts/postcss/tests/css-url-to-variables.test.js @@ -16,6 +16,7 @@ limitations under the License. const plugin = require("../css-url-to-variables"); const run = require("./common").createTestRunner(plugin); +const postcss = require("postcss"); module.exports.tests = function tests() { return { @@ -46,6 +47,21 @@ module.exports.tests = function tests() { background: no-repeat url("./img/foo/bar/image.png"); }`; await run(inputCSS, inputCSS, {}, assert); + }, + "map is populated with icons": async (assert) => { + const compiledVariables = new Map(); + const inputCSS = `div { + background: no-repeat center/80% url("../img/image.svg?primary=main-color--darker-20"); + } + button { + background: url("/home/foo/bar/cool.svg?primary=blue&secondary=green"); + }`; + const expectedObject = { + "icon-url-0": "../img/image.svg?primary=main-color--darker-20", + "icon-url-1": "/home/foo/bar/cool.svg?primary=blue&secondary=green", + }; + await postcss([plugin({compiledVariables})]).process(inputCSS, { from: "/foo/bar/test.css", }); + assert.deepEqual(expectedObject, compiledVariables.get("/foo/bar")["icon"]); } }; };