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
// this_file: crates/vexy-vsvg-plugin-sdk/src/plugins/cleanup_enable_background.rs

//! Removes or simplifies redundant `enable-background` attributes.
//!
//! The `enable-background` attribute controls whether filter effects can access the
//! background image of a container. It's only needed when filters explicitly reference
//! `BackgroundImage` or `BackgroundAlpha`, but is often left in by graphics editors.
//!
//! ## What it does
//!
//! - **Removes `enable-background="new"`** when no filters use background input
//! - **Simplifies `enable-background="new x y w h"`** to `"new"` when coordinates
//!   match the element's viewport dimensions
//! - **Removes from non-viewport elements** (only `<svg>`, `<symbol>`, `<image>`,
//!   `<foreignObject>`, `<pattern>`, and `<mask>` establish viewports)
//!
//! ## Why it matters
//!
//! Most SVGs don't use filter effects that access the background. The attribute adds
//! bytes without changing rendering behavior.
//!
//! ## Reference
//!
//! Ported from SVGO's `cleanupEnableBackground` plugin.

use crate::Plugin;
use anyhow::Result;
use vexy_vsvg::ast::{Document, Element, Node};
use vexy_vsvg::error::VexyError;
use vexy_vsvg::visitor::Visitor;

/// Removes or simplifies unnecessary `enable-background` attributes.
#[derive(Default)]
pub struct CleanupEnableBackgroundPlugin {}

impl CleanupEnableBackgroundPlugin {
    /// Create a new CleanupEnableBackgroundPlugin
    pub fn new() -> Self {
        Self {}
    }
}

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

    fn description(&self) -> &'static str {
        "Remove or cleanup enable-background attribute when possible"
    }

    fn validate_params(&self, _params: &serde_json::Value) -> anyhow::Result<()> {
        // This plugin has no parameters
        Ok(())
    }

    fn apply(&self, document: &mut Document) -> anyhow::Result<()> {
        let mut visitor = CleanupEnableBackgroundVisitor::new();
        vexy_vsvg::visitor::walk_document(&mut visitor, document)?;
        CleanupEnableBackgroundVisitor::cleanup_formatting_whitespace_recursive(&mut document.root);
        Ok(())
    }
}

/// Visitor that walks the tree, tracking filter usage and cleaning enable-background.
struct CleanupEnableBackgroundVisitor {
    /// True if any filter primitive uses BackgroundImage or BackgroundAlpha input.
    has_background_image_filter: bool,
    /// True if any filter element exists in the document.
    has_any_filter: bool,
}

impl CleanupEnableBackgroundVisitor {
    fn new() -> Self {
        Self {
            has_background_image_filter: false,
            has_any_filter: false,
        }
    }

    /// Returns true for elements that establish a viewport and can have enable-background.
    fn is_viewport_element(element_name: &str) -> bool {
        matches!(
            element_name,
            "svg" | "symbol" | "image" | "foreignObject" | "pattern" | "mask"
        )
    }

    /// Returns true if text is only formatting whitespace (newlines, tabs) without content.
    fn is_formatting_whitespace(text: &str) -> bool {
        text.trim().is_empty() && text.chars().any(|c| matches!(c, '\n' | '\r' | '\t'))
    }

    fn cleanup_formatting_whitespace(nodes: &mut Vec<Node>) {
        let has_non_whitespace_content = nodes.iter().any(|node| match node {
            Node::Element(_) => true,
            Node::Text(text) => !text.trim().is_empty(),
            _ => false,
        });

        if has_non_whitespace_content {
            nodes.retain(
                |node| !matches!(node, Node::Text(text) if Self::is_formatting_whitespace(text)),
            );
        }
    }

    fn cleanup_formatting_whitespace_recursive(element: &mut Element<'_>) {
        let preserve = matches!(
            element.name.as_ref(),
            "text" | "tspan" | "tref" | "textPath" | "altGlyph"
        );
        for child in &mut element.children {
            if let Node::Text(text) = child {
                if !preserve && (text.contains('\n') || text.contains('\r') || text.contains('\t'))
                {
                    let trimmed = text.trim();
                    if !trimmed.is_empty() {
                        *text = trimmed.to_string().into();
                    }
                }
            }
        }
        Self::cleanup_formatting_whitespace(&mut element.children);
        for child in &mut element.children {
            if let Node::Element(child_element) = child {
                Self::cleanup_formatting_whitespace_recursive(child_element);
            }
        }
    }

    fn parse_number(value: &str) -> Option<f64> {
        value.trim().parse::<f64>().ok()
    }

