Skip to content

Commit

Permalink
feat(addClassesToSVGElement): allow function as param (svg#1966)
Browse files Browse the repository at this point in the history
Updates the interface for addClassesToSVGElement to match prefixIds,
where we'll accept Array<string|function> instead of just a string.
  • Loading branch information
SethFalco authored Mar 1, 2024
1 parent f49b6a7 commit 53aad59
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 5 deletions.
10 changes: 7 additions & 3 deletions plugins/addClassesToSVGElement.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,9 @@ plugins: [
*
* @type {import('./plugins-types.js').Plugin<'addClassesToSVGElement'>}
*/
export const fn = (root, params) => {
export const fn = (root, params, info) => {
if (
!(Array.isArray(params.classNames) && params.classNames.some(String)) &&
!(Array.isArray(params.classNames) && params.classNames.length !== 0) &&
!params.className
) {
console.error(ENOCLS);
Expand All @@ -69,7 +69,11 @@ export const fn = (root, params) => {
);
for (const className of classNames) {
if (className != null) {
classList.add(className);
const classToAdd =
typeof className === 'string'
? className
: className(node, info);
classList.add(classToAdd);
}
}
node.attributes.class = Array.from(classList).join(' ');
Expand Down
6 changes: 4 additions & 2 deletions plugins/plugins-types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -273,8 +273,10 @@ export type BuiltinsWithRequiredParams = {
attributes?: Array<string | Record<string, null | string>>;
};
addClassesToSVGElement: {
className?: string;
classNames?: string[];
className?: string | ((node: XastElement, info: PluginInfo) => string);
classNames?: Array<
string | ((node: XastElement, info: PluginInfo) => string)
>;
};
removeAttributesBySelector: any;
removeAttrs: {
Expand Down
36 changes: 36 additions & 0 deletions test/plugins/addClassesToSVGElement.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { optimize } from '../../lib/svgo.js';

test('should accept function as className parameter', () => {
const svg = `<svg xmlns="http://www.w3.org/2000/svg"/>`;

expect(
optimize(svg, {
path: 'uwu.svg',
plugins: [
{
name: 'addClassesToSVGElement',
params: {
classNames: [
'icon',
(_, info) => `icon__${info?.path?.split('.')[0]}`,
],
},
},
],
}).data,
).toBe(`<svg xmlns="http://www.w3.org/2000/svg" class="icon icon__uwu"/>`);

expect(
optimize(svg, {
path: 'uwu.svg',
plugins: [
{
name: 'addClassesToSVGElement',
params: {
className: (_, info) => `icon__${info?.path?.split('.')[0]}`,
},
},
],
}).data,
).toBe(`<svg xmlns="http://www.w3.org/2000/svg" class="icon__uwu"/>`);
});

0 comments on commit 53aad59

Please sign in to comment.