vexy-vsvg-plugin-sdk 2.4.2

Plugin SDK for vexy-vsvg
Documentation
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
// this_file: crates/vexy-vsvg-plugin-sdk/src/plugins/move_elems_attrs_to_group.rs

//! Hoists duplicate attributes from child elements to their parent group.
//!
//! When all children share the same attribute value (like `fill="red"`), this plugin
//! moves that attribute to the parent `<g>` element instead. Reduces file size by
//! eliminating redundant declarations.
//!
//! **What it does:**
//! - Finds attributes that all child elements share (same name and value)
//! - Moves those attributes to the parent group element
//! - Removes the attributes from all children
//!
//! **What it preserves:**
//! - Attributes unique to each child (different values)
//! - Attributes already on the parent (won't overwrite)
//! - Non-movable attributes (transform, id, class, etc.)
//!
//! **Example:**
//! ```xml
//! <!-- Before -->
//! <g>
//!   <rect fill="red" stroke="blue" x="0"/>
//!   <circle fill="red" stroke="blue" r="5"/>
//! </g>
//!
//! <!-- After -->
//! <g fill="red" stroke="blue">
//!   <rect x="0"/>
//!   <circle r="5"/>
//! </g>
//! ```
//!
//! **Movable attributes:** fill, stroke, opacity, font-family, text-anchor, and other
//! inheritable presentation attributes. See `get_movable_attributes()` for the full list.
//!
//! Reference: SVGO's moveElemsAttrsToGroup plugin

use crate::Plugin;
use anyhow::Result;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::{HashMap, HashSet};
use vexy_vsvg::ast::{Document, Element, Node};

/// Configuration for the moveElemsAttrsToGroup 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 MoveElemsAttrsToGroupConfig {}

/// Plugin to move common attributes from elements to their group.
///
/// Analyzes child elements of groups and hoists shared attributes to the parent,
/// reducing file size and improving readability.
pub struct MoveElemsAttrsToGroupPlugin {
    #[allow(dead_code)]
    config: MoveElemsAttrsToGroupConfig,
}

impl MoveElemsAttrsToGroupPlugin {
    pub fn new() -> Self {
        Self {
            #[allow(dead_code)]
            config: MoveElemsAttrsToGroupConfig::default(),
        }
    }

    pub fn with_config(config: MoveElemsAttrsToGroupConfig) -> Self {
        Self { config }
    }

    fn parse_config(params: &Value) -> Result<MoveElemsAttrsToGroupConfig> {
        if params.is_null() {
            Ok(MoveElemsAttrsToGroupConfig::default())
        } else {
            serde_json::from_value(params.clone())
                .map_err(|e| anyhow::anyhow!("Invalid plugin configuration: {}", e))
        }
    }

    /// Check if a group can have attributes moved to it.
    ///
    /// Only container elements that define rendering contexts can receive hoisted attributes.
    /// Returns true for: g, svg, symbol, defs, clipPath, mask
    fn can_move_to_group(&self, element: &Element) -> bool {
        matches!(
            element.name.as_ref(),
            "g" | "svg" | "symbol" | "defs" | "clipPath" | "mask"
        )
    }

