Skip to content

Commit

Permalink
fix(reusePaths): dont reuse id if referenced in href
Browse files Browse the repository at this point in the history
  • Loading branch information
SethFalco committed Sep 23, 2023
1 parent 59ab80e commit 0c6f798
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 1 deletion.
21 changes: 20 additions & 1 deletion plugins/reusePaths.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,13 @@ exports.fn = () => {
*/
const paths = new Map();

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

return {
element: {
enter: (node) => {
Expand All @@ -41,12 +48,23 @@ exports.fn = () => {
}
list.push(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}
* @see https://developer.mozilla.org/en-US/docs/Web/SVG/Element/defs
*/
const defsTag = {
type: 'element',
Expand Down Expand Up @@ -74,7 +92,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.04.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 0c6f798

Please sign in to comment.