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

//! Removes width and height in presence of viewBox (opposite to removeViewBox)
//!
//! This plugin removes `width` and `height` attributes from the root `<svg>` element,
//! making the SVG fluid/responsive. Ensures a `viewBox` exists first (creates it if needed).
//!
//! ## What It Removes
//!
//! - `width` and `height` attributes from the root `<svg>` element only
//! - Does NOT touch nested `<svg>` elements
//!
//! ## What It Preserves/Creates
//!
//! - If no `viewBox` exists, creates one from `width` and `height` before removing them
//! - The SVG's intrinsic aspect ratio is preserved via the `viewBox`
//! - Does NOT add `preserveAspectRatio` (defaults to "xMidYMid meet")
//!
//! ## Why Use This
//!
//! - **Responsive SVG**: Allows CSS sizing (scales to container)
//! - **Fluid layout**: SVG adapts to parent element size
//! - **Modern web**: Common pattern for icon systems and responsive graphics
//!
//! ## Example
//!
//! Before:
//! ```xml
//! <svg width="100" height="50">
//!   <rect/>
//! </svg>
//! ```
//!
//! After:
//! ```xml
//! <svg viewBox="0 0 100 50">
//!   <rect/>
//! </svg>
//! ```
//!
//! ## SVGO Compatibility
//!
//! Ports SVGO's `removeDimensions` plugin. Opposite of `removeViewBox`.
//!
//! Reference: https://github.com/svg/svgo/blob/main/plugins/removeDimensions.js

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

use crate::Plugin;

/// Configuration for the removeDimensions plugin
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[derive(Default)]
pub struct RemoveDimensionsConfig {}

