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

Rewrite removeHiddenElems #37

Merged
merged 26 commits into from
Oct 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
124f09a
Rewrite removeHiddenElems.
johnkenny54 Oct 4, 2024
dbcbd68
Second draft.
johnkenny54 Oct 4, 2024
01879c8
Add loop detection.
johnkenny54 Oct 4, 2024
718f2d7
Fixed reference check.
johnkenny54 Oct 4, 2024
808606b
Remove unreferenced <defs> children.
johnkenny54 Oct 4, 2024
5d67997
Remove elements with display=none.
johnkenny54 Oct 4, 2024
8e3ab16
Restored test files.
johnkenny54 Oct 4, 2024
c3808a7
Remove elements with opacity=0.
johnkenny54 Oct 4, 2024
c594401
Delete <rect> with 0 width or height.
johnkenny54 Oct 5, 2024
f14cae4
Remove empty shapes from within non-rendered elements.
johnkenny54 Oct 5, 2024
3ba4d36
Remove paths with length < 2.
johnkenny54 Oct 5, 2024
cde7b9c
Remove zero-radius ellipses.
johnkenny54 Oct 5, 2024
f567fc7
Cleaned up test cases.
johnkenny54 Oct 5, 2024
44fdad0
Hoist <defs> children so all have an id.
johnkenny54 Oct 5, 2024
b347dd8
Convert non-rendering elements without an id to <defs>.
johnkenny54 Oct 5, 2024
dbebfa7
Deprecate removeUselessDefs.
johnkenny54 Oct 5, 2024
2ebc122
Fix issues with markers.
johnkenny54 Oct 5, 2024
2f2cb54
Preserve only comment and element children of <defs>.
johnkenny54 Oct 5, 2024
8910692
Check for id rather than checking for references.
johnkenny54 Oct 5, 2024
a3ea98e
Don't record referenced ids.
johnkenny54 Oct 5, 2024
87f5a66
Calculate ellipse rx/ry using properties.
johnkenny54 Oct 6, 2024
51459db
Don't change values if geometry properties are set in styles.
johnkenny54 Oct 6, 2024
3930402
Convert elements to <defs> rather than removing them directly, so any…
johnkenny54 Oct 6, 2024
f41125f
Remove newly created empty defs in removeHiddenElems.
johnkenny54 Oct 6, 2024
4e6aa8d
Remove circles with r="0".
johnkenny54 Oct 6, 2024
42f0beb
Remove original version.
johnkenny54 Oct 6, 2024
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
15 changes: 14 additions & 1 deletion lib/docdata.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import * as csso from 'csso';
import {
attrsGroups,
elemsGroups,
geometryProperties,
inheritableAttrs,
} from '../plugins/_collections.js';
import { parseStylesheet } from './style-css-tree.js';
Expand Down Expand Up @@ -97,6 +98,12 @@ export class StyleData {
for (const [name, value] of Object.entries(element.attributes)) {
if (attrsGroups.presentation.has(name)) {
computedStyles.set(name, value);
} else {
// See if it is a geometry property which applies to this element.
const els = geometryProperties[name];
if (els && els.has(element.name)) {
computedStyles.set(name, value);
}
}
}

Expand All @@ -112,6 +119,9 @@ export class StyleData {
const hasVars = VAR_REGEXP.test(value.value);
if (hasVars) {
computedStyles.set(name, null);
} else if (geometryProperties[name]) {
// Support for geometry properties is inconsistent. Avoid changing these.
computedStyles.set(name, null);
} else {
computedStyles.set(name, value.value);
if (value.important) {
Expand All @@ -129,7 +139,10 @@ export class StyleData {
}
if (declarations) {
declarations.forEach((value, name) => {
if (value.important || !importantProperties.has(name)) {
if (geometryProperties[name]) {
// Support for geometry properties is inconsistent. Avoid changing these.
computedStyles.set(name, null);
} else if (value.important || !importantProperties.has(name)) {
computedStyles.set(name, value.value);
}
});
Expand Down
2 changes: 1 addition & 1 deletion lib/parser.js
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ export const parseSvg = (data, from) => {
const node = {
type: 'comment',
parentNode: current,
value: foreignLevel > 0 ? comment : comment.trim(),
value: comment,
};
pushToContent(node);
};
Expand Down
1 change: 1 addition & 0 deletions lib/path.js
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,7 @@ const readNumber = (string, cursor) => {
/**
* @param {string} string
* @returns {PathDataItem[]}
* @deprecated
*/
export const parsePathData = (string) => {
/** @type {PathDataItem[]} */
Expand Down
22 changes: 22 additions & 0 deletions lib/svgo/tools.js
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,28 @@ export function exactMul(n, m) {
return toFixed(n * m, d1 + d2);
}

/**
* @param {Map<string,string|null>} properties
* @returns {{rx:string,ry:string}|undefined}
*/
export function getEllipseProperties(properties) {
let rx = properties.get('rx');
let ry = properties.get('ry');
if (rx === undefined) {
if (ry === undefined) {
rx = ry = '0';
} else {
rx = ry;
}
} else if (ry === undefined) {
ry = rx;
}
if (rx === null || ry === null) {
return;
}
return { rx: rx, ry: ry };
}

/**
* @param {number|string} str
*/
Expand Down
1 change: 1 addition & 0 deletions lib/xast.js
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ const visitChild = (node, visitor, parents) => {
/**
* @param {XastChild} node
* @param {XastParent} [parentNode]
* @deprecated
*/
// Disable no-unused-vars until all calls to detachNodeFromParent() are updated.
// eslint-disable-next-line no-unused-vars
Expand Down
15 changes: 15 additions & 0 deletions plugins/_collections.js
Original file line number Diff line number Diff line change
Expand Up @@ -2381,6 +2381,21 @@ export const colorsProps = new Set([
'stroke',
]);

// See https://www.w3.org/TR/SVG2/geometry.html#geometry-properties
/** @type {Object<string,Set<string>>} */
export const geometryProperties = {
cx: new Set(['circle', 'ellipse']),
cy: new Set(['circle', 'ellipse']),
d: new Set(['path']),
height: new Set(['foreignObject', 'image', 'rect', 'svg', 'symbol', 'use']),
r: new Set(['circle']),
rx: new Set(['ellipse', 'rect']),
ry: new Set(['ellipse', 'rect']),
width: new Set(['foreignObject', 'image', 'rect', 'svg', 'symbol', 'use']),
x: new Set(['foreignObject', 'image', 'rect', 'svg', 'symbol', 'use']),
y: new Set(['foreignObject', 'image', 'rect', 'svg', 'symbol', 'use']),
};

/** @see https://developer.mozilla.org/docs/Web/CSS/Pseudo-classes */
export const pseudoClasses = {
displayState: new Set(['fullscreen', 'modal', 'picture-in-picture']),
Expand Down
22 changes: 6 additions & 16 deletions plugins/cleanupStyleAttributes.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import { getStyleDeclarations } from '../lib/css-tools.js';
import { writeStyleAttribute } from '../lib/css.js';
import { visitSkip } from '../lib/xast.js';
import { elemsGroups, uselessShapeProperties } from './_collections.js';
import {
elemsGroups,
geometryProperties,
uselessShapeProperties,
} from './_collections.js';

export const name = 'cleanupStyleAttributes';
export const description = 'removes invalid properties from style attributes';
Expand Down Expand Up @@ -76,20 +80,6 @@ const presentationProperties = new Set([
'writing-mode',
]);

/** @type {Object<string,Set<string>>} */
const limitedProperties = {
cx: new Set(['circle', 'ellipse']),
cy: new Set(['circle', 'ellipse']),
d: new Set(['path']),
height: new Set(['foreignObject', 'image', 'rect', 'svg', 'symbol', 'use']),
r: new Set(['circle']),
rx: new Set(['ellipse', 'rect']),
ry: new Set(['ellipse', 'rect']),
width: new Set(['foreignObject', 'image', 'rect', 'svg', 'symbol', 'use']),
x: new Set(['foreignObject', 'image', 'rect', 'svg', 'symbol', 'use']),
y: new Set(['foreignObject', 'image', 'rect', 'svg', 'symbol', 'use']),
};

/**
* @type {import('./plugins-types.js').Plugin<'cleanupStyleAttributes'>}
*/
Expand Down Expand Up @@ -135,7 +125,7 @@ export const fn = (root, params, info) => {
}

// See if it is allowed for this element.
const allowedElements = limitedProperties[propName];
const allowedElements = geometryProperties[propName];
return allowedElements && allowedElements.has(elName);
}

Expand Down
1 change: 1 addition & 0 deletions plugins/combinePaths.js
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@ function allStylesAreMergeable(styles) {
continue;
}
break;
case 'd':
case 'fill-opacity':
case 'opacity':
case 'stroke-linecap':
Expand Down
8 changes: 6 additions & 2 deletions plugins/minifyPathData.js
Original file line number Diff line number Diff line change
Expand Up @@ -787,9 +787,10 @@ function stringifyCommand(cmdCode, prevCmdChar, lastNumber, args) {

/**
* @param {string} path
* @param {number} [maxCommands]
* @returns {PathCommand[]}
*/
export function parsePathCommands(path) {
export function parsePathCommands(path, maxCommands = Number.MAX_SAFE_INTEGER) {
function addArg() {
if (currentArg !== '') {
args.push(currentArg);
Expand Down Expand Up @@ -831,6 +832,9 @@ export function parsePathCommands(path) {
switch (getCharType(c)) {
case 'command':
addCurrentCommand(c);
if (commands.length >= maxCommands) {
return commands;
}
continue;
case '.':
if (currentCommand === '') {
Expand Down Expand Up @@ -1088,7 +1092,7 @@ class ExactNum {
}
}

class PathParseError extends Error {
export class PathParseError extends Error {
/**
* @param {string} msg
*/
Expand Down
2 changes: 0 additions & 2 deletions plugins/preset-default.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ import * as removeMetadata from './removeMetadata.js';
import * as removeNonInheritableGroupAttrs from './removeNonInheritableGroupAttrs.js';
import * as removeUnknownsAndDefaults from './removeUnknownsAndDefaults.js';
import * as removeUnusedNS from './removeUnusedNS.js';
import * as removeUselessDefs from './removeUselessDefs.js';
import * as removeUselessStrokeAndFill from './removeUselessStrokeAndFill.js';
import * as removeXMLProcInst from './removeXMLProcInst.js';

Expand All @@ -45,7 +44,6 @@ const presetDefault = createPreset({
inlineStyles,
minifyStyles,
cleanupIds,
removeUselessDefs,
convertColors,
removeUnknownsAndDefaults,
removeNonInheritableGroupAttrs,
Expand Down
2 changes: 0 additions & 2 deletions plugins/preset-next.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ import * as removeMetadata from './removeMetadata.js';
import * as removeNonInheritableGroupAttrs from './removeNonInheritableGroupAttrs.js';
import * as removeUnknownsAndDefaults from './removeUnknownsAndDefaults.js';
import * as removeUnusedNS from './removeUnusedNS.js';
import * as removeUselessDefs from './removeUselessDefs.js';
import * as removeUselessStrokeAndFill from './removeUselessStrokeAndFill.js';
import * as removeXMLProcInst from './removeXMLProcInst.js';

Expand All @@ -45,7 +44,6 @@ const presetNext = createPreset({
inlineStyles,
minifyStyles,
cleanupIds,
removeUselessDefs,
convertColors,
removeUnknownsAndDefaults,
removeNonInheritableGroupAttrs,
Expand Down
Loading