Skip to content

Commit 9de471a

Browse files
committed
Handle nested textual tags
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.
1 parent 4b4259b commit 9de471a

File tree

3 files changed

+29
-27
lines changed

3 files changed

+29
-27
lines changed

lib/svgo/svg2js.js

+9-27
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,7 @@ module.exports = function(data) {
2626
var sax = SAX.parser(config.strict, config),
2727
root = new JSAPI({ elem: '#document', content: [] }),
2828
current = root,
29-
stack = [root],
30-
textContext = null;
29+
stack = [root];
3130

3231
function pushToContent(content) {
3332

@@ -116,39 +115,22 @@ module.exports = function(data) {
116115
elem = pushToContent(elem);
117116
current = elem;
118117

119-
// Save info about tags containing text to prevent trimming of meaningful whitespace
120-
if (textElems.includes(data.name) && !data.prefix) {
121-
textContext = current;
122-
}
123-
124118
stack.push(elem);
125119

126120
};
127121

128122
sax.ontext = function(text) {
129-
130-
if (/\S/.test(text) || textContext) {
131-
132-
if (!textContext)
133-
text = text.trim();
134-
135-
pushToContent({
136-
text: text
137-
});
138-
139-
}
140-
123+
// prevent trimming of meaningful whitespace inside textual tags
124+
if (textElems.includes(current.elem) && !data.prefix) {
125+
pushToContent({ text: text });
126+
} else if (/\S/.test(text)) {
127+
pushToContent({ text: text.trim() });
128+
}
141129
};
142130

143131
sax.onclosetag = function() {
144-
145-
var last = stack.pop();
146-
147-
if (last == textContext) {
148-
textContext = null;
149-
}
150-
current = stack[stack.length - 1];
151-
132+
stack.pop();
133+
current = stack[stack.length - 1];
152134
};
153135

154136
sax.onerror = function(e) {

test/svgo/_index.js

+5
Original file line numberDiff line numberDiff line change
@@ -71,4 +71,9 @@ describe('svgo', () => {
7171
const result = optimize(original, { path: 'input.svg', plugins: [], js2svg: { pretty: true } });
7272
expect(normalize(result.data)).to.equal(expected);
7373
});
74+
it('should preserve whitespaces between tspan tags', async () => {
75+
const [original, expected] = await parseFixture('whitespaces.svg');
76+
const result = optimize(original, { path: 'input.svg', js2svg: { pretty: true } });
77+
expect(normalize(result.data)).to.equal(expected);
78+
});
7479
});

test/svgo/whitespaces.svg

+15
Loading

0 commit comments

Comments
 (0)