Skip to content

Commit

Permalink
refactor(postcss-svgo): always warn on invalid SVG
Browse files Browse the repository at this point in the history
Handle all SVGO failures in the same way, as there
is no practical difference between being unable to parse
and being unable to optimise.
  • Loading branch information
ludofischer committed Apr 2, 2021
1 parent 22d2a18 commit fc8a52a
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 14 deletions.
14 changes: 8 additions & 6 deletions packages/postcss-svgo/src/__tests__/index.js
@@ -1,4 +1,5 @@
import { readFileSync as file } from 'fs';
import postcss from 'postcss';
import filters from 'pleeease-filters';
import { extendDefaultPlugins } from 'svgo';
import plugin from '../';
Expand Down Expand Up @@ -189,12 +190,13 @@ test(
)
);

test(
'should skip svgs containing unclosed tags',
passthroughCSS(
'h1{background:url(data:image/svg+xml;charset=utf-8,<svg>style type="text/css"><![CDATA[ svg { fill: red; } ]]></style></svg>)}'
)
);
test('should warn on SVG containing unclosed tags', async () => {
const css =
'h1{background:url(data:image/svg+xml;charset=utf-8,<svg>style type="text/css"><![CDATA[ svg { fill: red; } ]]></style></svg>)}';
const result = await postcss(plugin()).process(css, { from: undefined });
expect(result.messages.length).toBe(1);
expect(result.messages[0].type).toBe('warning');
});

test(
'should pass through links to svg files',
Expand Down
15 changes: 7 additions & 8 deletions packages/postcss-svgo/src/index.js
Expand Up @@ -6,7 +6,7 @@ const PLUGIN = 'postcss-svgo';
const dataURI = /data:image\/svg\+xml(;((charset=)?utf-8|base64))?,/i;
const dataURIBase64 = /data:image\/svg\+xml;base64,/i;

function minify(decl, opts) {
function minify(decl, opts, postcssResult) {
const parsed = valueParser(decl.value);

decl.value = parsed.walk((node) => {
Expand Down Expand Up @@ -51,13 +51,12 @@ function minify(decl, opts) {
try {
result = optimize(svg, opts);
if (result.error) {
if (result.error.startsWith('Error in parsing SVG')) {
return;
}
throw new Error(`${PLUGIN}: ${result.error}`);
decl.warn(postcssResult, `${result.error}`);
return;
}
} catch (error) {
throw new Error(`${PLUGIN}: ${error}`);
decl.warn(postcssResult, `${error}`);
return;
}
let data, optimizedValue;

Expand Down Expand Up @@ -92,13 +91,13 @@ function pluginCreator(opts = {}) {
return {
postcssPlugin: PLUGIN,

OnceExit(css) {
OnceExit(css, { result }) {
css.walkDecls((decl) => {
if (!dataURI.test(decl.value)) {
return;
}

minify(decl, opts);
minify(decl, opts, result);
});
},
};
Expand Down

0 comments on commit fc8a52a

Please sign in to comment.