/// Removes width and height in presence of viewBox
pub struct RemoveDimensionsPlugin {
    #[allow(dead_code)]
    config: RemoveDimensionsConfig,
}

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

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

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

    fn process_svg_element(&self, element: &mut Element) {
        if element.name != "svg" {
            return;
        }

        let had_viewbox = element.has_attr("viewBox");

        // If viewBox already exists, just remove width and height
        if had_viewbox {
            element.remove_attr("width");
            element.remove_attr("height");
        } else {
            // Try to create viewBox from width and height if both are present and numeric
            let width_str = element.attr("width");
            let height_str = element.attr("height");

            if let (Some(width_str), Some(height_str)) = (width_str, height_str) {
                // Try to parse width and height as numbers
                if let (Ok(width), Ok(height)) =
                    (width_str.parse::<f64>(), height_str.parse::<f64>())
                {
                    // Only proceed if both are valid numbers (not NaN)
                    if !width.is_nan() && !height.is_nan() {
                        // Create viewBox and remove width/height
                        let viewbox = format!("0 0 {} {}", width, height);
                        element.set_attr("viewBox", &viewbox);
                        element.remove_attr("width");
                        element.remove_attr("height");
                    }
                }
            }
        }

        // Note: We do NOT add preserveAspectRatio="xMidYMid meet" here because
        // that is already the SVG spec default value. Adding it explicitly would be
        // redundant and would be stripped by removeUnknownsAndDefaults anyway.
    }

    fn process_element(&self, element: &mut Element) {
        // Process this element if it's an SVG element
        self.process_svg_element(element);

        // Process children recursively
        let mut i = 0;
        while i < element.children.len() {
            if let Node::Element(child) = &mut element.children[i] {
                self.process_element(child);
            }
            i += 1;
        }
    }
}

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

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

    fn description(&self) -> &'static str {
        "removes width and height in presence of viewBox (opposite to removeViewBox)"
    }

    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 indexmap::IndexMap;
    use vexy_vsvg::ast::{Document, Element, Node};

    use super::*;

    fn create_test_document() -> Document<'static> {
        Document {
            root: Element {
                name: "svg".into(),
                attributes: IndexMap::new(),
                namespaces: IndexMap::new(),
                children: vec![],
            },
            prologue: vec![],
            epilogue: vec![],
            metadata: vexy_vsvg::ast::DocumentMetadata {
                path: None,
                encoding: None,
                version: None,
                ..Default::default()
            },
            memory_budget: None,
        }
    }

    #[test]
    fn test_plugin_info() {
        let plugin = RemoveDimensionsPlugin::new();
        assert_eq!(plugin.name(), "removeDimensions");
        assert_eq!(
            plugin.description(),
            "removes width and height in presence of viewBox (opposite to removeViewBox)"
        );
    }

    #[test]
    fn test_param_validation() {
        let plugin = RemoveDimensionsPlugin::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_remove_dimensions_with_existing_viewbox() {
        let plugin = RemoveDimensionsPlugin::new();
        let mut doc = create_test_document();

        // Set up SVG with width, height, and viewBox
        doc.root.set_attr("width", "100");
        doc.root.set_attr("height", "50");
        doc.root.set_attr("viewBox", "0 0 200 100");

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

        // Width and height should be removed, viewBox should remain unchanged
        assert!(!doc.root.has_attr("width"));
        assert!(!doc.root.has_attr("height"));
        assert_eq!(doc.root.attr("viewBox"), Some("0 0 200 100"));
        // preserveAspectRatio is NOT added because "xMidYMid meet" is the SVG default
        assert!(!doc.root.has_attr("preserveAspectRatio"));
    }

    #[test]
    fn test_create_viewbox_from_dimensions() {
        let plugin = RemoveDimensionsPlugin::new();
        let mut doc = create_test_document();

        // Set up SVG with only width and height
        doc.root.set_attr("width", "100");
        doc.root.set_attr("height", "50");

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

        // Width and height should be removed, viewBox should be created
        assert!(!doc.root.has_attr("width"));
        assert!(!doc.root.has_attr("height"));
        assert_eq!(doc.root.attr("viewBox"), Some("0 0 100 50"));
        assert!(!doc.root.has_attr("preserveAspectRatio"));
    }

    #[test]
    fn test_decimal_dimensions() {
        let plugin = RemoveDimensionsPlugin::new();
        let mut doc = create_test_document();

        // Set up SVG with decimal dimensions
        doc.root.set_attr("width", "100.5");
        doc.root.set_attr("height", "50.25");

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

        // Width and height should be removed, viewBox should be created with decimals
        assert!(!doc.root.has_attr("width"));
        assert!(!doc.root.has_attr("height"));
        assert_eq!(doc.root.attr("viewBox"), Some("0 0 100.5 50.25"));
        assert!(!doc.root.has_attr("preserveAspectRatio"));
    }

    #[test]
    fn test_invalid_dimensions_ignored() {
        let plugin = RemoveDimensionsPlugin::new();
        let mut doc = create_test_document();

        // Set up SVG with invalid dimensions
        doc.root.set_attr("width", "invalid");
        doc.root.set_attr("height", "50");

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

        // Width and height should remain since they're not both valid numbers
        assert_eq!(doc.root.attr("width"), Some("invalid"));
        assert_eq!(doc.root.attr("height"), Some("50"));
        assert!(!doc.root.has_attr("viewBox"));
    }

    #[test]
    fn test_missing_dimension_ignored() {
        let plugin = RemoveDimensionsPlugin::new();
        let mut doc = create_test_document();

        // Set up SVG with only width
        doc.root.set_attr("width", "100");

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

        // Width should remain since height is missing
        assert_eq!(doc.root.attr("width"), Some("100"));
        assert!(!doc.root.has_attr("viewBox"));
    }

    #[test]
    fn test_only_processes_svg_elements() {
        let plugin = RemoveDimensionsPlugin::new();
        let mut doc = create_test_document();

        // Add a rect element with width and height (should not be processed)
        let mut rect = Element {
            name: "rect".into(),
            attributes: IndexMap::new(),
            namespaces: IndexMap::new(),
            children: vec![],
        };
        rect.set_attr("width", "100");
        rect.set_attr("height", "50");
        rect.set_attr("x", "10");
        rect.set_attr("y", "10");

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

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

        // Rect dimensions should remain unchanged
        if let Node::Element(rect) = &doc.root.children[0] {
            assert_eq!(rect.attr("width"), Some("100"));
            assert_eq!(rect.attr("height"), Some("50"));
            assert!(!rect.has_attr("viewBox"));
        } else {
            panic!("Expected rect element");
        }
    }

    #[test]
    fn test_nested_svg_elements() {
        let plugin = RemoveDimensionsPlugin::new();
        let mut doc = create_test_document();

        // Set up root SVG
        doc.root.set_attr("width", "200");
        doc.root.set_attr("height", "100");

        // Add nested SVG element
        let mut nested_svg = Element {
            name: "svg".into(),
            attributes: IndexMap::new(),
            namespaces: IndexMap::new(),
            children: vec![],
        };
        nested_svg.set_attr("width", "100");
        nested_svg.set_attr("height", "50");

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

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

        // Root SVG should have viewBox and no dimensions
        assert!(!doc.root.has_attr("width"));
        assert!(!doc.root.has_attr("height"));
        assert_eq!(doc.root.attr("viewBox"), Some("0 0 200 100"));
        assert!(!doc.root.has_attr("preserveAspectRatio"));

        // Nested SVG should also be processed
        if let Node::Element(nested_svg) = &doc.root.children[0] {
            assert!(!nested_svg.has_attr("width"));
            assert!(!nested_svg.has_attr("height"));
            assert_eq!(nested_svg.attr("viewBox"), Some("0 0 100 50"));
            assert!(!nested_svg.has_attr("preserveAspectRatio"));
        } else {
            panic!("Expected nested SVG element");
        }
    }

    #[test]
    fn test_zero_dimensions() {
        let plugin = RemoveDimensionsPlugin::new();
        let mut doc = create_test_document();

        // Set up SVG with zero dimensions
        doc.root.set_attr("width", "0");
        doc.root.set_attr("height", "0");

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

        // Should still create viewBox even with zero dimensions
        assert!(!doc.root.has_attr("width"));
        assert!(!doc.root.has_attr("height"));
        assert_eq!(doc.root.attr("viewBox"), Some("0 0 0 0"));
        assert!(!doc.root.has_attr("preserveAspectRatio"));
    }

    #[test]
    fn test_existing_preserve_aspect_ratio_is_not_overwritten() {
        let plugin = RemoveDimensionsPlugin::new();
        let mut doc = create_test_document();

        doc.root.set_attr("width", "100");
        doc.root.set_attr("height", "50");
        doc.root.set_attr("viewBox", "0 0 100 50");
        doc.root.set_attr("preserveAspectRatio", "none");

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

        assert_eq!(doc.root.attr("preserveAspectRatio"), Some("none"));
    }

    #[test]
    fn test_no_dimensions_no_change() {
        let plugin = RemoveDimensionsPlugin::new();
        let mut doc = create_test_document();

        // SVG with no width, height, or viewBox
        let original_count = doc.root.attributes.len();

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

        // Should not add any attributes
        assert_eq!(doc.root.attributes.len(), original_count);
        assert!(!doc.root.has_attr("width"));
        assert!(!doc.root.has_attr("height"));
        assert!(!doc.root.has_attr("viewBox"));
    }
}