Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add reuseDefs plugin #1776

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions docs/03-plugins/reuse-defs.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
---
title: Reuse Defs
svgo:
pluginId: reuseDefs
---


It looks for `<defs>` children that have same [`attributes`](https://developer.mozilla.org/docs/Web/SVG/Attribute) values and children, remove the duplicated one and replace references of the removed element.

:::

## Usage

<PluginUsage/>

## Demo

<PluginDemo/>

## Implementation

* https://github.com/svg/svgo/blob/main/plugins/reuseDefs.js
1 change: 1 addition & 0 deletions lib/builtin.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ exports.builtin = [
require('../plugins/removeXlink.js'),
require('../plugins/removeXMLNS.js'),
require('../plugins/removeXMLProcInst.js'),
require('../plugins/reuseDefs.js'),
require('../plugins/reusePaths.js'),
require('../plugins/sortAttrs.js'),
require('../plugins/sortDefsChildren.js'),
Expand Down
1 change: 1 addition & 0 deletions plugins/plugins-types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,7 @@ export type BuiltinsWithOptionalParams = DefaultPlugins & {
includeLegacy: boolean
};
removeXMLNS: void;
reuseDefs: void;
reusePaths: void;
};

Expand Down
130 changes: 130 additions & 0 deletions plugins/reuseDefs.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
'use strict';

/**
* @typedef {import('../lib/types').XastElement} XastElement
* @typedef {import('../lib/types').XastChild} XastChild
* @typedef {import('../lib/types').XastParent} XastParent
* @typedef {import('../lib/types').XastNode} XastNode
*/

const { referencesProps } = require('./_collections');
exports.name = 'reuseDefs';
exports.description =
'Find duplicated def elements, delete them' +
' and replace references by the id left';

const regReferencesUrl = /\burl\((["'])?#(.+?)\1\)/g;
const regReferencesHref = /^#(.+?)$/;
const regReferencesBegin = /(\D+)\./;

/**
* Find duplicated def elements, delete them
* and replace references by the id left.
*
* @author Sahel LUCAS--SAOUDI
*
* @type {import('./plugins-types').Plugin<'reuseDefs'>}
*/
exports.fn = () => {
/**
* @type {Array<XastElement>}
*/
const defsChildren = [];
/**
* @type {Map<string, string>}
*/
const defsReused = new Map();
/**
* @type {Map<string, Array<{element: XastElement, name: string, value: string }>>}
*/
const referencesById = new Map();

return {
element: {
enter: (node, parentNode) => {
if (parentNode.type !== 'root' && parentNode.name === 'defs' && node.attributes.id) {
const sameDef = defsChildren.find((def) => def.name === node.name
&& JSON.stringify({ ...def.attributes, id: undefined }) ===
JSON.stringify({ ...node.attributes, id: undefined })
&& JSON.stringify(def.children) ===
JSON.stringify(node.children)
);

if (!sameDef) {
defsChildren.push(node);
} else {
defsReused.set(node.attributes.id, sameDef.attributes.id);
// delete child
parentNode.children = parentNode.children.filter((c) => c !== node);
}
}

// collect all references
for (const [name, value] of Object.entries(node.attributes)) {
/**
* @type {string[]}
*/
let ids = [];
if (referencesProps.includes(name)) {
const matches = value.matchAll(regReferencesUrl);
for (const match of matches) {
ids.push(match[2]); // url() reference
}
}
if (name === 'href' || name.endsWith(':href')) {
const match = value.match(regReferencesHref);
if (match != null) {
ids.push(match[1]); // href reference
}
}
if (name === 'begin') {
const match = value.match(regReferencesBegin);
if (match != null) {
ids.push(match[1]); // begin reference
}
}
for (const id of ids) {
let refs = referencesById.get(id);
if (refs == null) {
refs = [];
referencesById.set(id, refs);
}
refs.push({ element: node, name, value });
}
}
},

exit: (node, parentNode) => {
// remove empty defs node
if (node.name === 'defs' && node.children.length === 0) {
parentNode.children = parentNode.children.filter((c) => c !== node);
}
},
},
root: {
exit: () => {
// Replace references to reused defs
for (const [id, refs] of referencesById.entries()) {
const reusedId = defsReused.get(id);
if (reusedId) {
for (const ref of refs) {
if (ref.value.includes('#')) {
// replace id in href and url()
ref.element.attributes[ref.name] = ref.value.replace(
`#${id}`,
`#${reusedId}`
);
} else {
// replace id in begin attribute
ref.element.attributes[ref.name] = ref.value.replace(
`${id}.`,
`${reusedId}.`
);
}
}
}
}
},
},
};
};
26 changes: 26 additions & 0 deletions test/plugins/reuseDefs.01.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
43 changes: 43 additions & 0 deletions test/plugins/reuseDefs.02.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
38 changes: 38 additions & 0 deletions test/plugins/reuseDefs.03.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
38 changes: 38 additions & 0 deletions test/plugins/reuseDefs.04.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.