    fn parse_enable_background(&self, value: &str) -> Option<EnableBackground> {
        let value = value.trim();

        if value == "new" {
            return Some(EnableBackground::New);
        }

        if value == "accumulate" {
            return Some(EnableBackground::Accumulate);
        }

        // Parse "new x y width height" format
        if let Some(stripped) = value.strip_prefix("new ") {
            let parts: Vec<&str> = stripped.split_whitespace().collect();
            if parts.len() == 4 {
                if let (Ok(_x), Ok(_y), Ok(_width), Ok(_height)) = (
                    parts[0].parse::<f64>(),
                    parts[1].parse::<f64>(),
                    parts[2].parse::<f64>(),
                    parts[3].parse::<f64>(),
                ) {
                    return Some(EnableBackground::NewWithCoords);
                }
            }
        }

        None
    }

    fn normalize_enable_background(&self, value: &str, element: &Element) -> Option<String> {
        if !Self::is_viewport_element(element.name.as_ref()) {
            return None;
        }

        if self.has_background_image_filter || self.element_has_filter_with_background(element) {
            return Some(value.to_string());
        }

        if let Some(EnableBackground::New) = self.parse_enable_background(value) {
            if self.has_any_filter {
                return Some(value.to_string());
            }
            return None;
        }

        if let Some(EnableBackground::NewWithCoords) = self.parse_enable_background(value) {
            let Some(stripped) = value.strip_prefix("new ") else {
                return Some(value.to_string());
            };
            let parts: Vec<&str> = stripped.split_whitespace().collect();
            if parts.len() == 4 {
                let x = Self::parse_number(parts[0]);
                let y = Self::parse_number(parts[1]);
                let width = Self::parse_number(parts[2]);
                let height = Self::parse_number(parts[3]);
                let element_width = element
                    .attributes
                    .get("width")
                    .and_then(|v| Self::parse_number(v));
                let element_height = element
                    .attributes
                    .get("height")
                    .and_then(|v| Self::parse_number(v));

                if let (
                    Some(x),
                    Some(y),
                    Some(width),
                    Some(height),
                    Some(element_width),
                    Some(element_height),
                ) = (x, y, width, height, element_width, element_height)
                {
                    let x_is_zero = x.abs() < f64::EPSILON;
                    let y_is_zero = y.abs() < f64::EPSILON;
                    let width_matches = (width - element_width).abs() < f64::EPSILON;
                    let height_matches = (height - element_height).abs() < f64::EPSILON;

                    if x_is_zero && y_is_zero && width_matches && height_matches {
                        if element.name == "svg" {
                            return None;
                        }
                        if self.has_any_filter {
                            return Some("new".to_string());
                        }
                        return None;
                    }
                }
            }
        }

        Some(value.to_string())
    }

    fn cleanup_style_attribute(style: &str) -> Option<String> {
        let mut kept_declarations = Vec::new();
        for declaration in style.split(';') {
            let trimmed = declaration.trim();
            if trimmed.is_empty() {
                continue;
            }
            let property_name = trimmed
                .split_once(':')
                .map(|(name, _)| name.trim())
                .unwrap_or("");
            if property_name == "enable-background" {
                continue;
            }
            kept_declarations.push(trimmed);
        }

        if kept_declarations.is_empty() {
            None
        } else {
            Some(kept_declarations.join("; "))
        }
    }

    fn element_has_filter_with_background(&self, element: &Element) -> bool {
        // Check if element has a filter attribute
        if element.attributes.contains_key("filter") {
            return true; // Conservative: assume filter might use background
        }

        // Check style attribute for filter property
        if let Some(style) = element.attributes.get("style") {
            if style.contains("filter:") || style.contains("filter ") {
                return true;
            }
        }

        false
    }

    fn check_for_background_image_filter(&mut self, element: &Element) {
        if element.name == "filter" {
            self.has_any_filter = true;
        }

        if element.name == "feImage" || element.name == "feBlend" {
            // Check for BackgroundImage or BackgroundAlpha usage
            if let Some(in_attr) = element.attributes.get("in") {
                if in_attr == "BackgroundImage" || in_attr == "BackgroundAlpha" {
                    self.has_background_image_filter = true;
                }
            }
            if let Some(in2_attr) = element.attributes.get("in2") {
                if in2_attr == "BackgroundImage" || in2_attr == "BackgroundAlpha" {
                    self.has_background_image_filter = true;
                }
            }
        }
    }
}

#[derive(Debug, PartialEq)]
enum EnableBackground {
    New,
    NewWithCoords,
    Accumulate,
}

