Support SVG strings with leading line-breaks

Closes #1813
This commit is contained in:
Jürg Lehni 2020-05-23 13:40:07 +02:00
parent ccd92acee7
commit 5631279f99
2 changed files with 20 additions and 4 deletions

View file

@ -662,8 +662,12 @@ new function() {
function onLoad(svg) { function onLoad(svg) {
try { try {
var node = typeof svg === 'object' ? svg : new self.DOMParser() var node = typeof svg === 'object'
.parseFromString(svg, 'image/svg+xml'); ? svg
: new self.DOMParser().parseFromString(
svg,
'image/svg+xml'
);
if (!node.nodeName) { if (!node.nodeName) {
node = null; node = null;
throw new Error('Unsupported SVG source: ' + source); throw new Error('Unsupported SVG source: ' + source);
@ -693,8 +697,10 @@ new function() {
// Have the group not pass on all transformations to its children, // Have the group not pass on all transformations to its children,
// as this is how SVG works too. // as this is how SVG works too.
// See if it's a string but handle markup separately // See if it's a string but handle markup separately, using `[\s\S]` to
if (typeof source === 'string' && !/^.*</.test(source)) { // also match the first tag if it only starts on the second line in a
// multi-line string.
if (typeof source === 'string' && !/^[\s\S]*</.test(source)) {
// First see if we're meant to import an element with the given // First see if we're meant to import an element with the given
// id. // id.
var node = document.getElementById(source); var node = document.getElementById(source);

View file

@ -158,6 +158,16 @@ test('Import SVG switch', function(assert) {
}); });
}); });
test('Import SVG string with leading line-breaks', function() {
var svg = '\n<svg xmlns="http://www.w3.org/2000/svg">\n <rect fill="red" width="100" height="100"/>\n</svg>\n'
var imported = paper.project.importSVG(svg);
equals(imported.children.length, 1);
equals(imported.firstChild, new Shape.Rectangle({
size: [100, 100],
fillColor: 'red'
}));
});
function importSVG(assert, url, message, options) { function importSVG(assert, url, message, options) {
var done = assert.async(); var done = assert.async();
project.importSVG(url, { project.importSVG(url, {