Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor svg2js to use txml #1301

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
276 changes: 165 additions & 111 deletions lib/svgo/svg2js.js
Original file line number Diff line number Diff line change
@@ -1,130 +1,184 @@
'use strict';

const SAX = require('@trysound/sax');
const JSAPI = require('./jsAPI.js');
const { textElems } = require('../../plugins/_collections.js');

const entityDeclaration = /<!ENTITY\s+(\S+)\s+(?:'([^']+)'|"([^"]+)")\s*>/g;

const config = {
strict: true,
trim: false,
normalize: false,
lowercase: true,
xmlns: true,
position: true,
};
var txml = require('txml'),
JSAPI = require('./jsAPI.js'),
entityDeclaration = /<!ENTITY\s+(\S+)\s+(?:'([^']+)'|"([^"]+)")\s*>/g;

/**
* Convert SVG (XML) string to SVG-as-JS object.
*
* @param {String} data input data
*/
module.exports = function (data) {
const sax = SAX.parser(config.strict, config);
const root = new JSAPI({ type: 'root', children: [] });
let current = root;
let stack = [root];

function pushToContent(node) {
const wrapped = new JSAPI(node, current);
current.children.push(wrapped);
return wrapped;
}

sax.ondoctype = function (doctype) {
pushToContent({
type: 'doctype',
// TODO parse doctype for name, public and system to match xast
name: 'svg',
data: {
doctype,
},
});

const subsetStart = doctype.indexOf('[');
let entityMatch;

if (subsetStart >= 0) {
entityDeclaration.lastIndex = subsetStart;

while ((entityMatch = entityDeclaration.exec(data)) != null) {
sax.ENTITIES[entityMatch[1]] = entityMatch[2] || entityMatch[3];
}
try {
var DOM = txml.parse(data, {
noChildNodes: ['?xml', '!DOCTYPE', '!ENTITY'],
keepComments: true,
keepWhitespace: true,
});

return dom2js(DOM);
} catch (err) {
return { error: 'Error in parsing SVG: ' + err.message };
}
};

sax.onprocessinginstruction = function (data) {
pushToContent({
type: 'instruction',
name: data.name,
value: data.body,
});
};

sax.oncomment = function (comment) {
pushToContent({
type: 'comment',
value: comment.trim(),
});
};
};

sax.oncdata = function (cdata) {
pushToContent({
type: 'cdata',
value: cdata,
/**
*
* @param {(txml.INode | string)[]} dom
*/
function dom2js(dom, root, ENTITIES) {
if (!root) root = new JSAPI({ type: 'root', children: [] });
if (!ENTITIES) ENTITIES = {};
if (!Array.isArray(dom)) return dom
dom.forEach(n => {
var text;
if (typeof n === 'object') {
let child;
if (n.tagName[0] === '?') {
child = pushToContent({
type: 'instruction',
name: n.tagName.substr(1),
value: Object.keys(n.attributes).map(name => name + '=' + JSON.stringify(n.attributes[name])).join(' '),
}, root)
} else {
var elem = {
type: 'element',
name: n.tagName,
attributes: n.attributes || {},
children: [],
};

Object.keys(n.attributes).forEach(name => {
if (name.startsWith('xmlns:')) {
n.attributes[name] = ENTITIES[n.attributes[name].substr(1, n.attributes[name].length - 2)] || n.attributes[name];
}
let prefix = name.includes(':') ? name.split(':')[0] : '';

if (prefix === 'xmlns'
&& n.attributes[name].startsWith('&')
&& n.attributes[name].endsWith(';')
&& ENTITIES[n.attributes[name].substr(1, n.attributes[name].length - 2)]
) {
elem.attributes[name] = ENTITIES[n.attributes[name].substr(1, n.attributes[name].length - 2)];
} else {
elem.attributes[name] = n.attributes[name];
}
});

child = pushToContent(elem, root);
}

if (n.children) {
dom2js(n.children, child, ENTITIES)
}
} else if (typeof n === 'string') {
if (n.startsWith('<!--') && n.endsWith('-->')) {
pushToContent({
type: 'comment',
value: n.substring(4, n.length - 3).trim()
}, root);
} else if (n.startsWith('!DOCTYPE')) {
const data = n.substr(8);
pushToContent({
type: 'doctype',
name: 'svg',
data: { doctype: data },
}, root);

var subsetStart = data.indexOf('[');

if (subsetStart >= 0) {
entityDeclaration.lastIndex = subsetStart;
var entryLines = data.split('<!ENTITY ');
entryLines.shift();
entryLines = entryLines
.map(el => el.split('>'))
.map(list => {
list.pop();
return list.join('>');
})
.map(el => el.split(' '));

entryLines.forEach(([name, ...rest]) => {
try {
ENTITIES[name] = JSON.parse(rest.join(' '))
} catch (err) {
console.log('---->', rest)
}
});
}
} else if (n.includes('<![CDATA[') && n.includes(']]>')) {
text = n.substring(n.indexOf('<![CDATA[') + 9, n.lastIndexOf(']]>'));
if (text) pushToContent({ type: 'cdata', value: text }, root);
} else {
text = decodeEntities(n);

if (
text.trim().startsWith('&')
&& text.trim().endsWith(';')
&& ENTITIES[text.trim().substr(1, text.trim().length - 2)]
) {
const replacement = txml.parse(ENTITIES[text.trim().substr(1, text.trim().length - 2)]);
dom2js(replacement, root, ENTITIES)
}
else if (textElems.includes(root.name)) {
pushToContent({
type: 'text',
value: text,
}, root);
} else if (/\S/.test(text)) {
pushToContent({
type: 'text',
value: text.trim(),
}, root);
}
}
} else {
pushToContent(n, root);
}
});
};

sax.onopentag = function (data) {
var element = {
type: 'element',
name: data.name,
attributes: {},
children: [],
};

for (const [name, attr] of Object.entries(data.attributes)) {
element.attributes[name] = attr.value;
}

element = pushToContent(element);
current = element;

stack.push(element);
};

sax.ontext = function (text) {
// prevent trimming of meaningful whitespace inside textual tags
if (textElems.includes(current.name) && !data.prefix) {
pushToContent({
type: 'text',
value: text,
});
} else if (/\S/.test(text)) {
pushToContent({
type: 'text',
value: text.trim(),
});
}
};
return root;
}

sax.onclosetag = function () {
stack.pop();
current = stack[stack.length - 1];
};
function pushToContent(node, current) {
const wrapped = new JSAPI(node, current);
current.children.push(wrapped);
return wrapped;
}

const ALPHA_INDEX = {
'&lt': '<',
'&gt': '>',
'&quot': '"',
'&apos': '\'',
'&amp': '&',
'&lt;': '<',
'&gt;': '>',
'&quot;': '"',
'&apos;': '\'',
'&amp;': '&'
};

sax.onerror = function (e) {
e.message = 'Error in parsing SVG: ' + e.message;
if (e.message.indexOf('Unexpected end') < 0) {
throw e;
function decodeEntities(str) {
if (!str || !str.length) {
return '';
}
};

try {
sax.write(data).close();
return root;
} catch (e) {
return { error: e.message };
}
};
return str.replace(/&#?[0-9a-zA-Z]+;?/g, function (s) {
if (s.charAt(1) === '#') {
const code = s.charAt(2).toLowerCase() === 'x' ?
parseInt(s.substr(3), 16) :
parseInt(s.substr(2));

if (isNaN(code) || code < -32768 || code > 65535) {
return '';
}
return String.fromCharCode(code);
}
return ALPHA_INDEX[s] || s;
});
}
28 changes: 20 additions & 8 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,8 @@
"css-select": "^3.1.2",
"css-tree": "^1.1.2",
"csso": "^4.2.0",
"stable": "^0.1.8"
"stable": "^0.1.8",
"txml": "^4.0.1"
},
"devDependencies": {
"@rollup/plugin-commonjs": "^17.1.0",
Expand Down