    /// Get attributes that can be moved to parent group.
    ///
    /// Returns the set of inheritable presentation attributes that are safe to hoist.
    /// Includes fill, stroke, opacity, font properties, and other CSS-inheritable attributes.
    /// Excludes structural attributes like transform, id, class that must stay on elements.
    fn get_movable_attributes() -> HashSet<&'static 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",
        ]
        .iter()
        .copied()
        .collect()
    }

    /// Find common attributes among all child elements.
    ///
    /// Computes the intersection of movable attributes across all children.
    /// Only returns attributes where both name and value match across all child elements.
    /// Requires at least 2 child elements (no point hoisting from a single child).
    fn find_common_attributes(&self, children: &[Node]) -> HashMap<String, String> {
        let movable_attrs = Self::get_movable_attributes();
        let mut common_attrs: Option<HashMap<String, String>> = None;

        // Only consider child elements, not text nodes
        let child_elements: Vec<&Element> = children
            .iter()
            .filter_map(|node| match node {
                Node::Element(elem) => Some(elem),
                _ => None,
            })
            .collect();

        // Need at least 2 children for hoisting to make sense
        if child_elements.len() < 2 {
            return HashMap::new();
        }

        for elem in child_elements {
            let mut elem_attrs = HashMap::new();

            // Collect movable attributes from this element
            for (name, value) in &elem.attributes {
                if movable_attrs.contains(name.as_ref()) {
                    elem_attrs.insert(name.to_string(), value.to_string());
                }
            }

            match &common_attrs {
                None => {
                    // First element sets the baseline
                    common_attrs = Some(elem_attrs);
                }
                Some(existing) => {
                    // Keep only attributes that match between elements
                    let mut intersection = HashMap::new();
                    for (name, value) in existing {
                        if let Some(elem_value) = elem_attrs.get(name) {
                            if elem_value == value {
                                intersection.insert(name.clone(), value.clone());
                            }
                        }
                    }
                    common_attrs = Some(intersection);
                }
            }

            // If no common attributes remain, no point continuing
            if common_attrs.as_ref().is_none_or(|attrs| attrs.is_empty()) {
                break;
            }
        }

        common_attrs.unwrap_or_default()
    }

    /// Remove attributes from child elements.
    ///
    /// Deletes the specified attributes from all child elements after they've been
    /// hoisted to the parent group.
    fn remove_attributes_from_children(
        &self,
        children: &mut [Node],
        attrs_to_remove: &HashSet<String>,
    ) {
        for node in children {
            if let Node::Element(elem) = node {
                for attr_name in attrs_to_remove {
                    elem.remove_attr(attr_name);
                }
            }
        }
    }

    /// Add attributes to the parent element.
    ///
    /// Applies hoisted attributes to the parent group. Won't overwrite attributes
    /// the parent already has (preserves existing group styling).
    fn add_attributes_to_parent(
        &self,
        parent: &mut Element,
        attrs_to_add: &HashMap<String, String>,
    ) {
        for (name, value) in attrs_to_add {
            // Only add if the parent doesn't already have this attribute
            if !parent.has_attr(name) {
                parent.set_attr(name, value);
            }
        }
    }

    /// Process an element and its children.
    ///
    /// Recursively processes the tree depth-first, then hoists common attributes
    /// from children to the current group if applicable.
    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) = &mut element.children[i] {
                self.process_element(child);
            }
            i += 1;
        }

        // Only process group-like elements that can contain other elements
        if !self.can_move_to_group(element) {
            return;
        }

        // Find common attributes among all child elements
        let common_attrs = self.find_common_attributes(&element.children);

        if common_attrs.is_empty() {
            return;
        }

        // Only move attributes the parent doesn't already have — removing an attr
        // from children when the parent has a DIFFERENT value would change what the
        // children inherit (e.g., children lose stroke="none" and inherit stroke="#000").
        let attrs_to_move: HashMap<String, String> = common_attrs
            .into_iter()
            .filter(|(name, _)| !element.has_attr(name))
            .collect();

        if attrs_to_move.is_empty() {
            return;
        }

        let attrs_to_remove: HashSet<String> = attrs_to_move.keys().cloned().collect();
        self.remove_attributes_from_children(&mut element.children, &attrs_to_remove);
        self.add_attributes_to_parent(element, &attrs_to_move);
    }
}

impl Default for MoveElemsAttrsToGroupPlugin {
    fn default() -> Self {
        Self::new()
    }
}

