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

//! Remove raster images plugin implementation
//!
//! This plugin removes `<image>` elements that reference raster image formats (JPEG, PNG, GIF).
//! Useful for creating vector-only SVGs or stripping embedded bitmaps.
//!
//! ## What It Removes
//!
//! `<image>` elements where `href` or `xlink:href` matches raster formats:
//! - JPEG: `.jpg`, `.jpeg`, `image/jpeg`
//! - PNG: `.png`, `image/png`
//! - GIF: `.gif`, `image/gif`
//!
//! Detection uses regex pattern: `(\.|image/)(jpe?g|png|gif)`
//!
//! ## What It Preserves
//!
//! - `<image>` elements referencing SVG files
//! - `<image>` elements with data URIs for vector formats
//! - All other SVG elements
//!
//! ## Why Use This
//!
//! - **Vector-only workflow**: Remove raster content from SVG
//! - **File size**: Embedded base64 images can be huge
//! - **Scalability**: Raster images don't scale well in SVG
//! - **Processing**: Simplify SVG for further optimization
//!
//! ## Configuration
//!
//! This plugin accepts no configuration parameters.
//!
//! ## Example
//!
//! Before:
//! ```xml
//! <svg>
//!   <image href="photo.jpg" width="100" height="100"/>
//!   <image href="icon.svg" width="50" height="50"/>
//!   <rect/>
//! </svg>
//! ```
//!
//! After:
//! ```xml
//! <svg>
//!   <image href="icon.svg" width="50" height="50"/>
//!   <rect/>
//! </svg>
//! ```
//!
//! ## SVGO Compatibility
//!
//! Ports SVGO's `removeRasterImages` plugin. Uses same regex pattern.
//!
//! Reference: https://github.com/svg/svgo/blob/main/plugins/removeRasterImages.js

use crate::Plugin;
use anyhow::Result;
use regex::Regex;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use vexy_vsvg::ast::{Document, Element, Node};

/// Configuration parameters for remove raster images plugin
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[derive(Default)]
pub struct RemoveRasterImagesConfig {
    // No configuration options for this plugin
}

/// Plugin that removes raster images
pub struct RemoveRasterImagesPlugin {
    config: RemoveRasterImagesConfig,
    raster_pattern: Regex,
}

impl RemoveRasterImagesPlugin {
    /// Create a new RemoveRasterImagesPlugin
    pub fn new() -> Self {
        // Pattern to match raster image references
        // Matches: .jpg, .jpeg, .png, .gif or image/jpeg, image/png, image/gif
        let raster_pattern =
            Regex::new(r"(\.|image/)(jpe?g|png|gif)").expect("Invalid regex pattern");

        Self {
            config: RemoveRasterImagesConfig::default(),
            raster_pattern,
        }
    }

    /// Create a new RemoveRasterImagesPlugin with config
    pub fn with_config(config: RemoveRasterImagesConfig) -> Self {
        let mut plugin = Self::new();
        plugin.config = config;
        plugin
    }

    /// Parse configuration from JSON
    fn parse_config(params: &Value) -> Result<RemoveRasterImagesConfig> {
        if params.is_null() {
            Ok(RemoveRasterImagesConfig::default())
        } else if params.is_object() {
            serde_json::from_value(params.clone())
                .map_err(|e| anyhow::anyhow!("Invalid configuration: {}", e))
        } else {
            Err(anyhow::anyhow!("Configuration must be an object"))
        }
    }

    /// Check if element is a raster image
    fn is_raster_image(&self, element: &Element) -> bool {
        if element.name != "image" {
            return false;
        }

        // Check xlink:href attribute
        if let Some(href) = element.attributes.get("xlink:href") {
            if self.raster_pattern.is_match(href) {
                return true;
            }
        }

        // Also check href attribute (SVG2 style)
        if let Some(href) = element.attributes.get("href") {
            if self.raster_pattern.is_match(href) {
                return true;
            }
        }

        false
    }

