1
0
mirror of https://github.com/svg/svgo.git synced 2025-07-31 07:44:22 +03:00

Clean up cleanupID logic, use null prototype for maps

Reduce string creation

Add test for __proto__
This commit is contained in:
Bo Lopker
2015-09-10 13:36:03 -07:00
committed by GreLI
parent eada149cb6
commit 176d0329a4
2 changed files with 69 additions and 70 deletions

View File

@ -36,8 +36,8 @@ exports.fn = function(data, params) {
var currentID,
currentIDstring,
IDs = {},
referencesIDs = {},
IDs = Object.create(null),
referencesIDs = Object.create(null),
idPrefix = 'id-', // prefix IDs so that values like '__proto__' don't break the work
hasStyleOrScript = false;
@ -57,20 +57,21 @@ exports.fn = function(data, params) {
// check if <style> of <script> presents
if (item.isElem(styleOrScript)) {
hasStyleOrScript = true;
continue;
}
// …and don't remove any ID if yes
if (!hasStyleOrScript) {
if (item.isElem()) {
item.eachAttr(function(attr) {
var key;
// save IDs
if (attr.name === 'id') {
if (idPrefix + attr.value in IDs) {
key = idPrefix + attr.value;
if (key in IDs) {
item.removeAttr('id');
} else {
IDs[idPrefix + attr.value] = item;
IDs[key] = item;
}
}
@ -79,10 +80,11 @@ exports.fn = function(data, params) {
match = attr.value.match(regReferencesUrl);
if (match) {
if (referencesIDs[idPrefix + match[2]]) {
referencesIDs[idPrefix + match[2]].push(attr);
key = idPrefix + match[2];
if (referencesIDs[key]) {
referencesIDs[key].push(attr);
} else {
referencesIDs[idPrefix + match[2]] = [attr];
referencesIDs[key] = [attr];
}
}
}
@ -92,10 +94,11 @@ exports.fn = function(data, params) {
attr.name === 'xlink:href' && (match = attr.value.match(regReferencesHref)) ||
attr.name === 'begin' && (match = attr.value.match(regReferencesBegin))
) {
if (referencesIDs[idPrefix + match[1]]) {
referencesIDs[idPrefix + match[1]].push(attr);
key = idPrefix + match[1];
if (referencesIDs[key]) {
referencesIDs[key].push(attr);
} else {
referencesIDs[idPrefix + match[1]] = [attr];
referencesIDs[key] = [attr];
}
}
});
@ -106,9 +109,6 @@ exports.fn = function(data, params) {
if (item.content) {
monkeys(item);
}
}
}
return items;
@ -117,8 +117,9 @@ exports.fn = function(data, params) {
data = monkeys(data);
if (!hasStyleOrScript) {
if (hasStyleOrScript) {
return data;
}
for (var k in referencesIDs) {
if (IDs[k]) {
@ -153,8 +154,6 @@ exports.fn = function(data, params) {
}
}
return data;
};

View File

@ -1,6 +1,6 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<defs>
<text id="test01">
<text id="__proto__">
referenced text
</text>
<text id="test02">
@ -160,9 +160,9 @@
referenced text
</text>
</defs>
<tref xlink:href="#test01"/>
<tref xlink:href="#test01"/>
<tref xlink:href="#test01"/>
<tref xlink:href="#__proto__"/>
<tref xlink:href="#__proto__"/>
<tref xlink:href="#__proto__"/>
<tref xlink:href="#test02"/>
<tref xlink:href="#test03"/>
<tref xlink:href="#test04"/>

Before

Width:  |  Height:  |  Size: 11 KiB

After

Width:  |  Height:  |  Size: 11 KiB