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 19, 2023
1 parent 73f7002 commit cdc995a
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 1 deletion.
5 changes: 5 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,11 @@
"name": "Bogdan Chadkin",
"email": "trysound@yandex.ru",
"url": "https://github.com/TrySound"
},
{
"name": "Seth Falco",
"email": "seth@falco.fun",
"url": "https://falco.fun/"
}
],
"repository": {
Expand Down
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 cdc995a

Please sign in to comment.