1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
// this_file: crates/vexy-vsvg-plugin-sdk/src/plugins/collapse_groups.rs
//! Collapses unnecessary `<g>` wrappers to flatten the DOM tree.
//!
//! Groups (`<g>` elements) organize related shapes and share attributes, but they're
//! often left empty or wrapping single children after optimization. This plugin removes
//! those redundant layers.
//!
//! ## What it does
//!
//! 1. **Removes empty groups** with no attributes: `<g><rect /></g>` → `<rect />`
//! 2. **Merges single-child groups**: Moves group attributes to the child and unwraps
//! - `<g fill="red"><rect /></g>` → `<rect fill="red" />`
//! 3. **Concatenates transforms**: Parent and child transforms combine correctly
//! - `<g transform="translate(10,0)"><rect transform="scale(2)" /></g>`
//! - → `<rect transform="translate(10,0) scale(2)" />`
//!
//! ## What it preserves
//!
//! - **Groups with animations**: `<animate>`, `<animateTransform>`, etc. rely on parent context
//! - **Groups in `<switch>`**: Alternate renderings need the wrapper
//! - **Groups with `filter`**: Filters apply to the group boundary box
//! - **Conflicting attributes**: Won't merge if both parent and child have incompatible values
//!
//! ## Reference
//!
//! Ported from SVGO's `collapseGroups` plugin.
use crate::Plugin;
use anyhow::Result;
use std::collections::HashSet;
use vexy_vsvg::ast::{Document, Element, Node};
use vexy_vsvg::error::VexyError;
use vexy_vsvg::visitor::Visitor;
/// Removes redundant `<g>` group wrappers to simplify the document structure.
///
/// # Example
///
/// ```text
/// Before: <g><g fill="red"><rect x="10" y="10" /></g></g>
/// After: <rect fill="red" x="10" y="10" />
/// ```
#[derive(Default)]
pub struct CollapseGroupsPlugin;
impl CollapseGroupsPlugin {
/// Create a new CollapseGroupsPlugin
pub fn new() -> Self {
Self
}
/// Returns SVG animation element names that depend on their parent group's context.
///
/// These elements reference their parent via timing/targeting, so we can't remove
/// the group without breaking the animation.
fn animation_elements() -> &'static [&'static str] {
&[
"animate",
"animateColor",
"animateMotion",
"animateTransform",
"set",
]
}
/// Returns the set of SVG attributes that inherit from parent to child.
///
/// Used to resolve `inherit` keyword when merging group attributes.
fn inheritable_attributes() -> &'static HashSet<&'static str> {
static INHERITABLE_ATTRS: std::sync::OnceLock<HashSet<&'static str>> =
std::sync::OnceLock::new();
INHERITABLE_ATTRS.get_or_init(|| {
[
"clip-rule",
"color",
"color-interpolation",
"color-interpolation-filters",
"color-profile",
"color-rendering",
"cursor",
"direction",
"fill",
"fill-opacity",
"fill-rule",
"font",
"font-family",
"font-size",
"font-size-adjust",
"font-stretch",
"font-style",
"font-variant",
"font-weight",
"glyph-orientation-horizontal",
"glyph-orientation-vertical",
"image-rendering",
"kerning",
"letter-spacing",
"marker",
"marker-end",
"marker-mid",
"marker-start",
"pointer-events",
"shape-rendering",
"stroke",
"stroke-dasharray",
"stroke-dashoffset",
"stroke-linecap",
"stroke-linejoin",
"stroke-miterlimit",
"stroke-opacity",
"stroke-width",
"text-anchor",
"text-rendering",
"visibility",
"word-spacing",
"writing-mode",
]
.into_iter()
.collect()
})
}
/// Returns true if the element has animation children that depend on the parent.
fn has_animation_children(element: &Element) -> bool {
element.children.iter().any(|child| {
if let Node::Element(elem) = child {
Self::animation_elements().contains(&elem.name.as_ref())
} else {
false
}
})
}
/// Returns true if the group's attributes can safely merge into the child.
///
/// Checks for conflicts that would break references or duplicate properties:
/// - Child must not have an `id` (to avoid creating duplicate IDs)
/// - Group must not have `filter` (filters apply to the group's bounding box)
/// - Both cannot have `class` attributes (would conflict)
/// - Both cannot have `clip-path` or `mask` (would conflict)
fn can_move_attributes(group: &Element, child: &Element) -> bool {
// Child must not have an id (to avoid reference conflicts)
if child.attributes.contains_key("id") {
return false;
}
// Group must not have filter (filters apply to group boundary)
if group.attributes.contains_key("filter") {
return false;
}
// Both cannot have class attributes (would conflict)
if group.attributes.contains_key("class") && child.attributes.contains_key("class") {
return false;
}
// Check for clip-path/mask conflicts
if (group.attributes.contains_key("clip-path")
&& child.attributes.contains_key("clip-path"))
|| (group.attributes.contains_key("mask") && child.attributes.contains_key("mask"))
{
return false;
}
true
}
/// Transfers all group attributes to the child, handling special cases.
///
/// Special handling:
/// - `transform`: Concatenates group and child transforms (group's transform first)
/// - `inherit` keyword: Replaces child's `inherit` value with parent's actual value
/// - Other attributes: Only adds if child doesn't already have them
fn move_attributes<'a>(group: &Element<'a>, child: &mut Element<'a>) {
for (attr_name, attr_value) in &group.attributes {
match attr_name.as_ref() {
"transform" => {
// Concatenate transforms: parent transform comes first
if let Some(child_transform) = child.attributes.get("transform") {
let combined = format!("{} {}", attr_value, child_transform);
child.attributes.insert("transform".into(), combined.into());
} else {
child
.attributes
.insert(attr_name.clone(), attr_value.clone());
}
}
_ => {
// Handle inheritance: replace "inherit" with parent's value
if let Some(existing_value) = child.attributes.get(attr_name) {
if existing_value == "inherit"
&& Self::inheritable_attributes().contains(attr_name.as_ref())
{
child
.attributes
.insert(attr_name.clone(), attr_value.clone());
}
// If child already has non-inherit value, don't override
} else {
// Child doesn't have this attribute, so add it
child
.attributes
.insert(attr_name.clone(), attr_value.clone());
}
}
}
}
}
/// Returns true if the group is truly empty and can be unwrapped completely.
fn can_remove_group(group: &Element, parent_name: Option<&str>) -> bool {
// Must have no attributes
if !group.attributes.is_empty() {
return false;
}
// Must not contain animation elements
if Self::has_animation_children(group) {
return false;
}
// Cannot be direct child of switch element
if let Some(parent) = parent_name {
if parent == "switch" {
return false;
}
}
true
}
/// Attempts to collapse a group, returning replacement nodes if successful.
fn process_group<'a>(
group: &mut Element<'a>,
parent_name: Option<&str>,
) -> Option<Vec<Node<'a>>> {
// First check if we can remove the group entirely
if Self::can_remove_group(group, parent_name) {
return Some(group.children.clone());
}
// Check if we can move attributes to a single child
if group.children.len() == 1 {
if let Node::Element(child_element) = &group.children[0] {
if Self::can_move_attributes(group, child_element) {
// Clone the child and move attributes to it
let mut new_child = child_element.clone();
Self::move_attributes(group, &mut new_child);
return Some(vec![Node::Element(new_child)]);
}
}
}
// No collapse possible
None
}
}
impl Plugin for CollapseGroupsPlugin {
fn name(&self) -> &'static str {
"collapseGroups"
}
fn description(&self) -> &'static str {
"Collapse unnecessary group elements"
}
fn validate_params(&self, params: &serde_json::Value) -> anyhow::Result<()> {
// This plugin doesn't accept any parameters in the original SVGO implementation
if !params.is_null() && !params.as_object().is_some_and(|obj| obj.is_empty()) {
return Err(anyhow::anyhow!(
"collapseGroups plugin does not accept any parameters"
));
}
Ok(())
}
fn apply(&self, document: &mut Document) -> anyhow::Result<()> {
let mut visitor = GroupCollapseVisitor::new();
vexy_vsvg::visitor::walk_document(&mut visitor, document)?;
Ok(())
}
}
/// Visitor that walks the tree bottom-up, collapsing groups after children are processed.
struct GroupCollapseVisitor;
impl GroupCollapseVisitor {
fn new() -> Self {
Self
}
}
impl Visitor<'_> for GroupCollapseVisitor {
fn visit_element_exit(&mut self, element: &mut Element<'_>) -> Result<(), VexyError> {
// Process from bottom up - children are already processed
let mut indices_to_replace = Vec::new();
for (i, child) in element.children.iter_mut().enumerate() {
if let Node::Element(child_element) = child {
if child_element.name.as_ref() == "g" {
// Try to collapse this group
if let Some(replacement_nodes) =
CollapseGroupsPlugin::process_group(child_element, Some(&element.name))
{
indices_to_replace.push((i, replacement_nodes));
}
}
}
}
// Apply replacements in reverse order to maintain indices
for (index, replacement_nodes) in indices_to_replace.into_iter().rev() {
element.children.remove(index);
for (offset, node) in replacement_nodes.into_iter().enumerate() {
element.children.insert(index + offset, node);
}
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
use std::borrow::Cow;
use vexy_vsvg::ast::{Document, Element, Node};
fn create_element(name: &'static str) -> Element<'static> {
let mut element = Element::new(name);
element.name = Cow::Borrowed(name);
element
}
fn create_element_with_attrs(name: &'static str, attrs: &[(&str, &str)]) -> Element<'static> {
let mut element = create_element(name);
for (key, value) in attrs {
element.set_attr(*key, *value);
}
element
}
#[test]
fn test_plugin_creation() {
let plugin = CollapseGroupsPlugin::new();
assert_eq!(plugin.name(), "collapseGroups");
}
#[test]
fn test_parameter_validation() {
let plugin = CollapseGroupsPlugin::new();
// Valid: null parameters
assert!(plugin.validate_params(&json!(null)).is_ok());
// Valid: empty object
assert!(plugin.validate_params(&json!({})).is_ok());
// Invalid: non-empty parameters
assert!(plugin.validate_params(&json!({"someParam": true})).is_err());
}
#[test]
fn test_animation_elements() {
assert!(CollapseGroupsPlugin::animation_elements().contains(&"animate"));
assert!(CollapseGroupsPlugin::animation_elements().contains(&"animateTransform"));
assert!(!CollapseGroupsPlugin::animation_elements().contains(&"rect"));
}
#[test]
fn test_has_animation_children() {
let mut group = create_element("g");
assert!(!CollapseGroupsPlugin::has_animation_children(&group));
// Add animation child
group
.children
.push(Node::Element(create_element("animate")));
assert!(CollapseGroupsPlugin::has_animation_children(&group));
// Add non-animation child
let mut group2 = create_element("g");
group2.children.push(Node::Element(create_element("rect")));
assert!(!CollapseGroupsPlugin::has_animation_children(&group2));
}
#[test]
fn test_can_move_attributes() {
let group = create_element("g");
let child = create_element("rect");
assert!(CollapseGroupsPlugin::can_move_attributes(&group, &child));
// Child with id should prevent movement
let child_with_id = create_element_with_attrs("rect", &[("id", "test")]);
assert!(!CollapseGroupsPlugin::can_move_attributes(
&group,
&child_with_id
));
// Group with filter should prevent movement
let group_with_filter = create_element_with_attrs("g", &[("filter", "url(#filter)")]);
assert!(!CollapseGroupsPlugin::can_move_attributes(
&group_with_filter,
&child
));
// Both with class should prevent movement
let group_with_class = create_element_with_attrs("g", &[("class", "group-class")]);
let child_with_class = create_element_with_attrs("rect", &[("class", "child-class")]);
assert!(!CollapseGroupsPlugin::can_move_attributes(
&group_with_class,
&child_with_class
));
}
#[test]
fn test_move_attributes_basic() {
let group = create_element_with_attrs("g", &[("fill", "red"), ("stroke", "blue")]);
let mut child = create_element("rect");
CollapseGroupsPlugin::move_attributes(&group, &mut child);
assert_eq!(child.attr("fill"), Some("red"));
assert_eq!(child.attr("stroke"), Some("blue"));
}
#[test]
fn test_move_attributes_transform_concatenation() {
let group = create_element_with_attrs("g", &[("transform", "translate(10,10)")]);
let mut child = create_element_with_attrs("rect", &[("transform", "scale(2)")]);
CollapseGroupsPlugin::move_attributes(&group, &mut child);
assert_eq!(child.attr("transform"), Some("translate(10,10) scale(2)"));
}
#[test]
fn test_move_attributes_inheritance() {
let group = create_element_with_attrs("g", &[("fill", "red")]);
let mut child = create_element_with_attrs("rect", &[("fill", "inherit")]);
CollapseGroupsPlugin::move_attributes(&group, &mut child);
// inherit should be replaced with parent's value
assert_eq!(child.attr("fill"), Some("red"));
}
#[test]
fn test_can_remove_group() {
// Empty group with no attributes should be removable
let group = create_element("g");
assert!(CollapseGroupsPlugin::can_remove_group(&group, None));
// Group with attributes should not be removable
let group_with_attrs = create_element_with_attrs("g", &[("fill", "red")]);
assert!(!CollapseGroupsPlugin::can_remove_group(
&group_with_attrs,
None
));
// Group in switch should not be removable
assert!(!CollapseGroupsPlugin::can_remove_group(
&group,
Some("switch")
));
// Group with animation children should not be removable
let mut group_with_animation = create_element("g");
group_with_animation
.children
.push(Node::Element(create_element("animate")));
assert!(!CollapseGroupsPlugin::can_remove_group(
&group_with_animation,
None
));
}
#[test]
fn test_plugin_apply_empty_group_removal() {
let plugin = CollapseGroupsPlugin::new();
let mut doc = Document::new();
// Create nested empty groups: svg > g > g > rect
let rect = create_element("rect");
let mut inner_group = create_element("g");
inner_group.children.push(Node::Element(rect));
let mut outer_group = create_element("g");
outer_group.children.push(Node::Element(inner_group));
doc.root.children.push(Node::Element(outer_group));
plugin.apply(&mut doc).unwrap();
// Both groups should be removed, leaving just the rect
assert_eq!(doc.root.children.len(), 1);
if let Node::Element(element) = &doc.root.children[0] {
assert_eq!(element.name.as_ref(), "rect");
}
}
#[test]
fn test_plugin_apply_attribute_movement() {
let plugin = CollapseGroupsPlugin::new();
let mut doc = Document::new();
// Create group with attributes and single child
let child = create_element("rect");
let mut group = create_element_with_attrs("g", &[("fill", "red"), ("stroke", "blue")]);
group.children.push(Node::Element(child));
doc.root.children.push(Node::Element(group));
plugin.apply(&mut doc).unwrap();
// Group should be collapsed, attributes moved to rect
assert_eq!(doc.root.children.len(), 1);
if let Node::Element(element) = &doc.root.children[0] {
assert_eq!(element.name.as_ref(), "rect");
assert_eq!(element.attr("fill"), Some("red"));
assert_eq!(element.attr("stroke"), Some("blue"));
}
}
#[test]
fn test_plugin_apply_preservation() {
let plugin = CollapseGroupsPlugin::new();
let mut doc = Document::new();
// Create group that should not be collapsed (multiple children)
let mut group = create_element_with_attrs("g", &[("fill", "red")]);
group.children.push(Node::Element(create_element("rect")));
group.children.push(Node::Element(create_element("circle")));
doc.root.children.push(Node::Element(group.clone()));
plugin.apply(&mut doc).unwrap();
// Group should be preserved
assert_eq!(doc.root.children.len(), 1);
if let Node::Element(element) = &doc.root.children[0] {
assert_eq!(element.name.as_ref(), "g");
assert_eq!(element.children.len(), 2);
assert_eq!(element.attr("fill"), Some("red"));
}
}
}