From a2f1ddddb555671f02113c0804e086277062cc77 Mon Sep 17 00:00:00 2001 From: Jonas Hermsmeier Date: Mon, 7 Aug 2017 16:29:30 +0200 Subject: [PATCH] fix(svg-icon): Handle DOMParser parsererrors (#1663) This checks for `parsererror`s in the DOMParser's returned document, to prevent re-use of the previous image and avoid displaying an error document in the SVG icon slot. Change-Type: patch Changelog-Entry: Avoid "broken" icon when selecting a zip image archive with invalid SVG. --- lib/gui/components/svg-icon.js | 10 ++++++---- tests/gui/components/svg-icon.spec.js | 11 +++++++++++ 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/lib/gui/components/svg-icon.js b/lib/gui/components/svg-icon.js index 6739e42f..a0a65699 100644 --- a/lib/gui/components/svg-icon.js +++ b/lib/gui/components/svg-icon.js @@ -35,6 +35,8 @@ const angularSVGIcon = angular.module(MODULE_NAME, []) const DEFAULT_SIZE = '40px' +const domParser = new window.DOMParser() + /** * @summary SVG element that takes both filepaths and file contents * @type {Object} @@ -65,11 +67,11 @@ class SVGIcon extends react.Component { const width = this.props.width || DEFAULT_SIZE const height = this.props.height || DEFAULT_SIZE - const parser = new window.DOMParser() - const doc = parser.parseFromString(contents, 'image/svg+xml') + const doc = domParser.parseFromString(contents, 'image/svg+xml') + const parserError = doc.querySelector('parsererror') const svg = doc.querySelector('svg') - - const svgData = `data:image/svg+xml,${encodeURIComponent(svg.outerHTML)}` + const svgXml = svg && _.isNil(parserError) ? svg.outerHTML : '' + const svgData = `data:image/svg+xml,${encodeURIComponent(svgXml)}` return react.createElement('img', { className: 'svg-icon', diff --git a/tests/gui/components/svg-icon.spec.js b/tests/gui/components/svg-icon.spec.js index 3f4ccd06..5274f7ce 100644 --- a/tests/gui/components/svg-icon.spec.js +++ b/tests/gui/components/svg-icon.spec.js @@ -72,6 +72,17 @@ describe('Browser: SVGIcon', function () { m.chai.expect(element.children().attr('src')).to.equal(imgData) }) + it('should use an empty src if there is a parsererror', function () { + // The following is invalid, because there's no closing tag for `foreignObject` + const iconContents = '' + const imgData = `data:image/svg+xml,` + $rootScope.iconContents = iconContents + + const element = $compile('Resin.io')($rootScope) + $rootScope.$digest() + m.chai.expect(element.children().attr('src')).to.equal(imgData) + }) + it('should default the size to 40x40 pixels', function () { const icon = '../../../lib/gui/assets/etcher.svg' const element = $compile(`Resin.io`)($rootScope)