Skip to content

Commit

Permalink
fix(reusePaths): dont reuse id if referenced in href (#1784)
Browse files Browse the repository at this point in the history
Fixes a bug where the reusePaths plugin would reuse the node ID that
it's optimizing, but that ID was also referenced in a href elsewhere
in the document, so it unintentionally applied the path to other nodes.
  • Loading branch information
SethFalco authored Sep 23, 2023
1 parent 5f40d8b commit bd750ce
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 4 deletions.
23 changes: 19 additions & 4 deletions plugins/reusePaths.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,13 @@ exports.fn = () => {
*/
let svgDefs;

/**
* Set of hrefs that reference the id of another node.
*
* @type {Set<string>}
*/
const hrefs = new Set();

return {
element: {
enter: (node, parentNode) => {
Expand All @@ -61,13 +68,20 @@ exports.fn = () => {
) {
svgDefs = node;
}

if (node.name === 'use') {
for (const name of ['href', 'xlink:href']) {
const href = node.attributes[name];

if (href != null && href.startsWith('#') && href.length > 1) {
hrefs.add(href.slice(1));
}
}
}
},

exit: (node, parentNode) => {
if (node.name === 'svg' && parentNode.type === 'root') {
/**
* @type {XastElement}
*/
let defsTag = svgDefs;

if (defsTag == null) {
Expand Down Expand Up @@ -99,7 +113,8 @@ exports.fn = () => {
};
delete reusablePath.attributes.transform;
let id;
if (reusablePath.attributes.id == null) {
const reusablePathId = reusablePath.attributes.id;
if (reusablePathId == null || hrefs.has(reusablePathId)) {
id = 'reuse-' + index;
index += 1;
reusablePath.attributes.id = id;
Expand Down
40 changes: 40 additions & 0 deletions test/plugins/reusePaths.06.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 bd750ce

Please sign in to comment.