Merge pull request #717 from vector-im/fix-css-url-processor

Theming - Fix css-url-processor
This commit is contained in:
R Midhun Suresh 2022-04-13 14:19:36 +05:30 committed by GitHub
commit b76fb70579
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 17 additions and 2 deletions

View File

@ -16,6 +16,7 @@ limitations under the License.
const valueParser = require("postcss-value-parser");
const resolve = require("path").resolve;
let cssPath;
function colorsFromURL(url, colorMap) {
const params = new URL(`file://${url}`).searchParams;
@ -44,7 +45,6 @@ function processURL(decl, replacer, colorMap) {
}
const urlStringNode = node.nodes[0];
const oldURL = urlStringNode.value;
const cssPath = decl.source?.input.file.replace(/[^/]*$/, "");
const oldURLAbsolute = resolve(cssPath, oldURL);
const colors = colorsFromURL(oldURLAbsolute, colorMap);
if (!colors) {
@ -68,6 +68,11 @@ module.exports = (opts = {}) => {
postcssPlugin: "postcss-url-to-variable",
Once(root, {result}) {
const cssFileLocation = root.source.input.from;
if (cssFileLocation.includes("type=runtime")) {
// If this is a runtime theme, don't process urls.
return;
}
/*
postcss-compile-variables should have sent the list of resolved colours down via results
*/
@ -79,6 +84,7 @@ module.exports = (opts = {}) => {
Go through each declaration and if it contains an URL, replace the url with the result
of running replacer(url)
*/
cssPath = root.source?.input.file.replace(/[^/]*$/, "");
root.walkDecls(decl => processURL(decl, opts.replacer, colorMap));
},
};

View File

@ -16,6 +16,14 @@ limitations under the License.
const fs = require("fs");
const path = require("path");
const xxhash = require('xxhashjs');
function createHash(content) {
const hasher = new xxhash.h32(0);
hasher.update(content);
return hasher.digest();
}
/**
* Builds a new svg with the colors replaced and returns its location.
* @param {string} svgLocation The location of the input svg file
@ -30,6 +38,7 @@ module.exports.buildColorizedSVG = function (svgLocation, primaryColor, secondar
throw new Error("svg-colorizer made no color replacements! The input svg should only contain colors #ff00ff (primary, case-sensitive) and #00ffff (secondary, case-sensitive).");
}
const fileName = svgLocation.match(/.+\/(.+\.svg)/)[1];
const outputName = `${fileName.substring(0, fileName.length - 4)}-${createHash(coloredSVGCode)}.svg`;
const outputPath = path.resolve(__dirname, "../../.tmp");
try {
fs.mkdirSync(outputPath);
@ -39,7 +48,7 @@ module.exports.buildColorizedSVG = function (svgLocation, primaryColor, secondar
throw e;
}
}
const outputFile = `${outputPath}/${fileName}`;
const outputFile = `${outputPath}/${outputName}`;
fs.writeFileSync(outputFile, coloredSVGCode);
return outputFile;
}