Skip to content

Commit

Permalink
fix: reuse defs tag in reusePaths
Browse files Browse the repository at this point in the history
  • Loading branch information
SethFalco committed Sep 20, 2023
1 parent 73f7002 commit 5f01e36
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 13 deletions.
51 changes: 38 additions & 13 deletions plugins/reusePaths.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,18 @@ exports.fn = () => {
*/
const paths = new Map();

/**
* Reference to the first defs element that is a direct child of the svg
* element if one exists.
*
* @type {XastElement}
* @see https://developer.mozilla.org/en-US/docs/Web/SVG/Element/defs
*/
let svgDefs;

return {
element: {
enter: (node) => {
enter: (node, parentNode) => {
if (node.name === 'path' && node.attributes.d != null) {
const d = node.attributes.d;
const fill = node.attributes.fill || '';
Expand All @@ -41,24 +50,37 @@ exports.fn = () => {
}
list.push(node);
}

if (svgDefs == null &&
node.name === 'defs' &&
parentNode.type === 'element' &&
parentNode.name === 'svg'
) {
svgDefs = node;
}
},

exit: (node, parentNode) => {
if (node.name === 'svg' && parentNode.type === 'root') {
/**
* @type {XastElement}
*/
const defsTag = {
type: 'element',
name: 'defs',
attributes: {},
children: [],
};
// TODO remove legacy parentNode in v4
Object.defineProperty(defsTag, 'parentNode', {
writable: true,
value: node,
});
let defsTag = svgDefs;

if (defsTag == null) {
defsTag = {
type: 'element',
name: 'defs',
attributes: {},
children: [],
};
// TODO remove legacy parentNode in v4
Object.defineProperty(defsTag, 'parentNode', {
writable: true,
value: node,
});
}

let index = 0;
for (const list of paths.values()) {
if (list.length > 1) {
Expand Down Expand Up @@ -102,7 +124,10 @@ exports.fn = () => {
if (node.attributes['xmlns:xlink'] == null) {
node.attributes['xmlns:xlink'] = 'http://www.w3.org/1999/xlink';
}
node.children.unshift(defsTag);

if (svgDefs == null) {
node.children.unshift(defsTag);
}
}
}
},
Expand Down
23 changes: 23 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 5f01e36

Please sign in to comment.