svgo-browser
Version:
svgo tool for browser and node usage
176 lines (142 loc) • 3.98 kB
JavaScript
const SAX = require('sax');
const JSAPI = require('./jsAPI.js');
const CSSClassList = require('./css-class-list');
const CSSStyleDeclaration = require('./css-style-declaration');
const entityDeclaration = / tag to prevent trimming of meaningful whitespace
if (data.name == 'text' && !data.prefix) {
textContext = current;
}
stack.push(elem);
};
sax.ontext = function (text) {
if (/\S/.test(text) || textContext) {
if (!textContext) text = text.trim();
pushToContent({
text,
});
}
};
sax.onclosetag = function () {
const last = stack.pop();
// Trim text inside <text> tag.
if (last == textContext) {
trim(textContext);
textContext = null;
}
current = stack[stack.length - 1];
};
sax.onerror = function (e) {
e.message = `Error in parsing SVG: ${e.message}`;
if (e.message.indexOf('Unexpected end') < 0) {
throw e;
}
};
sax.onend = function () {
if (!this.error) {
callback(root);
} else {
callback({ error: this.error.message });
}
};
try {
sax.write(data);
} catch (e) {
callback({ error: e.message });
parsingError = true;
}
if (!parsingError) sax.close();
function trim(elem) {
if (!elem.content) return elem;
let start = elem.content[0];
let end = elem.content[elem.content.length - 1];
while (start && start.content && !start.text) start = start.content[0];
if (start && start.text) start.text = start.text.replace(/^\s+/, '');
while (end && end.content && !end.text) end = end.content[end.content.length - 1];
if (end && end.text) end.text = end.text.replace(/\s+$/, '');
return elem;
}
};