    /// Process element to remove raster images
    fn process_element(&self, element: &mut Element) {
        // Remove image elements that reference raster images
        element.children.retain(|child| {
            if let Node::Element(elem) = child {
                !self.is_raster_image(elem)
            } else {
                true
            }
        });

        // Recursively process children
        for child in &mut element.children {
            if let Node::Element(elem) = child {
                self.process_element(elem);
            }
        }
    }
}

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

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

    fn description(&self) -> &'static str {
        "removes raster images (disabled by default)"
    }

    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 unit_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
    }

    #[test]
    fn test_plugin_creation() {
        let plugin = RemoveRasterImagesPlugin::new();
        assert_eq!(plugin.name(), "removeRasterImages");
        assert_eq!(
            plugin.description(),
            "removes raster images (disabled by default)"
        );
    }

    #[test]
    fn test_removes_jpeg_images() {
        let plugin = RemoveRasterImagesPlugin::new();

        let mut doc = Document::new();
        doc.root = create_element("svg");

        // Add JPEG image
        let mut image = create_element("image");
        image.set_attr("xlink:href", "photo.jpg");
        doc.root.children.push(Node::Element(image));

        // Add SVG image (should be preserved)
        let mut svg_image = create_element("image");
        svg_image.set_attr("xlink:href", "icon.svg");
        doc.root.children.push(Node::Element(svg_image));

        // Apply plugin
        plugin.apply(&mut doc).unwrap();

        // Check that only SVG image remains
        assert_eq!(doc.root.children.len(), 1);
        if let Node::Element(elem) = &doc.root.children[0] {
            assert_eq!(elem.attr("xlink:href"), Some("icon.svg"));
        }
    }

    #[test]
    fn test_removes_png_images() {
        let plugin = RemoveRasterImagesPlugin::new();

        let mut doc = Document::new();
        doc.root = create_element("svg");

        // Add PNG image
        let mut image = create_element("image");
        image.set_attr("xlink:href", "logo.png");
        doc.root.children.push(Node::Element(image));

        // Apply plugin
        plugin.apply(&mut doc).unwrap();

        // Check that image was removed
        assert_eq!(doc.root.children.len(), 0);
    }

    #[test]
    fn test_removes_gif_images() {
        let plugin = RemoveRasterImagesPlugin::new();

        let mut doc = Document::new();
        doc.root = create_element("svg");

        // Add GIF image
        let mut image = create_element("image");
        image.set_attr("xlink:href", "animation.gif");
        doc.root.children.push(Node::Element(image));

        // Apply plugin
        plugin.apply(&mut doc).unwrap();

        // Check that image was removed
        assert_eq!(doc.root.children.len(), 0);
    }

    #[test]
    fn test_removes_data_uri_raster_images() {
        let plugin = RemoveRasterImagesPlugin::new();

        let mut doc = Document::new();
        doc.root = create_element("svg");

        // Add data URI JPEG
        let mut image1 = create_element("image");
        image1.set_attr("xlink:href", "data:image/jpeg;base64,/9j/4AAQ...");
        doc.root.children.push(Node::Element(image1));

        // Add data URI PNG
        let mut image2 = create_element("image");
        image2.set_attr("xlink:href", "data:image/png;base64,iVBORw0KGg...");
        doc.root.children.push(Node::Element(image2));

        // Apply plugin
        plugin.apply(&mut doc).unwrap();

        // Check that both images were removed
        assert_eq!(doc.root.children.len(), 0);
    }

    #[test]
    fn test_removes_svg2_href_images() {
        let plugin = RemoveRasterImagesPlugin::new();

        let mut doc = Document::new();
        doc.root = create_element("svg");

        // Add image with SVG2 href attribute
        let mut image = create_element("image");
        image.set_attr("href", "picture.jpeg");
        doc.root.children.push(Node::Element(image));

        // Apply plugin
        plugin.apply(&mut doc).unwrap();

        // Check that image was removed
        assert_eq!(doc.root.children.len(), 0);
    }

    #[test]
    fn test_preserves_vector_images() {
        let plugin = RemoveRasterImagesPlugin::new();

        let mut doc = Document::new();
        doc.root = create_element("svg");

        // Add various vector image formats
        let mut svg_image = create_element("image");
        svg_image.set_attr("xlink:href", "vector.svg");
        doc.root.children.push(Node::Element(svg_image));

        let mut pdf_image = create_element("image");
        pdf_image.set_attr("xlink:href", "document.pdf");
        doc.root.children.push(Node::Element(pdf_image));

        let mut data_svg = create_element("image");
        data_svg.set_attr("xlink:href", "data:image/svg+xml;base64,PHN2Zy...");
        doc.root.children.push(Node::Element(data_svg));

        // Apply plugin
        plugin.apply(&mut doc).unwrap();

        // Check that all vector images were preserved
        assert_eq!(doc.root.children.len(), 3);
    }

    #[test]
    fn test_removes_nested_raster_images() {
        let plugin = RemoveRasterImagesPlugin::new();

        let mut doc = Document::new();
        doc.root = create_element("svg");

        // Create nested structure
        let mut group = create_element("g");

        let mut image1 = create_element("image");
        image1.set_attr("xlink:href", "nested.jpg");
        group.children.push(Node::Element(image1));

        let rect = create_element("rect");
        group.children.push(Node::Element(rect));

        let mut defs = create_element("defs");
        let mut pattern = create_element("pattern");
        let mut image2 = create_element("image");
        image2.set_attr("href", "pattern.png");
        pattern.children.push(Node::Element(image2));
        defs.children.push(Node::Element(pattern));
        group.children.push(Node::Element(defs));

        doc.root.children.push(Node::Element(group));

        // Apply plugin
        plugin.apply(&mut doc).unwrap();

        // Check nested removal
        if let Node::Element(g) = &doc.root.children[0] {
            // First child should be rect (image removed)
            if let Node::Element(r) = &g.children[0] {
                assert_eq!(r.name, "rect");
            }

            // Check pattern has no image
            if let Node::Element(d) = &g.children[1] {
                if let Node::Element(p) = &d.children[0] {
                    assert_eq!(p.children.len(), 0);
                }
            }
        }
    }

    #[test]
    fn test_ignores_non_image_elements() {
        let plugin = RemoveRasterImagesPlugin::new();

        let mut doc = Document::new();
        doc.root = create_element("svg");

        // Add elements with raster-like hrefs that aren't images
        let mut use_elem = create_element("use");
        use_elem.set_attr("xlink:href", "icon.png");
        doc.root.children.push(Node::Element(use_elem));

        let mut a_elem = create_element("a");
        a_elem.set_attr("href", "photo.jpg");
        doc.root.children.push(Node::Element(a_elem));

        // Apply plugin
        plugin.apply(&mut doc).unwrap();

        // Check that non-image elements were preserved
        assert_eq!(doc.root.children.len(), 2);
    }

    #[test]
    fn test_empty_document() {
        let plugin = RemoveRasterImagesPlugin::new();

        let mut doc = Document::new();
        doc.root = create_element("svg");

        // Apply plugin to empty document
        let result = plugin.apply(&mut doc);
        assert!(result.is_ok());
    }

    #[test]
    fn test_parameter_validation() {
        let plugin = RemoveRasterImagesPlugin::new();

        // Empty object is valid
        assert!(plugin.validate_params(&json!({})).is_ok());

        // Null is valid
        assert!(plugin.validate_params(&Value::Null).is_ok());

        // Non-object is invalid
        assert!(plugin.validate_params(&json!("invalid")).is_err());
    }
}

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