impl Plugin for MoveElemsAttrsToGroupPlugin {
    fn name(&self) -> &'static str {
        "moveElemsAttrsToGroup"
    }

    fn description(&self) -> &'static str {
        "move common attributes from elements to their group"
    }

    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::*;

    fn create_test_element(tag: &str, attrs: Vec<(&str, &str)>) -> Element<'static> {
        let mut element = Element::new(tag.to_string());
        for (name, value) in attrs {
            element.set_attr(name, value);
        }
        element
    }

    #[test]
    fn test_plugin_info() {
        let plugin = MoveElemsAttrsToGroupPlugin::new();
        assert_eq!(plugin.name(), "moveElemsAttrsToGroup");
        assert_eq!(
            plugin.description(),
            "move common attributes from elements to their group"
        );
    }

    #[test]
    fn test_param_validation() {
        let plugin = MoveElemsAttrsToGroupPlugin::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_common_fill_attribute() {
        let plugin = MoveElemsAttrsToGroupPlugin::new();

        let mut group = create_test_element("g", vec![]);
        group.children = vec![
            Node::Element(create_test_element(
                "rect",
                vec![("fill", "red"), ("x", "0")],
            )),
            Node::Element(create_test_element(
                "circle",
                vec![("fill", "red"), ("r", "5")],
            )),
        ];

        let mut document = Document::default();
        document.root.children = vec![Node::Element(group)];

        let result = plugin.apply(&mut document);
        assert!(result.is_ok());

        // Check that the group now has the fill attribute
        if let Node::Element(ref group) = document.root.children[0] {
            assert_eq!(group.attr("fill"), Some("red"));

            // Check that children no longer have the fill attribute
            for child in &group.children {
                if let Node::Element(elem) = child {
                    assert!(!elem.has_attr("fill"));
                }
            }
        }
    }

    #[test]
    fn test_no_change_when_attributes_differ() {
        let plugin = MoveElemsAttrsToGroupPlugin::new();

        let mut group = create_test_element("g", vec![]);
        group.children = vec![
            Node::Element(create_test_element("rect", vec![("fill", "red")])),
            Node::Element(create_test_element("circle", vec![("fill", "blue")])),
        ];

        let mut document = Document::default();
        document.root.children = vec![Node::Element(group.clone())];

        let result = plugin.apply(&mut document);
        assert!(result.is_ok());

        // Group should not have fill attribute
        if let Node::Element(ref result_group) = document.root.children[0] {
            assert!(!result_group.has_attr("fill"));

            // Children should still have their original fill attributes
            if let Node::Element(ref rect) = result_group.children[0] {
                assert_eq!(rect.attr("fill"), Some("red"));
            }
            if let Node::Element(ref circle) = result_group.children[1] {
                assert_eq!(circle.attr("fill"), Some("blue"));
            }
        }
    }

    #[test]
    fn test_multiple_common_attributes() {
        let plugin = MoveElemsAttrsToGroupPlugin::new();

        let mut group = create_test_element("g", vec![]);
        group.children = vec![
            Node::Element(create_test_element(
                "rect",
                vec![("fill", "red"), ("stroke", "blue"), ("opacity", "0.5")],
            )),
            Node::Element(create_test_element(
                "circle",
                vec![("fill", "red"), ("stroke", "blue"), ("opacity", "0.5")],
            )),
        ];

        let mut document = Document::default();
        document.root.children = vec![Node::Element(group)];

        let result = plugin.apply(&mut document);
        assert!(result.is_ok());

        // Check that the group has all common attributes
        if let Node::Element(ref group) = document.root.children[0] {
            assert_eq!(group.attr("fill"), Some("red"));
            assert_eq!(group.attr("stroke"), Some("blue"));
            assert_eq!(group.attr("opacity"), Some("0.5"));

            // Check that children no longer have these attributes
            for child in &group.children {
                if let Node::Element(elem) = child {
                    assert!(!elem.has_attr("fill"));
                    assert!(!elem.has_attr("stroke"));
                    assert!(!elem.has_attr("opacity"));
                }
            }
        }
    }

    #[test]
    fn test_group_already_has_attribute() {
        let plugin = MoveElemsAttrsToGroupPlugin::new();

        let mut group = create_test_element("g", vec![("fill", "green")]);
        group.children = vec![
            Node::Element(create_test_element("rect", vec![("fill", "red")])),
            Node::Element(create_test_element("circle", vec![("fill", "red")])),
        ];

        let mut document = Document::default();
        document.root.children = vec![Node::Element(group)];

        let result = plugin.apply(&mut document);
        assert!(result.is_ok());

        // Group should keep its original fill attribute
        if let Node::Element(ref group) = document.root.children[0] {
            assert_eq!(group.attr("fill"), Some("green"));

            // Children MUST keep fill="red" — removing it would cause them to inherit
            // the parent's fill="green", changing the visual output.
            for child in &group.children {
                if let Node::Element(elem) = child {
                    assert_eq!(elem.attr("fill"), Some("red"));
                }
            }
        }
    }

    #[test]
    fn test_single_child_no_change() {
        let plugin = MoveElemsAttrsToGroupPlugin::new();

        let mut group = create_test_element("g", vec![]);
        group.children = vec![Node::Element(create_test_element(
            "rect",
            vec![("fill", "red")],
        ))];

        let mut document = Document::default();
        document.root.children = vec![Node::Element(group.clone())];

        let result = plugin.apply(&mut document);
        assert!(result.is_ok());

        // No changes should be made with only one child
        if let Node::Element(ref result_group) = document.root.children[0] {
            assert!(!result_group.has_attr("fill"));

            if let Node::Element(ref rect) = result_group.children[0] {
                assert_eq!(rect.attr("fill"), Some("red"));
            }
        }
    }
}