Skip to content

Commit

Permalink
fix(reusePaths): remove duplicate/redundant defs
Browse files Browse the repository at this point in the history
  • Loading branch information
SethFalco committed Sep 20, 2023
1 parent 86880fb commit 75cabf7
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 2 deletions.
31 changes: 29 additions & 2 deletions plugins/reusePaths.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
'use strict';

const { detachNodeFromParent, querySelectorAll } = require('../lib/xast');

/**
* @typedef {import('../lib/types').XastElement} XastElement
* @typedef {import('../lib/types').XastParent} XastParent
Expand Down Expand Up @@ -113,11 +115,36 @@ exports.fn = () => {
defsTag.children.push(reusablePath);
// convert paths to <use>
for (const pathNode of list) {
pathNode.name = 'use';
pathNode.attributes['xlink:href'] = '#' + id;
delete pathNode.attributes.d;
delete pathNode.attributes.stroke;
delete pathNode.attributes.fill;

if (
defsTag.children.includes(pathNode) &&
pathNode.children.length === 0
) {
if (Object.keys(pathNode.attributes).length === 0) {
detachNodeFromParent(pathNode, defsTag);
continue;
}

if (
Object.keys(pathNode.attributes).length === 1 &&
pathNode.attributes.id != null
) {
detachNodeFromParent(pathNode, defsTag);
const selector = `[xlink\\:href=#${pathNode.attributes.id}]`;
for (const child of querySelectorAll(node, selector)) {
if (child.type === 'element') {
child.attributes['xlink:href'] = '#' + id;
}
}
continue;
}
}

pathNode.name = 'use';
pathNode.attributes['xlink:href'] = '#' + id;
}
}
}
Expand Down
33 changes: 33 additions & 0 deletions test/plugins/reusePaths.05.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 75cabf7

Please sign in to comment.