From dd276b92f7225d25df961e385ca1022358eea0c5 Mon Sep 17 00:00:00 2001 From: Paul Kaplan Date: Thu, 29 Mar 2018 10:51:38 -0400 Subject: [PATCH] Export and import SVGs with multiline text --- src/svg/SvgExport.js | 15 +++++++++++++-- src/svg/SvgImport.js | 25 +++++++++++++++++++++---- 2 files changed, 34 insertions(+), 6 deletions(-) diff --git a/src/svg/SvgExport.js b/src/svg/SvgExport.js index 382a49e5..0eaa6194 100644 --- a/src/svg/SvgExport.js +++ b/src/svg/SvgExport.js @@ -253,9 +253,20 @@ new function() { } function exportText(item) { - var node = SvgElement.create('text', getTransform(item._matrix, true), + // Scratch-specific: do not use x/y attributes for text elements + // because they break mutliline formatting (below) + var node = SvgElement.create('text', getTransform(item._matrix, false), formatter); - node.textContent = item._content; + for (var i = 0; i < item._lines.length; i++) { + // Scratch-specific: Use for multiline text, + // right now only supports left justified (x=0) + var tspanNode = SvgElement.create('tspan', { + x: '0', + dy: i === 0 ? '0' : item._style.getLeading() + 'px' + }, formatter); + tspanNode.textContent = item._lines[i]; + node.appendChild(tspanNode); + } return node; } diff --git a/src/svg/SvgImport.js b/src/svg/SvgImport.js index 539283bf..3830c2ef 100644 --- a/src/svg/SvgImport.js +++ b/src/svg/SvgImport.js @@ -300,10 +300,27 @@ new function() { // TODO: Support for these is missing in Paper.js right now // rotate: character rotation // lengthAdjust: - var text = new PointText(getPoint(node).add( - getPoint(node, 'dx', 'dy'))); - text.setContent(node.textContent.trim() || ''); - return text; + + // Scratch-specific: Do not use x/y attributes because they break multiline usage. + if (node.childElementCount === 0) { + var text = new PointText(); + text.setContent(node.textContent.trim() || ''); + // Scratch-specific: Scratch2 SVGs are offset by 1 leading vertically. + // Scratch3 SVGs use method for all text (below) + text.translate(0, text._style.getLeading()); + return text; + } else { + // Scratch3 SVGs always use 's for multiline string support. + // Does not support x/y attribute or tspan positioning beyond left justified. + var lines = []; + for (var i = 0; i < node.children.length; i++) { + var child = node.children[i]; + lines.push(child.textContent); + } + var text = new PointText(); + text.setContent(lines.join('\n') || ''); + return text; + } } };