Skip to content
Draft
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
33 changes: 33 additions & 0 deletions lib/svgo.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -369,6 +369,39 @@ test('multipass option should trigger plugins multiple times', () => {
expect(data).toBe(`<svg id="klmnopqrstuvwxyz"/>`);
});

test('cleanupAttrs handles numeric attribute values', () => {
const svg = `<svg xmlns="http://www.w3.org/2000/svg"><rect width="10" height="10"/></svg>`;
/** @type {import('./types.js').CustomPlugin} */
const addNumericDimensions = {
name: 'addNumericDimensions',
fn: () => ({
element: {
enter: (node) => {
if (
node.name === 'svg' &&
node.attributes.width == null &&
node.attributes.height == null &&
node.attributes.viewBox == null
) {
// @ts-expect-error regression test for non-string attribute values
node.attributes.width = 0;
// @ts-expect-error regression test for non-string attribute values
node.attributes.height = 0;
}
},
},
}),
};

const { data } = optimize(svg, {
plugins: [addNumericDimensions, 'cleanupAttrs'],
});

expect(data).toBe(
'<svg xmlns="http://www.w3.org/2000/svg" width="0" height="0"><rect width="10" height="10"/></svg>',
);
});

test('encode as datauri', () => {
const input = `
<svg xmlns="http://www.w3.org/2000/svg">
Expand Down
24 changes: 14 additions & 10 deletions plugins/cleanupAttrs.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,27 +25,31 @@ export const fn = (root, params) => {
element: {
enter: (node) => {
for (const name of Object.keys(node.attributes)) {
const value = node.attributes[name];
if (value === undefined) {
continue;
}

let attrValue =
value === null ? '' : typeof value === 'string' ? value : String(value);

if (newlines) {
// new line which requires a space instead
node.attributes[name] = node.attributes[name].replace(
attrValue = attrValue.replace(
regNewlinesNeedSpace,
(match, p1, p2) => p1 + ' ' + p2,
);
// simple new line
node.attributes[name] = node.attributes[name].replace(
regNewlines,
'',
);
attrValue = attrValue.replace(regNewlines, '');
}
if (trim) {
node.attributes[name] = node.attributes[name].trim();
attrValue = attrValue.trim();
}
if (spaces) {
node.attributes[name] = node.attributes[name].replace(
regSpaces,
' ',
);
attrValue = attrValue.replace(regSpaces, ' ');
}

node.attributes[name] = attrValue;
}
},
},
Expand Down