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
// this_file: crates/vexy-vsvg-plugin-sdk/src/plugins/move_group_attrs_to_elems.rs
//! Pushes group attributes down to a single child element.
//!
//! When a `<g>` wrapper contains exactly one child element, this plugin moves inheritable
//! presentation attributes from the group to the child. Prepares groups for removal by
//! the collapseGroups plugin.
//!
//! **What it does:**
//! - Finds `<g>` elements with exactly one child element
//! - Moves inheritable attributes (fill, stroke, opacity, etc.) from group to child
//! - Removes moved attributes from the group
//!
//! **What it preserves:**
//! - Attributes the child already has (won't overwrite)
//! - Non-movable attributes on the group (id, class, transform stay on group)
//! - Groups with multiple children (unchanged)
//!
//! **Example:**
//! ```xml
//! <!-- Before -->
//! <g fill="red" stroke="blue">
//! <rect x="0" y="0" width="10" height="10"/>
//! </g>
//!
//! <!-- After -->
//! <g>
//! <rect fill="red" stroke="blue" x="0" y="0" width="10" height="10"/>
//! </g>
//! <!-- collapseGroups can now remove the empty wrapper -->
//! ```
//!
//! **Why it's useful:** Makes single-child groups redundant, allowing them to be collapsed.
//! Often runs before collapseGroups in the plugin pipeline.
//!
//! Reference: SVGO's moveGroupAttrsToElems plugin
use crate::Plugin;
use anyhow::Result;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use vexy_vsvg::ast::{Document, Element, Node};
/// Configuration for the moveGroupAttrsToElems plugin.
///
/// Currently no configuration options. The plugin uses a fixed set of movable attributes.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[derive(Default)]
pub struct MoveGroupAttrsToElemsConfig {}
/// Plugin to move group attributes to children when the group only has one child.
///
/// Pushes inheritable attributes from single-child groups down to their child,
/// preparing the group for removal by collapseGroups.
pub struct MoveGroupAttrsToElemsPlugin {
#[allow(dead_code)]
config: MoveGroupAttrsToElemsConfig,
}
impl MoveGroupAttrsToElemsPlugin {
pub fn new() -> Self {
Self {
#[allow(dead_code)]
config: MoveGroupAttrsToElemsConfig::default(),
}
}
pub fn with_config(config: MoveGroupAttrsToElemsConfig) -> Self {
Self { config }
}
fn parse_config(params: &Value) -> Result<MoveGroupAttrsToElemsConfig> {
if params.is_null() {
Ok(MoveGroupAttrsToElemsConfig::default())
} else {
serde_json::from_value(params.clone())
.map_err(|e| anyhow::anyhow!("Invalid plugin configuration: {}", e))
}
}
/// Process an element and its children.
///
/// Recursively processes the tree depth-first, then moves attributes from
/// single-child groups to their child element.
fn process_element(&self, element: &mut Element) {
// Process children first (depth-first)
let mut i = 0;
while i < element.children.len() {
if let Node::Element(child_elem) = &mut element.children[i] {
self.process_element(child_elem);
}
i += 1;
}
// Check if this is a group with exactly one element child
if element.name == "g" {
let element_children_count = element
.children
.iter()
.filter(|node| matches!(node, Node::Element(_)))
.count();
if element_children_count == 1 {
// We have exactly one child element, move applicable attributes
self.move_attributes_to_single_child(element);
}
}
}
/// Move inheritable attributes from group to its single child.
///
/// Only moves attributes the child doesn't already have. Won't overwrite
/// child's existing styling. Only applies to inheritable presentation attributes.
fn move_attributes_to_single_child(&self, group: &mut Element) {
// Inheritable presentation attributes that can safely move from group to child
const MOVABLE_ATTRS: &[&str] = &[
"fill",
"stroke",
"stroke-width",
"stroke-linecap",
"stroke-linejoin",
"stroke-miterlimit",
"stroke-dasharray",
"stroke-dashoffset",
"stroke-opacity",
"fill-opacity",
"opacity",
"color",
"font-family",
"font-size",
"font-style",
"font-variant",
"font-weight",
"text-anchor",
"text-decoration",
"letter-spacing",
"word-spacing",
];
// Find the single child element
let mut child_index = None;
for (i, node) in group.children.iter().enumerate() {
if matches!(node, Node::Element(_)) {
child_index = Some(i);
break;
}
}
if let Some(index) = child_index {
let mut attrs_to_move = Vec::new();
// Collect attributes to move
for attr_name in MOVABLE_ATTRS {
if let Some(attr_value) = group.attr(attr_name) {
if let Node::Element(child) = &group.children[index] {
// Only move if child doesn't already have this attribute
if !child.has_attr(attr_name) {
attrs_to_move.push((attr_name.to_string(), attr_value.to_string()));
}
}
}
}
// Apply the moves
if !attrs_to_move.is_empty() {
if let Node::Element(child) = &mut group.children[index] {
for (attr_name, attr_value) in &attrs_to_move {
child.set_attr(attr_name, attr_value);
}
}
// Remove moved attributes from group
for (attr_name, _) in attrs_to_move {
group.remove_attr(&attr_name);
}
}
}
}
}
impl Default for MoveGroupAttrsToElemsPlugin {
fn default() -> Self {
Self::new()
}
}
impl Plugin for MoveGroupAttrsToElemsPlugin {
fn name(&self) -> &'static str {
"moveGroupAttrsToElems"
}
fn description(&self) -> &'static str {
"Move group attributes to children when group has single child"
}
fn validate_params(&self, params: &Value) -> Result<()> {
Self::parse_config(params)?;
Ok(())
}
fn apply(&self, document: &mut Document) -> Result<()> {
self.process_element(&mut document.root);
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use vexy_vsvg::ast::{Element, Node};
#[test]
fn test_plugin_info() {
let plugin = MoveGroupAttrsToElemsPlugin::new();
assert_eq!(plugin.name(), "moveGroupAttrsToElems");
assert_eq!(
plugin.description(),
"Move group attributes to children when group has single child"
);
}
#[test]
fn test_param_validation() {
let plugin = MoveGroupAttrsToElemsPlugin::new();
// Test null params
assert!(plugin.validate_params(&Value::Null).is_ok());
// Test empty object params
assert!(plugin.validate_params(&serde_json::json!({})).is_ok());
// Test invalid params
assert!(plugin
.validate_params(&serde_json::json!({
"invalidParam": true
}))
.is_err());
}
#[test]
fn test_move_attrs_to_single_child() {
let plugin = MoveGroupAttrsToElemsPlugin::new();
let mut doc = Document::new();
// Create a group with attributes and a single child
let mut group = Element::new("g");
group.set_attr("fill", "red");
group.set_attr("stroke", "blue");
group.set_attr("id", "group1"); // This should not be moved
let child = Element::new("rect");
group.children.push(Node::Element(child));
doc.root = group;
// Apply the plugin
plugin.apply(&mut doc).unwrap();
// Check that attributes were moved
match &doc.root.children[0] {
Node::Element(child) => {
assert_eq!(child.attr("fill"), Some("red"));
assert_eq!(child.attr("stroke"), Some("blue"));
}
_ => panic!("Expected element child"),
}
// Check that movable attributes were removed from group
assert!(!doc.root.has_attr("fill"));
assert!(!doc.root.has_attr("stroke"));
// Check that non-movable attributes remain on group
assert_eq!(doc.root.attr("id"), Some("group1"));
}
#[test]
fn test_no_move_when_child_has_attr() {
let plugin = MoveGroupAttrsToElemsPlugin::new();
let mut doc = Document::new();
// Create a group with attributes and a single child that already has some attributes
let mut group = Element::new("g");
group.set_attr("fill", "red");
group.set_attr("stroke", "blue");
let mut child = Element::new("rect");
child.set_attr("fill", "green"); // Child already has fill
group.children.push(Node::Element(child));
doc.root = group;
// Apply the plugin
plugin.apply(&mut doc).unwrap();
// Check that fill was not moved (child already had it)
match &doc.root.children[0] {
Node::Element(child) => {
assert_eq!(child.attr("fill"), Some("green")); // Original value preserved
assert_eq!(child.attr("stroke"), Some("blue")); // This was moved
}
_ => panic!("Expected element child"),
}
// Check that fill remains on group (not moved)
assert_eq!(doc.root.attr("fill"), Some("red"));
assert!(!doc.root.has_attr("stroke")); // This was moved
}
#[test]
fn test_no_move_with_multiple_children() {
let plugin = MoveGroupAttrsToElemsPlugin::new();
let mut doc = Document::new();
// Create a group with attributes and multiple children
let mut group = Element::new("g");
group.set_attr("fill", "red");
group.children.push(Node::Element(Element::new("rect")));
group.children.push(Node::Element(Element::new("circle")));
doc.root = group;
// Apply the plugin
plugin.apply(&mut doc).unwrap();
// Check that attributes were not moved
assert_eq!(doc.root.attr("fill"), Some("red"));
}
}