impl Visitor<'_> for CleanupEnableBackgroundVisitor {
    fn visit_element_enter(&mut self, element: &mut Element<'_>) -> Result<(), VexyError> {
        // First check if this element has filter primitives that use background
        self.check_for_background_image_filter(element);

        Ok(())
    }

    fn visit_element_exit(&mut self, element: &mut Element<'_>) -> Result<(), VexyError> {
        // Process enable-background attribute after we've checked all children
        if let Some(enable_bg_value) = element.attributes.get("enable-background").cloned() {
            match self.normalize_enable_background(&enable_bg_value, element) {
                None => {
                    element.attributes.shift_remove("enable-background");
                }
                Some(normalized) => {
                    if normalized != enable_bg_value.as_ref() {
                        element
                            .attributes
                            .insert("enable-background".into(), normalized.into());
                    }
                }
            }
        }

        if let Some(style_value) = element.attributes.get("style").cloned() {
            match Self::cleanup_style_attribute(&style_value) {
                None => {
                    element.attributes.shift_remove("style");
                }
                Some(cleaned_style) => {
                    if cleaned_style != style_value.as_ref() {
                        element
                            .attributes
                            .insert("style".into(), cleaned_style.into());
                    }
                }
            }
        }

        Ok(())
    }
}

#[cfg(test)]
mod unit_tests {
    use super::*;
    use vexy_vsvg::ast::{Document, Element};

    #[test]
    fn test_plugin_creation() {
        let plugin = CleanupEnableBackgroundPlugin::new();
        assert_eq!(plugin.name(), "cleanupEnableBackground");
    }

    #[test]
    fn test_parse_enable_background() {
        let visitor = CleanupEnableBackgroundVisitor::new();

        assert_eq!(
            visitor.parse_enable_background("new"),
            Some(EnableBackground::New)
        );

        assert_eq!(
            visitor.parse_enable_background("accumulate"),
            Some(EnableBackground::Accumulate)
        );

        assert_eq!(
            visitor.parse_enable_background("new 0 0 100 100"),
            Some(EnableBackground::NewWithCoords)
        );

        assert_eq!(visitor.parse_enable_background("invalid"), None);
    }

    #[test]
    fn test_remove_default_new() {
        let plugin = CleanupEnableBackgroundPlugin::new();
        let mut doc = Document::new();

        // Add enable-background="new" to root element
        doc.root.set_attr("enable-background", "new");

        // Apply the plugin
        let result = plugin.apply(&mut doc);
        assert!(result.is_ok());

        // Check that enable-background was removed
        assert!(!doc.root.attributes.contains_key("enable-background"));
    }

    #[test]
    fn test_keep_with_coords() {
        let plugin = CleanupEnableBackgroundPlugin::new();
        let mut doc = Document::new();

        // Add enable-background with coordinates to SVG element
        doc.root.name = "svg".into();
        doc.root.set_attr("enable-background", "new 0 0 100 100");

        // Apply the plugin
        let result = plugin.apply(&mut doc);
        assert!(result.is_ok());

        // Check that enable-background was kept (SVG establishes viewport)
        assert!(doc.root.attributes.contains_key("enable-background"));
    }

    #[test]
    fn test_remove_from_non_viewport_element() {
        let plugin = CleanupEnableBackgroundPlugin::new();
        let mut doc = Document::new();

        // Create a g element with enable-background
        let mut g_element = Element::new("g");
        g_element.set_attr("enable-background", "new 0 0 100 100");

        doc.root
            .children
            .push(vexy_vsvg::ast::Node::Element(g_element));

        // Apply the plugin
        let result = plugin.apply(&mut doc);
        assert!(result.is_ok());

        // Check that enable-background was removed from g element
        if let vexy_vsvg::ast::Node::Element(ref g) = doc.root.children[0] {
            assert!(!g.attributes.contains_key("enable-background"));
        }
    }

    #[test]
    fn test_keep_with_filter() {
        let plugin = CleanupEnableBackgroundPlugin::new();
        let mut doc = Document::new();

        // Add enable-background and filter to element
        doc.root.set_attr("enable-background", "new");
        doc.root.set_attr("filter", "url(#myFilter)");

        // Apply the plugin
        let result = plugin.apply(&mut doc);
        assert!(result.is_ok());

        // Check that enable-background was kept due to filter
        assert!(doc.root.attributes.contains_key("enable-background"));
    }

    #[test]
    fn test_background_image_filter_detection() {
        let mut visitor = CleanupEnableBackgroundVisitor::new();

        // Test feBlend with BackgroundImage
        let mut element = Element::new("feBlend");
        element.set_attr("in", "BackgroundImage");
        visitor.check_for_background_image_filter(&element);
        assert!(visitor.has_background_image_filter);

        // Test feImage with BackgroundAlpha
        let mut visitor2 = CleanupEnableBackgroundVisitor::new();
        let mut element2 = Element::new("feImage");
        element2.set_attr("in2", "BackgroundAlpha");
        visitor2.check_for_background_image_filter(&element2);
        assert!(visitor2.has_background_image_filter);
    }
}

// Use parameterized testing framework for SVGO fixture tests
#[cfg(test)]
#[cfg(test)]
vexy_vsvg_test_utils::plugin_fixture_tests!(
    CleanupEnableBackgroundPlugin,
    "cleanupEnableBackground"
);