From a3ff7c7182ca10671ebbfb422bf4489e604270ed Mon Sep 17 00:00:00 2001 From: adroitwhiz Date: Thu, 7 Jan 2021 18:57:09 -0500 Subject: [PATCH 1/7] Remove measure function As far as I can tell, no public Scratch repository is calling this. --- src/svg-renderer.js | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/src/svg-renderer.js b/src/svg-renderer.js index ea93ee9e..8ccf99ce 100644 --- a/src/svg-renderer.js +++ b/src/svg-renderer.js @@ -61,16 +61,6 @@ class SvgRenderer { return this._canvas; } - /** - * Load an SVG from a string and measure it. - * @param {string} svgString String of SVG data to draw in quirks-mode. - * @return {object} the natural size, in Scratch units, of this SVG. - */ - measure (svgString) { - this.loadString(svgString); - return this._measurements; - } - /** * @return {Array} the natural size, in Scratch units, of this SVG. */ From b9730c7f7b426110083079b47ba3c952e291fabc Mon Sep 17 00:00:00 2001 From: adroitwhiz Date: Thu, 7 Jan 2021 19:19:46 -0500 Subject: [PATCH 2/7] Pass SVG into SvgRenderer "fix SVG" methods This will allow us to make these methods static / move them into a separate "fixup" function --- src/svg-renderer.js | 86 +++++++++++++++++++++++++-------------------- 1 file changed, 47 insertions(+), 39 deletions(-) diff --git a/src/svg-renderer.js b/src/svg-renderer.js index 8ccf99ce..88e2ab65 100644 --- a/src/svg-renderer.js +++ b/src/svg-renderer.js @@ -88,40 +88,42 @@ class SvgRenderer { // Parse string into SVG XML. const parser = new DOMParser(); svgString = fixupSvgString(svgString); - this._svgDom = parser.parseFromString(svgString, 'text/xml'); - if (this._svgDom.childNodes.length < 1 || - this._svgDom.documentElement.localName !== 'svg') { + const svgDom = parser.parseFromString(svgString, 'text/xml'); + if (svgDom.childNodes.length < 1 || + svgDom.documentElement.localName !== 'svg') { throw new Error('Document does not appear to be SVG.'); } - this._svgTag = this._svgDom.documentElement; + const svgTag = svgDom.documentElement; if (fromVersion2) { // Fix gradients. Scratch 2 exports no x2 when x2 = 0, but // SVG default is that x2 is 1. This must be done before // transformStrokeWidths since transformStrokeWidths affects // gradients. - this._transformGradients(); + this._transformGradients(svgTag); } - transformStrokeWidths(this._svgTag, window); - this._transformImages(this._svgTag); + transformStrokeWidths(svgTag, window); + this._transformImages(svgTag); if (fromVersion2) { // Transform all text elements. - this._transformText(); + this._transformText(svgTag); // Transform measurements. - this._transformMeasurements(); + this._transformMeasurements(svgTag); // Fix stroke roundedness. - this._setGradientStrokeRoundedness(); - } else if (!this._svgTag.getAttribute('viewBox')) { + this._setGradientStrokeRoundedness(svgTag); + } else if (!svgTag.getAttribute('viewBox')) { // Renderer expects a view box. - this._transformMeasurements(); - } else if (!this._svgTag.getAttribute('width') || !this._svgTag.getAttribute('height')) { - this._svgTag.setAttribute('width', this._svgTag.viewBox.baseVal.width); - this._svgTag.setAttribute('height', this._svgTag.viewBox.baseVal.height); + this._transformMeasurements(svgTag); + } else if (!svgTag.getAttribute('width') || !svgTag.getAttribute('height')) { + svgTag.setAttribute('width', svgTag.viewBox.baseVal.width); + svgTag.setAttribute('height', svgTag.viewBox.baseVal.height); } + + this._svgDom = svgDom; this._measurements = { - width: this._svgTag.viewBox.baseVal.width, - height: this._svgTag.viewBox.baseVal.height, - x: this._svgTag.viewBox.baseVal.x, - y: this._svgTag.viewBox.baseVal.y + width: svgTag.viewBox.baseVal.width, + height: svgTag.viewBox.baseVal.height, + x: svgTag.viewBox.baseVal.x, + y: svgTag.viewBox.baseVal.y }; } @@ -160,8 +162,9 @@ class SvgRenderer { * 2. Alignment is set to `text-before-edge`. * 3. Line-breaks are converted to explicit elements. * 4. Any required fonts are injected. + * @param {SVGSVGElement} svgTag the SVG tag to apply the transformation to */ - _transformText () { + _transformText (svgTag) { // Collect all text elements into a list. const textElements = []; const collectText = domElement => { @@ -172,8 +175,8 @@ class SvgRenderer { collectText(domElement.childNodes[i]); } }; - collectText(this._svgTag); - convertFonts(this._svgTag); + collectText(svgTag); + convertFonts(svgTag); // For each text element, apply quirks. for (const textElement of textElements) { // Remove x and y attributes - they are not used in Scratch. @@ -224,7 +227,7 @@ class SvgRenderer { } if (textElement.transform.baseVal.numberOfItems === 0) { - const transform = this._svgTag.createSVGTransform(); + const transform = svgTag.createSVGTransform(); textElement.transform.baseVal.appendItem(transform); } @@ -250,10 +253,11 @@ class SvgRenderer { } /** + * @param {SVGElement} svgTag the tag to search within * @param {string} [tagName] svg tag to search for (or collect all elements if not given) - * @return {Array} a list of elements with the given tagname in _svgTag + * @return {Array} a list of elements with the given tagname */ - _collectElements (tagName) { + _collectElements (svgTag, tagName) { const elts = []; const collectElements = domElement => { if ((domElement.localName === tagName || typeof tagName === 'undefined') && domElement.getAttribute) { @@ -263,16 +267,17 @@ class SvgRenderer { collectElements(domElement.childNodes[i]); } }; - collectElements(this._svgTag); + collectElements(svgTag); return elts; } /** * Fix SVGs to comply with SVG spec. Scratch 2 defaults to x2 = 0 when x2 is missing, but * SVG defaults to x2 = 1 when missing. + * @param {SVGSVGElement} svgTag the SVG tag to apply the transformation to */ - _transformGradients () { - const linearGradientElements = this._collectElements('linearGradient'); + _transformGradients (svgTag) { + const linearGradientElements = this._collectElements(svgTag, 'linearGradient'); // For each gradient element, supply x2 if necessary. for (const gradientElement of linearGradientElements) { @@ -285,9 +290,10 @@ class SvgRenderer { /** * Fix SVGs to match appearance in Scratch 2, which used nearest neighbor scaling for bitmaps * within SVGs. + * @param {SVGSVGElement} svgTag the SVG tag to apply the transformation to */ - _transformImages () { - const imageElements = this._collectElements('image'); + _transformImages (svgTag) { + const imageElements = this._collectElements(svgTag, 'image'); // For each image element, set image rendering to pixelated const pixelatedImages = 'image-rendering: optimizespeed; image-rendering: pixelated;'; @@ -335,9 +341,10 @@ class SvgRenderer { /** * Find all instances of a URL-referenced `stroke` in the svg. In 2.0, all gradient strokes * have a round `stroke-linejoin` and `stroke-linecap`... for some reason. + * @param {SVGSVGElement} svgTag the SVG tag to apply the transformation to */ - _setGradientStrokeRoundedness () { - const elements = this._collectElements(); + _setGradientStrokeRoundedness (svgTag) { + const elements = this._collectElements(svgTag); for (const elt of elements) { if (!elt.style) continue; @@ -362,8 +369,9 @@ class SvgRenderer { * attributes and then drawing (Firefox won't draw anything), * or inflating them and then measuring a canvas. But this seems to be * a natural and performant way. + * @param {SVGSVGElement} svgTag the SVG tag to apply the transformation to */ - _transformMeasurements () { + _transformMeasurements (svgTag) { // Append the SVG dom to the document. // This allows us to use `getBBox` on the page, // which returns the full bounding-box of all drawn SVG @@ -373,8 +381,8 @@ class SvgRenderer { // sanitizing is required. This should not affect bounding box calculation. // outerHTML is attribute of Element (and not HTMLElement), so use it instead of // calling serializer or toString() - // NOTE: this._svgTag remains untouched! - const rawValue = this._svgTag.outerHTML; + // NOTE: svgTag remains untouched! + const rawValue = svgTag.outerHTML; const sanitizedValue = DOMPurify.sanitize(rawValue, { // Use SVG profile (no HTML elements) USE_PROFILES: {svg: true}, @@ -405,7 +413,7 @@ class SvgRenderer { if (bbox.width === 0 || bbox.height === 0) { halfStrokeWidth = 0; } else { - halfStrokeWidth = this._findLargestStrokeWidth(this._svgTag) / 2; + halfStrokeWidth = this._findLargestStrokeWidth(svgTag) / 2; } const width = bbox.width + (halfStrokeWidth * 2); const height = bbox.height + (halfStrokeWidth * 2); @@ -413,9 +421,9 @@ class SvgRenderer { const y = bbox.y - halfStrokeWidth; // Set the correct measurements on the SVG tag - this._svgTag.setAttribute('width', width); - this._svgTag.setAttribute('height', height); - this._svgTag.setAttribute('viewBox', + svgTag.setAttribute('width', width); + svgTag.setAttribute('height', height); + svgTag.setAttribute('viewBox', `${x} ${y} ${width} ${height}`); } From 57eb4a8274254ed895eac67d00b5510ebdf9afdf Mon Sep 17 00:00:00 2001 From: adroitwhiz Date: Thu, 7 Jan 2021 19:49:13 -0500 Subject: [PATCH 3/7] Move SVG string fixups/loading into separate file The VM uses the SvgRenderer solely to convert SVGs from version 2. This allows the VM to simply import loadSvgString without bringing in the entire SvgRenderer along with it. The next commit will move toString to a separate file as well, so the VM's dependency on SvgRenderer can be entirely removed. --- src/index.js | 2 + src/load-svg-string.js | 334 +++++++++++++++++++++++++++++++++++++++++ src/svg-renderer.js | 316 +------------------------------------- 3 files changed, 340 insertions(+), 312 deletions(-) create mode 100644 src/load-svg-string.js diff --git a/src/index.js b/src/index.js index d1e4a82b..771824e8 100644 --- a/src/index.js +++ b/src/index.js @@ -1,6 +1,7 @@ const SVGRenderer = require('./svg-renderer'); const BitmapAdapter = require('./bitmap-adapter'); const inlineSvgFonts = require('./font-inliner'); +const loadSvgString = require('./load-svg-string'); const SvgElement = require('./svg-element'); const convertFonts = require('./font-converter'); // /** @@ -11,6 +12,7 @@ module.exports = { BitmapAdapter: BitmapAdapter, convertFonts: convertFonts, inlineSvgFonts: inlineSvgFonts, + loadSvgString: loadSvgString, SvgElement: SvgElement, SVGRenderer: SVGRenderer }; diff --git a/src/load-svg-string.js b/src/load-svg-string.js new file mode 100644 index 00000000..93b6a18c --- /dev/null +++ b/src/load-svg-string.js @@ -0,0 +1,334 @@ +const DOMPurify = require('dompurify'); +const SvgElement = require('./svg-element'); +const convertFonts = require('./font-converter'); +const fixupSvgString = require('./fixup-svg-string'); +const transformStrokeWidths = require('./transform-applier'); + +/** + * @param {SVGElement} svgTag the tag to search within + * @param {string} [tagName] svg tag to search for (or collect all elements if not given) + * @return {Array} a list of elements with the given tagname + */ +const collectElements = (svgTag, tagName) => { + const elts = []; + const collectElementsInner = domElement => { + if ((domElement.localName === tagName || typeof tagName === 'undefined') && domElement.getAttribute) { + elts.push(domElement); + } + for (let i = 0; i < domElement.childNodes.length; i++) { + collectElementsInner(domElement.childNodes[i]); + } + }; + collectElementsInner(svgTag); + return elts; +}; + +/** + * Fix SVGs to comply with SVG spec. Scratch 2 defaults to x2 = 0 when x2 is missing, but + * SVG defaults to x2 = 1 when missing. + * @param {SVGSVGElement} svgTag the SVG tag to apply the transformation to + */ +const transformGradients = svgTag => { + const linearGradientElements = collectElements(svgTag, 'linearGradient'); + + // For each gradient element, supply x2 if necessary. + for (const gradientElement of linearGradientElements) { + if (!gradientElement.getAttribute('x2')) { + gradientElement.setAttribute('x2', '0'); + } + } +}; + +/** + * Fix SVGs to match appearance in Scratch 2, which used nearest neighbor scaling for bitmaps + * within SVGs. + * @param {SVGSVGElement} svgTag the SVG tag to apply the transformation to + */ +const transformImages = svgTag => { + const imageElements = collectElements(svgTag, 'image'); + + // For each image element, set image rendering to pixelated + const pixelatedImages = 'image-rendering: optimizespeed; image-rendering: pixelated;'; + for (const elt of imageElements) { + if (elt.getAttribute('style')) { + elt.setAttribute('style', + `${pixelatedImages} ${elt.getAttribute('style')}`); + } else { + elt.setAttribute('style', pixelatedImages); + } + } +}; + +/** + * Transforms an SVG's text elements for Scratch 2.0 quirks. + * These quirks include: + * 1. `x` and `y` properties are removed/ignored. + * 2. Alignment is set to `text-before-edge`. + * 3. Line-breaks are converted to explicit elements. + * 4. Any required fonts are injected. + * @param {SVGSVGElement} svgTag the SVG tag to apply the transformation to + */ +const transformText = svgTag => { + // Collect all text elements into a list. + const textElements = []; + const collectText = domElement => { + if (domElement.localName === 'text') { + textElements.push(domElement); + } + for (let i = 0; i < domElement.childNodes.length; i++) { + collectText(domElement.childNodes[i]); + } + }; + collectText(svgTag); + convertFonts(svgTag); + // For each text element, apply quirks. + for (const textElement of textElements) { + // Remove x and y attributes - they are not used in Scratch. + textElement.removeAttribute('x'); + textElement.removeAttribute('y'); + // Set text-before-edge alignment: + // Scratch renders all text like this. + textElement.setAttribute('alignment-baseline', 'text-before-edge'); + textElement.setAttribute('xml:space', 'preserve'); + // If there's no font size provided, provide one. + if (!textElement.getAttribute('font-size')) { + textElement.setAttribute('font-size', '18'); + } + let text = textElement.textContent; + + // Fix line breaks in text, which are not natively supported by SVG. + // Only fix if text does not have child tspans. + // @todo this will not work for font sizes with units such as em, percent + // However, text made in scratch 2 should only ever export size 22 font. + const fontSize = parseFloat(textElement.getAttribute('font-size')); + const tx = 2; + let ty = 0; + let spacing = 1.2; + // Try to match the position and spacing of Scratch 2.0's fonts. + // Different fonts seem to use different line spacing. + // Scratch 2 always uses alignment-baseline=text-before-edge + // However, most SVG readers don't support this attribute + // or don't support it alongside use of tspan, so the translations + // here are to make up for that. + if (textElement.getAttribute('font-family') === 'Handwriting') { + spacing = 2; + ty = -11 * fontSize / 22; + } else if (textElement.getAttribute('font-family') === 'Scratch') { + spacing = 0.89; + ty = -3 * fontSize / 22; + } else if (textElement.getAttribute('font-family') === 'Curly') { + spacing = 1.38; + ty = -6 * fontSize / 22; + } else if (textElement.getAttribute('font-family') === 'Marker') { + spacing = 1.45; + ty = -6 * fontSize / 22; + } else if (textElement.getAttribute('font-family') === 'Sans Serif') { + spacing = 1.13; + ty = -3 * fontSize / 22; + } else if (textElement.getAttribute('font-family') === 'Serif') { + spacing = 1.25; + ty = -4 * fontSize / 22; + } + + if (textElement.transform.baseVal.numberOfItems === 0) { + const transform = svgTag.createSVGTransform(); + textElement.transform.baseVal.appendItem(transform); + } + + // Right multiply matrix by a translation of (tx, ty) + const mtx = textElement.transform.baseVal.getItem(0).matrix; + mtx.e += (mtx.a * tx) + (mtx.c * ty); + mtx.f += (mtx.b * tx) + (mtx.d * ty); + + if (text && textElement.childElementCount === 0) { + textElement.textContent = ''; + const lines = text.split('\n'); + text = ''; + for (const line of lines) { + const tspanNode = SvgElement.create('tspan'); + tspanNode.setAttribute('x', '0'); + tspanNode.setAttribute('style', 'white-space: pre'); + tspanNode.setAttribute('dy', `${spacing}em`); + tspanNode.textContent = line ? line : ' '; + textElement.appendChild(tspanNode); + } + } + } +}; + +/** + * Find the largest stroke width in the svg. If a shape has no + * `stroke` property, it has a stroke-width of 0. If it has a `stroke`, + * it is by default a stroke-width of 1. + * This is used to enlarge the computed bounding box, which doesn't take + * stroke width into account. + * @param {SVGSVGElement} rootNode The root SVG node to traverse. + * @return {number} The largest stroke width in the SVG. + */ +const findLargestStrokeWidth = rootNode => { + let largestStrokeWidth = 0; + const collectStrokeWidths = domElement => { + if (domElement.getAttribute) { + if (domElement.getAttribute('stroke')) { + largestStrokeWidth = Math.max(largestStrokeWidth, 1); + } + if (domElement.getAttribute('stroke-width')) { + largestStrokeWidth = Math.max( + largestStrokeWidth, + Number(domElement.getAttribute('stroke-width')) || 0 + ); + } + } + for (let i = 0; i < domElement.childNodes.length; i++) { + collectStrokeWidths(domElement.childNodes[i]); + } + }; + collectStrokeWidths(rootNode); + return largestStrokeWidth; +}; + +/** + * Transform the measurements of the SVG. + * In Scratch 2.0, SVGs are drawn without respect to the width, + * height, and viewBox attribute on the tag. The exporter + * does output these properties - but they appear to be incorrect often. + * To address the incorrect measurements, we append the DOM to the + * document, and then use SVG's native `getBBox` to find the real + * drawn dimensions. This ensures things drawn in negative dimensions, + * outside the given viewBox, etc., are all eventually drawn to the canvas. + * I tried to do this several other ways: stripping the width/height/viewBox + * attributes and then drawing (Firefox won't draw anything), + * or inflating them and then measuring a canvas. But this seems to be + * a natural and performant way. + * @param {SVGSVGElement} svgTag the SVG tag to apply the transformation to + */ +const transformMeasurements = svgTag => { + // Append the SVG dom to the document. + // This allows us to use `getBBox` on the page, + // which returns the full bounding-box of all drawn SVG + // elements, similar to how Scratch 2.0 did measurement. + const svgSpot = document.createElement('span'); + // Since we're adding user-provided SVG to document.body, + // sanitizing is required. This should not affect bounding box calculation. + // outerHTML is attribute of Element (and not HTMLElement), so use it instead of + // calling serializer or toString() + // NOTE: svgTag remains untouched! + const rawValue = svgTag.outerHTML; + const sanitizedValue = DOMPurify.sanitize(rawValue, { + // Use SVG profile (no HTML elements) + USE_PROFILES: {svg: true}, + // Remove some tags that Scratch does not use. + FORBID_TAGS: ['a', 'audio', 'canvas', 'video'], + // Allow data URI in image tags (e.g. SVGs converted from bitmap) + ADD_DATA_URI_TAGS: ['image'] + }); + let bbox; + try { + // Insert sanitized value. + svgSpot.innerHTML = sanitizedValue; + document.body.appendChild(svgSpot); + // Take the bounding box. We have to get elements via svgSpot + // because we added it via innerHTML. + bbox = svgSpot.children[0].getBBox(); + } finally { + // Always destroy the element, even if, for example, getBBox throws. + document.body.removeChild(svgSpot); + } + + // Enlarge the bbox from the largest found stroke width + // This may have false-positives, but at least the bbox will always + // contain the full graphic including strokes. + // If the width or height is zero however, don't enlarge since + // they won't have a stroke width that needs to be enlarged. + let halfStrokeWidth; + if (bbox.width === 0 || bbox.height === 0) { + halfStrokeWidth = 0; + } else { + halfStrokeWidth = findLargestStrokeWidth(svgTag) / 2; + } + const width = bbox.width + (halfStrokeWidth * 2); + const height = bbox.height + (halfStrokeWidth * 2); + const x = bbox.x - halfStrokeWidth; + const y = bbox.y - halfStrokeWidth; + + // Set the correct measurements on the SVG tag + svgTag.setAttribute('width', width); + svgTag.setAttribute('height', height); + svgTag.setAttribute('viewBox', + `${x} ${y} ${width} ${height}`); +}; + +/** + * Find all instances of a URL-referenced `stroke` in the svg. In 2.0, all gradient strokes + * have a round `stroke-linejoin` and `stroke-linecap`... for some reason. + * @param {SVGSVGElement} svgTag the SVG tag to apply the transformation to + */ +const setGradientStrokeRoundedness = svgTag => { + const elements = collectElements(svgTag); + + for (const elt of elements) { + if (!elt.style) continue; + const stroke = elt.style.stroke || elt.getAttribute('stroke'); + if (stroke && stroke.match(/^url\(#.*\)$/)) { + elt.style['stroke-linejoin'] = 'round'; + elt.style['stroke-linecap'] = 'round'; + } + } +}; + +/** + * In-place, convert passed SVG to something consistent that will be rendered the way we want them to be. + * Currently, this will normalize stroke widths (see transform-applier.js) and render all embedded images pixelated. + * The returned SVG will be guaranteed to always have a `width`, `height` and `viewBox`. + * In addition, if the `fromVersion2` parameter is `true`, several "quirks-mode" transformations will be applied which + * mimic Scratch 2.0's SVG rendering. + * @param {SVGSvgElement} svgTag root SVG node to operate upon + * @param {boolean} [fromVersion2] True if we should perform conversion from version 2 to version 3 svg. + */ +const normalizeSvg = (svgTag, fromVersion2) => { + if (fromVersion2) { + // Fix gradients. Scratch 2 exports no x2 when x2 = 0, but + // SVG default is that x2 is 1. This must be done before + // transformStrokeWidths since transformStrokeWidths affects + // gradients. + transformGradients(svgTag); + } + transformStrokeWidths(svgTag, window); + transformImages(svgTag); + if (fromVersion2) { + // Transform all text elements. + transformText(svgTag); + // Transform measurements. + transformMeasurements(svgTag); + // Fix stroke roundedness. + setGradientStrokeRoundedness(svgTag); + } else if (!svgTag.getAttribute('viewBox')) { + // Renderer expects a view box. + transformMeasurements(svgTag); + } else if (!svgTag.getAttribute('width') || !svgTag.getAttribute('height')) { + svgTag.setAttribute('width', svgTag.viewBox.baseVal.width); + svgTag.setAttribute('height', svgTag.viewBox.baseVal.height); + } +}; + +/** + * Load an SVG string and normalize it. All the steps before drawing/measuring. + * @param {!string} svgString String of SVG data to draw in quirks-mode. + * @param {?boolean} fromVersion2 True if we should perform conversion from version 2 to version 3 svg. + * @return {SVGSVGElement} The normalized SVG element. + */ +const loadSvgString = (svgString, fromVersion2) => { + // Parse string into SVG XML. + const parser = new DOMParser(); + svgString = fixupSvgString(svgString); + const svgDom = parser.parseFromString(svgString, 'text/xml'); + if (svgDom.childNodes.length < 1 || + svgDom.documentElement.localName !== 'svg') { + throw new Error('Document does not appear to be SVG.'); + } + const svgTag = svgDom.documentElement; + normalizeSvg(svgTag, fromVersion2); + return svgTag; +}; + +module.exports = loadSvgString; diff --git a/src/svg-renderer.js b/src/svg-renderer.js index 88e2ab65..8cc13364 100644 --- a/src/svg-renderer.js +++ b/src/svg-renderer.js @@ -1,9 +1,5 @@ -const DOMPurify = require('dompurify'); const inlineSvgFonts = require('./font-inliner'); -const SvgElement = require('./svg-element'); -const convertFonts = require('./font-converter'); -const fixupSvgString = require('./fixup-svg-string'); -const transformStrokeWidths = require('./transform-applier'); +const loadSvgString = require('./load-svg-string'); /** * Main quirks-mode SVG rendering code. @@ -84,41 +80,9 @@ class SvgRenderer { loadString (svgString, fromVersion2) { // New svg string invalidates the cached image this._cachedImage = null; + const svgTag = loadSvgString(svgString, fromVersion2); - // Parse string into SVG XML. - const parser = new DOMParser(); - svgString = fixupSvgString(svgString); - const svgDom = parser.parseFromString(svgString, 'text/xml'); - if (svgDom.childNodes.length < 1 || - svgDom.documentElement.localName !== 'svg') { - throw new Error('Document does not appear to be SVG.'); - } - const svgTag = svgDom.documentElement; - if (fromVersion2) { - // Fix gradients. Scratch 2 exports no x2 when x2 = 0, but - // SVG default is that x2 is 1. This must be done before - // transformStrokeWidths since transformStrokeWidths affects - // gradients. - this._transformGradients(svgTag); - } - transformStrokeWidths(svgTag, window); - this._transformImages(svgTag); - if (fromVersion2) { - // Transform all text elements. - this._transformText(svgTag); - // Transform measurements. - this._transformMeasurements(svgTag); - // Fix stroke roundedness. - this._setGradientStrokeRoundedness(svgTag); - } else if (!svgTag.getAttribute('viewBox')) { - // Renderer expects a view box. - this._transformMeasurements(svgTag); - } else if (!svgTag.getAttribute('width') || !svgTag.getAttribute('height')) { - svgTag.setAttribute('width', svgTag.viewBox.baseVal.width); - svgTag.setAttribute('height', svgTag.viewBox.baseVal.height); - } - - this._svgDom = svgDom; + this._svgTag = svgTag; this._measurements = { width: svgTag.viewBox.baseVal.width, height: svgTag.viewBox.baseVal.height, @@ -155,278 +119,6 @@ class SvgRenderer { this.loaded = false; } - /** - * Transforms an SVG's text elements for Scratch 2.0 quirks. - * These quirks include: - * 1. `x` and `y` properties are removed/ignored. - * 2. Alignment is set to `text-before-edge`. - * 3. Line-breaks are converted to explicit elements. - * 4. Any required fonts are injected. - * @param {SVGSVGElement} svgTag the SVG tag to apply the transformation to - */ - _transformText (svgTag) { - // Collect all text elements into a list. - const textElements = []; - const collectText = domElement => { - if (domElement.localName === 'text') { - textElements.push(domElement); - } - for (let i = 0; i < domElement.childNodes.length; i++) { - collectText(domElement.childNodes[i]); - } - }; - collectText(svgTag); - convertFonts(svgTag); - // For each text element, apply quirks. - for (const textElement of textElements) { - // Remove x and y attributes - they are not used in Scratch. - textElement.removeAttribute('x'); - textElement.removeAttribute('y'); - // Set text-before-edge alignment: - // Scratch renders all text like this. - textElement.setAttribute('alignment-baseline', 'text-before-edge'); - textElement.setAttribute('xml:space', 'preserve'); - // If there's no font size provided, provide one. - if (!textElement.getAttribute('font-size')) { - textElement.setAttribute('font-size', '18'); - } - let text = textElement.textContent; - - // Fix line breaks in text, which are not natively supported by SVG. - // Only fix if text does not have child tspans. - // @todo this will not work for font sizes with units such as em, percent - // However, text made in scratch 2 should only ever export size 22 font. - const fontSize = parseFloat(textElement.getAttribute('font-size')); - const tx = 2; - let ty = 0; - let spacing = 1.2; - // Try to match the position and spacing of Scratch 2.0's fonts. - // Different fonts seem to use different line spacing. - // Scratch 2 always uses alignment-baseline=text-before-edge - // However, most SVG readers don't support this attribute - // or don't support it alongside use of tspan, so the translations - // here are to make up for that. - if (textElement.getAttribute('font-family') === 'Handwriting') { - spacing = 2; - ty = -11 * fontSize / 22; - } else if (textElement.getAttribute('font-family') === 'Scratch') { - spacing = 0.89; - ty = -3 * fontSize / 22; - } else if (textElement.getAttribute('font-family') === 'Curly') { - spacing = 1.38; - ty = -6 * fontSize / 22; - } else if (textElement.getAttribute('font-family') === 'Marker') { - spacing = 1.45; - ty = -6 * fontSize / 22; - } else if (textElement.getAttribute('font-family') === 'Sans Serif') { - spacing = 1.13; - ty = -3 * fontSize / 22; - } else if (textElement.getAttribute('font-family') === 'Serif') { - spacing = 1.25; - ty = -4 * fontSize / 22; - } - - if (textElement.transform.baseVal.numberOfItems === 0) { - const transform = svgTag.createSVGTransform(); - textElement.transform.baseVal.appendItem(transform); - } - - // Right multiply matrix by a translation of (tx, ty) - const mtx = textElement.transform.baseVal.getItem(0).matrix; - mtx.e += (mtx.a * tx) + (mtx.c * ty); - mtx.f += (mtx.b * tx) + (mtx.d * ty); - - if (text && textElement.childElementCount === 0) { - textElement.textContent = ''; - const lines = text.split('\n'); - text = ''; - for (const line of lines) { - const tspanNode = SvgElement.create('tspan'); - tspanNode.setAttribute('x', '0'); - tspanNode.setAttribute('style', 'white-space: pre'); - tspanNode.setAttribute('dy', `${spacing}em`); - tspanNode.textContent = line ? line : ' '; - textElement.appendChild(tspanNode); - } - } - } - } - - /** - * @param {SVGElement} svgTag the tag to search within - * @param {string} [tagName] svg tag to search for (or collect all elements if not given) - * @return {Array} a list of elements with the given tagname - */ - _collectElements (svgTag, tagName) { - const elts = []; - const collectElements = domElement => { - if ((domElement.localName === tagName || typeof tagName === 'undefined') && domElement.getAttribute) { - elts.push(domElement); - } - for (let i = 0; i < domElement.childNodes.length; i++) { - collectElements(domElement.childNodes[i]); - } - }; - collectElements(svgTag); - return elts; - } - - /** - * Fix SVGs to comply with SVG spec. Scratch 2 defaults to x2 = 0 when x2 is missing, but - * SVG defaults to x2 = 1 when missing. - * @param {SVGSVGElement} svgTag the SVG tag to apply the transformation to - */ - _transformGradients (svgTag) { - const linearGradientElements = this._collectElements(svgTag, 'linearGradient'); - - // For each gradient element, supply x2 if necessary. - for (const gradientElement of linearGradientElements) { - if (!gradientElement.getAttribute('x2')) { - gradientElement.setAttribute('x2', '0'); - } - } - } - - /** - * Fix SVGs to match appearance in Scratch 2, which used nearest neighbor scaling for bitmaps - * within SVGs. - * @param {SVGSVGElement} svgTag the SVG tag to apply the transformation to - */ - _transformImages (svgTag) { - const imageElements = this._collectElements(svgTag, 'image'); - - // For each image element, set image rendering to pixelated - const pixelatedImages = 'image-rendering: optimizespeed; image-rendering: pixelated;'; - for (const elt of imageElements) { - if (elt.getAttribute('style')) { - elt.setAttribute('style', - `${pixelatedImages} ${elt.getAttribute('style')}`); - } else { - elt.setAttribute('style', pixelatedImages); - } - } - } - - /** - * Find the largest stroke width in the svg. If a shape has no - * `stroke` property, it has a stroke-width of 0. If it has a `stroke`, - * it is by default a stroke-width of 1. - * This is used to enlarge the computed bounding box, which doesn't take - * stroke width into account. - * @param {SVGSVGElement} rootNode The root SVG node to traverse. - * @return {number} The largest stroke width in the SVG. - */ - _findLargestStrokeWidth (rootNode) { - let largestStrokeWidth = 0; - const collectStrokeWidths = domElement => { - if (domElement.getAttribute) { - if (domElement.getAttribute('stroke')) { - largestStrokeWidth = Math.max(largestStrokeWidth, 1); - } - if (domElement.getAttribute('stroke-width')) { - largestStrokeWidth = Math.max( - largestStrokeWidth, - Number(domElement.getAttribute('stroke-width')) || 0 - ); - } - } - for (let i = 0; i < domElement.childNodes.length; i++) { - collectStrokeWidths(domElement.childNodes[i]); - } - }; - collectStrokeWidths(rootNode); - return largestStrokeWidth; - } - - /** - * Find all instances of a URL-referenced `stroke` in the svg. In 2.0, all gradient strokes - * have a round `stroke-linejoin` and `stroke-linecap`... for some reason. - * @param {SVGSVGElement} svgTag the SVG tag to apply the transformation to - */ - _setGradientStrokeRoundedness (svgTag) { - const elements = this._collectElements(svgTag); - - for (const elt of elements) { - if (!elt.style) continue; - const stroke = elt.style.stroke || elt.getAttribute('stroke'); - if (stroke && stroke.match(/^url\(#.*\)$/)) { - elt.style['stroke-linejoin'] = 'round'; - elt.style['stroke-linecap'] = 'round'; - } - } - } - - /** - * Transform the measurements of the SVG. - * In Scratch 2.0, SVGs are drawn without respect to the width, - * height, and viewBox attribute on the tag. The exporter - * does output these properties - but they appear to be incorrect often. - * To address the incorrect measurements, we append the DOM to the - * document, and then use SVG's native `getBBox` to find the real - * drawn dimensions. This ensures things drawn in negative dimensions, - * outside the given viewBox, etc., are all eventually drawn to the canvas. - * I tried to do this several other ways: stripping the width/height/viewBox - * attributes and then drawing (Firefox won't draw anything), - * or inflating them and then measuring a canvas. But this seems to be - * a natural and performant way. - * @param {SVGSVGElement} svgTag the SVG tag to apply the transformation to - */ - _transformMeasurements (svgTag) { - // Append the SVG dom to the document. - // This allows us to use `getBBox` on the page, - // which returns the full bounding-box of all drawn SVG - // elements, similar to how Scratch 2.0 did measurement. - const svgSpot = document.createElement('span'); - // Since we're adding user-provided SVG to document.body, - // sanitizing is required. This should not affect bounding box calculation. - // outerHTML is attribute of Element (and not HTMLElement), so use it instead of - // calling serializer or toString() - // NOTE: svgTag remains untouched! - const rawValue = svgTag.outerHTML; - const sanitizedValue = DOMPurify.sanitize(rawValue, { - // Use SVG profile (no HTML elements) - USE_PROFILES: {svg: true}, - // Remove some tags that Scratch does not use. - FORBID_TAGS: ['a', 'audio', 'canvas', 'video'], - // Allow data URI in image tags (e.g. SVGs converted from bitmap) - ADD_DATA_URI_TAGS: ['image'] - }); - let bbox; - try { - // Insert sanitized value. - svgSpot.innerHTML = sanitizedValue; - document.body.appendChild(svgSpot); - // Take the bounding box. We have to get elements via svgSpot - // because we added it via innerHTML. - bbox = svgSpot.children[0].getBBox(); - } finally { - // Always destroy the element, even if, for example, getBBox throws. - document.body.removeChild(svgSpot); - } - - // Enlarge the bbox from the largest found stroke width - // This may have false-positives, but at least the bbox will always - // contain the full graphic including strokes. - // If the width or height is zero however, don't enlarge since - // they won't have a stroke width that needs to be enlarged. - let halfStrokeWidth; - if (bbox.width === 0 || bbox.height === 0) { - halfStrokeWidth = 0; - } else { - halfStrokeWidth = this._findLargestStrokeWidth(svgTag) / 2; - } - const width = bbox.width + (halfStrokeWidth * 2); - const height = bbox.height + (halfStrokeWidth * 2); - const x = bbox.x - halfStrokeWidth; - const y = bbox.y - halfStrokeWidth; - - // Set the correct measurements on the SVG tag - svgTag.setAttribute('width', width); - svgTag.setAttribute('height', height); - svgTag.setAttribute('viewBox', - `${x} ${y} ${width} ${height}`); - } - /** * Serialize the active SVG DOM to a string. * @param {?boolean} shouldInjectFonts True if fonts should be included in the SVG as @@ -435,7 +127,7 @@ class SvgRenderer { */ toString (shouldInjectFonts) { const serializer = new XMLSerializer(); - let string = serializer.serializeToString(this._svgDom); + let string = serializer.serializeToString(this._svgTag); if (shouldInjectFonts) { string = inlineSvgFonts(string); } From 847329438404b27a4195607062b8b4edbb13a973 Mon Sep 17 00:00:00 2001 From: adroitwhiz Date: Thu, 7 Jan 2021 20:04:37 -0500 Subject: [PATCH 4/7] Split out SVG serialization+quirks-mode conversion I may be going a bit overboard with the exports here. --- src/index.js | 6 +++++- src/serialize-svg-to-string.js | 19 +++++++++++++++++++ src/svg-renderer.js | 10 +++------- src/v2-svg-adapter.js | 9 +++++++++ 4 files changed, 36 insertions(+), 8 deletions(-) create mode 100644 src/serialize-svg-to-string.js create mode 100644 src/v2-svg-adapter.js diff --git a/src/index.js b/src/index.js index 771824e8..7f61ea23 100644 --- a/src/index.js +++ b/src/index.js @@ -2,7 +2,9 @@ const SVGRenderer = require('./svg-renderer'); const BitmapAdapter = require('./bitmap-adapter'); const inlineSvgFonts = require('./font-inliner'); const loadSvgString = require('./load-svg-string'); +const serializeSvgToString = require('./serialize-svg-to-string'); const SvgElement = require('./svg-element'); +const V2SVGAdapter = require('./v2-svg-adapter'); const convertFonts = require('./font-converter'); // /** // * Export for NPM & Node.js @@ -13,6 +15,8 @@ module.exports = { convertFonts: convertFonts, inlineSvgFonts: inlineSvgFonts, loadSvgString: loadSvgString, + serializeSvgToString: serializeSvgToString, SvgElement: SvgElement, - SVGRenderer: SVGRenderer + SVGRenderer: SVGRenderer, + V2SVGAdapter: V2SVGAdapter }; diff --git a/src/serialize-svg-to-string.js b/src/serialize-svg-to-string.js new file mode 100644 index 00000000..defd88aa --- /dev/null +++ b/src/serialize-svg-to-string.js @@ -0,0 +1,19 @@ +const inlineSvgFonts = require('./font-inliner'); + +/** + * Serialize a given SVG DOM to a string. + * @param {SVGSVGElement} svgTag The SVG element to serialize. + * @param {?boolean} shouldInjectFonts True if fonts should be included in the SVG as + * base64 data. + * @returns {string} String representing current SVG data. + */ +const serializeSvgToString = (svgTag, shouldInjectFonts) => { + const serializer = new XMLSerializer(); + let string = serializer.serializeToString(svgTag); + if (shouldInjectFonts) { + string = inlineSvgFonts(string); + } + return string; +}; + +module.exports = serializeSvgToString; diff --git a/src/svg-renderer.js b/src/svg-renderer.js index 8cc13364..2d1666a7 100644 --- a/src/svg-renderer.js +++ b/src/svg-renderer.js @@ -1,5 +1,5 @@ -const inlineSvgFonts = require('./font-inliner'); const loadSvgString = require('./load-svg-string'); +const serializeSvgToString = require('./serialize-svg-to-string'); /** * Main quirks-mode SVG rendering code. @@ -124,14 +124,10 @@ class SvgRenderer { * @param {?boolean} shouldInjectFonts True if fonts should be included in the SVG as * base64 data. * @returns {string} String representing current SVG data. + * @deprecated Use the standalone `serializeSvgToString` export instead. */ toString (shouldInjectFonts) { - const serializer = new XMLSerializer(); - let string = serializer.serializeToString(this._svgTag); - if (shouldInjectFonts) { - string = inlineSvgFonts(string); - } - return string; + return serializeSvgToString(this._svgTag, shouldInjectFonts); } /** diff --git a/src/v2-svg-adapter.js b/src/v2-svg-adapter.js new file mode 100644 index 00000000..48c63c55 --- /dev/null +++ b/src/v2-svg-adapter.js @@ -0,0 +1,9 @@ +const loadSvgString = require('./load-svg-string'); +const serializeSvgToString = require('./serialize-svg-to-string'); + +/** + * Convert a version 2 SVG (Scratch 2.0 "quirks mode") to a version 3 svg (complies with normal SVG standards). + * @param {string} svgString the SVG string to convert from version 2 SVG. + * @returns {string} the converted SVG string. + */ +module.exports = svgString => serializeSvgToString(loadSvgString(svgString, true /* fromVersion2 */)); From 9b85dd3e564d65f1b8939b69f04c93ac802d4477 Mon Sep 17 00:00:00 2001 From: adroitwhiz Date: Thu, 7 Jan 2021 21:13:51 -0500 Subject: [PATCH 5/7] Deprecate SvgRenderer --- src/svg-renderer.js | 1 + 1 file changed, 1 insertion(+) diff --git a/src/svg-renderer.js b/src/svg-renderer.js index 2d1666a7..9561949f 100644 --- a/src/svg-renderer.js +++ b/src/svg-renderer.js @@ -3,6 +3,7 @@ const serializeSvgToString = require('./serialize-svg-to-string'); /** * Main quirks-mode SVG rendering code. + * @deprecated Call into individual methods exported from this library instead. */ class SvgRenderer { /** From 51c80da661d109e3dfb53eccf83fe58eb568c62c Mon Sep 17 00:00:00 2001 From: adroitwhiz Date: Thu, 11 Feb 2021 18:04:36 -0500 Subject: [PATCH 6/7] Move loadSvgString "normalize" docs to public API The details of what "normalizing" an SVG does should be easily viewable to those using the publicly exported `loadSvgString` function. --- src/load-svg-string.js | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/load-svg-string.js b/src/load-svg-string.js index 93b6a18c..c1383355 100644 --- a/src/load-svg-string.js +++ b/src/load-svg-string.js @@ -278,10 +278,6 @@ const setGradientStrokeRoundedness = svgTag => { /** * In-place, convert passed SVG to something consistent that will be rendered the way we want them to be. - * Currently, this will normalize stroke widths (see transform-applier.js) and render all embedded images pixelated. - * The returned SVG will be guaranteed to always have a `width`, `height` and `viewBox`. - * In addition, if the `fromVersion2` parameter is `true`, several "quirks-mode" transformations will be applied which - * mimic Scratch 2.0's SVG rendering. * @param {SVGSvgElement} svgTag root SVG node to operate upon * @param {boolean} [fromVersion2] True if we should perform conversion from version 2 to version 3 svg. */ @@ -313,8 +309,12 @@ const normalizeSvg = (svgTag, fromVersion2) => { /** * Load an SVG string and normalize it. All the steps before drawing/measuring. + * Currently, this will normalize stroke widths (see transform-applier.js) and render all embedded images pixelated. + * The returned SVG will be guaranteed to always have a `width`, `height` and `viewBox`. + * In addition, if the `fromVersion2` parameter is `true`, several "quirks-mode" transformations will be applied which + * mimic Scratch 2.0's SVG rendering. * @param {!string} svgString String of SVG data to draw in quirks-mode. - * @param {?boolean} fromVersion2 True if we should perform conversion from version 2 to version 3 svg. + * @param {boolean} [fromVersion2] True if we should perform conversion from version 2 to version 3 svg. * @return {SVGSVGElement} The normalized SVG element. */ const loadSvgString = (svgString, fromVersion2) => { From 5997a426f3f810c1345267b2a5fb5d8b7b96d1b9 Mon Sep 17 00:00:00 2001 From: adroitwhiz Date: Mon, 22 Feb 2021 18:12:12 -0500 Subject: [PATCH 7/7] Remove V2SVGAdapter --- src/index.js | 4 +--- src/v2-svg-adapter.js | 9 --------- 2 files changed, 1 insertion(+), 12 deletions(-) delete mode 100644 src/v2-svg-adapter.js diff --git a/src/index.js b/src/index.js index 7f61ea23..060a3235 100644 --- a/src/index.js +++ b/src/index.js @@ -4,7 +4,6 @@ const inlineSvgFonts = require('./font-inliner'); const loadSvgString = require('./load-svg-string'); const serializeSvgToString = require('./serialize-svg-to-string'); const SvgElement = require('./svg-element'); -const V2SVGAdapter = require('./v2-svg-adapter'); const convertFonts = require('./font-converter'); // /** // * Export for NPM & Node.js @@ -17,6 +16,5 @@ module.exports = { loadSvgString: loadSvgString, serializeSvgToString: serializeSvgToString, SvgElement: SvgElement, - SVGRenderer: SVGRenderer, - V2SVGAdapter: V2SVGAdapter + SVGRenderer: SVGRenderer }; diff --git a/src/v2-svg-adapter.js b/src/v2-svg-adapter.js deleted file mode 100644 index 48c63c55..00000000 --- a/src/v2-svg-adapter.js +++ /dev/null @@ -1,9 +0,0 @@ -const loadSvgString = require('./load-svg-string'); -const serializeSvgToString = require('./serialize-svg-to-string'); - -/** - * Convert a version 2 SVG (Scratch 2.0 "quirks mode") to a version 3 svg (complies with normal SVG standards). - * @param {string} svgString the SVG string to convert from version 2 SVG. - * @returns {string} the converted SVG string. - */ -module.exports = svgString => serializeSvgToString(loadSvgString(svgString, true /* fromVersion2 */));