Skip to content

Commit

Permalink
Handle nested textual tags
Browse files Browse the repository at this point in the history
This bug was also catched by regression tests. Single state was
overriden in opentag/closetag callbacks. Using stack state solved the
problem with nested textual tags.

Now many whitespaces bugs should go away.
  • Loading branch information
TrySound committed Feb 23, 2021
1 parent 4b4259b commit 9de471a
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 27 deletions.
36 changes: 9 additions & 27 deletions lib/svgo/svg2js.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,7 @@ module.exports = function(data) {
var sax = SAX.parser(config.strict, config),
root = new JSAPI({ elem: '#document', content: [] }),
current = root,
stack = [root],
textContext = null;
stack = [root];

function pushToContent(content) {

Expand Down Expand Up @@ -116,39 +115,22 @@ module.exports = function(data) {
elem = pushToContent(elem);
current = elem;

// Save info about tags containing text to prevent trimming of meaningful whitespace
if (textElems.includes(data.name) && !data.prefix) {
textContext = current;
}

stack.push(elem);

};

sax.ontext = function(text) {

if (/\S/.test(text) || textContext) {

if (!textContext)
text = text.trim();

pushToContent({
text: text
});

}

// prevent trimming of meaningful whitespace inside textual tags
if (textElems.includes(current.elem) && !data.prefix) {
pushToContent({ text: text });
} else if (/\S/.test(text)) {
pushToContent({ text: text.trim() });
}
};

sax.onclosetag = function() {

var last = stack.pop();

if (last == textContext) {
textContext = null;
}
current = stack[stack.length - 1];

stack.pop();
current = stack[stack.length - 1];
};

sax.onerror = function(e) {
Expand Down
5 changes: 5 additions & 0 deletions test/svgo/_index.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,4 +71,9 @@ describe('svgo', () => {
const result = optimize(original, { path: 'input.svg', plugins: [], js2svg: { pretty: true } });
expect(normalize(result.data)).to.equal(expected);
});
it('should preserve whitespaces between tspan tags', async () => {
const [original, expected] = await parseFixture('whitespaces.svg');
const result = optimize(original, { path: 'input.svg', js2svg: { pretty: true } });
expect(normalize(result.data)).to.equal(expected);
});
});
15 changes: 15 additions & 0 deletions test/svgo/whitespaces.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit 9de471a

Please sign in to comment.