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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
// this_file: crates/vexy-vsvg-plugin-sdk/src/plugins/cleanup_numeric_values.rs

//! Rounds numeric values to reduce file size while preserving visual fidelity.
//!
//! SVG coordinates and dimensions can have unnecessary decimal precision. This plugin
//! rounds numbers to a configurable precision and removes redundant units.
//!
//! ## What it does
//!
//! - **Rounds floats**: `10.123456` → `10.123` (default 3 decimals)
//! - **Strips leading zeros**: `0.5` → `.5` (saves 1 byte per number)
//! - **Removes default `px` units**: `width="100px"` → `width="100"` (px is assumed)
//! - **Converts units to px**: `10pt` → `13.333` (when beneficial)
//!
//! ## What it preserves
//!
//! - **Integers stay integers**: `10.0` → `10`, not `10.000`
//! - **Trailing zeros dropped**: `1.500` → `1.5`
//! - **Transform precision**: Separate precision for transforms (more critical)
//!
//! ## Configuration
//!
//! - `floatPrecision` (default: `3`) — Decimal places for coordinates
//! - `leadingZero` (default: `true`) — Keep leading zero in `.5` vs `0.5`
//! - `defaultPx` (default: `true`) — Remove `px` units where they're the default
//! - `convertToPx` (default: `true`) — Convert `pt`, `pc`, `mm`, `cm`, `in` to px
//!
//! ## Reference
//!
//! Ported from SVGO's `cleanupNumericValues` plugin.

use crate::Plugin;
use anyhow::Result;
use once_cell::sync::Lazy;
use regex::Regex;
use serde::{Deserialize, Serialize};
use vexy_vsvg::ast::{Document, Element};
use vexy_vsvg::error::VexyError;
use vexy_vsvg::visitor::Visitor;

/// Configuration for numeric value cleanup.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct CleanupNumericValuesParams {
    /// Number of decimal places to preserve (default: 3).
    pub float_precision: u8,
    /// Keep leading zero: `true` → `0.5`, `false` → `.5` (default: `false` for smaller output).
    pub leading_zero: bool,
    /// Remove `px` units where they're the default (e.g., `width`, `height`).
    pub default_px: bool,
    /// Convert `pt`, `mm`, `cm`, `in` to px when the result is shorter.
    pub convert_to_px: bool,
}

impl Default for CleanupNumericValuesParams {
    fn default() -> Self {
        Self {
            float_precision: 3,
            leading_zero: false,
            default_px: true,
            convert_to_px: true,
        }
    }
}

/// Rounds numeric values to reduce precision bloat and strips redundant units.
///
/// # Example
///
/// ```text
/// Before: <rect x="10.123456" y="20.000000" width="100px" height="50.5pt" />
/// After:  <rect x="10.123" y="20" width="100" height="67.333" />
/// ```
#[derive(Default)]
pub struct CleanupNumericValuesPlugin {
    params: CleanupNumericValuesParams,
}

impl CleanupNumericValuesPlugin {
    /// Create a new CleanupNumericValuesPlugin with default settings
    pub fn new() -> Self {
        Self {
            params: CleanupNumericValuesParams::default(),
        }
    }

    /// Create plugin with specific parameters
    pub fn with_params(params: CleanupNumericValuesParams) -> Self {
        Self { params }
    }

    fn parse_params(params: &serde_json::Value) -> anyhow::Result<CleanupNumericValuesParams> {
        if params.is_null() {
            return Ok(CleanupNumericValuesParams::default());
        }

        serde_json::from_value::<CleanupNumericValuesParams>(params.clone())
            .map_err(|e| anyhow::anyhow!("Invalid parameters: {}", e))
    }
}

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

    fn description(&self) -> &'static str {
        "Round numeric values to the fixed precision, remove default px units"
    }

    fn validate_params(&self, params: &serde_json::Value) -> anyhow::Result<()> {
        let _ = Self::parse_params(params)?;
        Ok(())
    }

    fn configure(&mut self, params: &serde_json::Value) -> anyhow::Result<()> {
        self.params = Self::parse_params(params)?;
        Ok(())
    }

    fn apply(&self, document: &mut Document) -> anyhow::Result<()> {
        // Use the default params for now
        let params = self.params.clone();

        let mut visitor = CleanupNumericValuesVisitor::new(params);
        vexy_vsvg::visitor::walk_document(&mut visitor, document)?;
        Ok(())
    }
}

// Regex patterns for numeric value detection
static NUMERIC_PATTERN: Lazy<Regex> = Lazy::new(|| {
    Regex::new(r"(-?\d*\.?\d+(?:[eE][+-]?\d+)?)\s*(px|pt|pc|mm|cm|in|em|ex|%)?").unwrap()
});

static TRANSFORM_NUMERIC: Lazy<Regex> =
    Lazy::new(|| Regex::new(r"-?\d*\.?\d+(?:[eE][+-]?\d+)?").unwrap());

/// Visitor that walks the document tree, rounding numbers in attributes.
struct CleanupNumericValuesVisitor {
    params: CleanupNumericValuesParams,
}

impl CleanupNumericValuesVisitor {
    fn new(params: CleanupNumericValuesParams) -> Self {
        Self { params }
    }

    fn round_numeric_value(&self, value: f64) -> String {
        if value.fract() == 0.0 {
            // Integer value
            format!("{:.0}", value)
        } else {
            let multiplier = 10f64.powi(self.params.float_precision as i32);
            let rounded = (value * multiplier).round() / multiplier;

            let mut result = format!(
                "{:.prec$}",
                rounded,
                prec = self.params.float_precision as usize
            );

            // Remove trailing zeros after decimal point
            if result.contains('.') {
                result = result
                    .trim_end_matches('0')
                    .trim_end_matches('.')
                    .to_string();
            }

            // Handle leading zero
            if !self.params.leading_zero && result.starts_with("0.") {
                result = result[1..].to_string();
            } else if !self.params.leading_zero && result.starts_with("-0.") {
                result = format!("-{}", &result[2..]);
            }

            result
        }
    }

    fn optimize_numeric_string(&self, value: &str, attribute_name: &str) -> String {
        if value.starts_with('#')
            || value.starts_with("url(")
            || value == "none"
            || value == "inherit"
            || value == "currentColor"
        {
            return value.to_string();
        }

        // Special handling for transform attributes
        if matches!(
            attribute_name,
            "transform" | "gradientTransform" | "patternTransform"
        ) {
            return self.optimize_transform_value(value);
        }

        if attribute_name == "viewBox" {
            return value
                .split(|c: char| c == ',' || c.is_whitespace())
                .filter(|token| !token.is_empty())
                .map(|token| {
                    token
                        .parse::<f64>()
                        .map(|num| self.round_numeric_value(num))
                        .unwrap_or_else(|_| token.to_string())
                })
                .collect::<Vec<_>>()
                .join(" ");
        }

        // For other attributes, use the general numeric pattern
        NUMERIC_PATTERN
            .replace_all(value, |caps: &regex::Captures| {
                let number_str = &caps[1];
                let unit = caps.get(2).map(|m| m.as_str()).unwrap_or("");

                if let Ok(num) = number_str.parse::<f64>() {
                    let rounded = self.round_numeric_value(num);

                    // Handle unit optimization
                    if unit == "px"
                        && self.params.default_px
                        && self.is_default_px_context(attribute_name)
                    {
                        // Remove px unit when it's the default
                        rounded
                    } else if !unit.is_empty()
                        && self.params.convert_to_px
                        && self.is_default_px_context(attribute_name)
                    {
                        if let Some(px_value) = self.convert_unit_to_px(num, unit) {
                            self.round_numeric_value(px_value)
                        } else {
                            format!("{}{}", rounded, unit)
                        }
                    } else if !unit.is_empty() {
                        // Keep the unit
                        format!("{}{}", rounded, unit)
                    } else {
                        rounded
                    }
                } else {
                    caps[0].to_string()
                }
            })
            .to_string()
    }

    fn optimize_transform_value(&self, value: &str) -> String {
        TRANSFORM_NUMERIC
            .replace_all(value, |caps: &regex::Captures| {
                let number_str = &caps[0];
                if let Ok(num) = number_str.parse::<f64>() {
                    self.round_numeric_value(num)
                } else {
                    caps[0].to_string()
                }
            })
            .to_string()
    }

    fn is_default_px_context(&self, attribute_name: &str) -> bool {
        // These attributes default to px units in SVG
        matches!(
            attribute_name,
            "x" | "y"
                | "x1"
                | "y1"
                | "x2"
                | "y2"
                | "width"
                | "height"
                | "rx"
                | "ry"
                | "r"
                | "cx"
                | "cy"
                | "fx"
                | "fy"
                | "markerWidth"
                | "markerHeight"
                | "refX"
                | "refY"
                | "stroke-width"
                | "stroke-dasharray"
                | "stroke-dashoffset"
                | "font-size"
                | "letter-spacing"
                | "word-spacing"
                | "baseline-shift"
        )
    }

    fn convert_unit_to_px(&self, value: f64, unit: &str) -> Option<f64> {
        let px_value = match unit {
            "px" => value,
            "pt" => value * (96.0 / 72.0),
            "pc" => value * 16.0,
            "mm" => value * (96.0 / 25.4),
            "cm" => value * (96.0 / 2.54),
            "in" => value * 96.0,
            _ => return None,
        };

        Some(px_value)
    }

    fn should_process_attribute(&self, name: &str) -> bool {
        !matches!(
            name,
            "version" | "id" | "class" | "preserveAspectRatio" | "xml:space" | "d" | "points"
        )
    }

    fn process_style_value(&self, style: &str) -> String {
        // Process CSS style values
        let mut result = String::new();

        for declaration in style.split(';') {
            let declaration = declaration.trim();
            if declaration.is_empty() {
                continue;
            }

            if let Some((property, value)) = declaration.split_once(':') {
                let property = property.trim();
                let value = value.trim();

                let optimized = if self.is_numeric_css_property(property) {
                    self.optimize_numeric_string(value, property)
                } else {
                    value.to_string()
                };

                if !result.is_empty() {
                    result.push_str("; ");
                }
                result.push_str(&format!("{}: {}", property, optimized));
            } else {
                if !result.is_empty() {
                    result.push_str("; ");
                }
                result.push_str(declaration);
            }
        }

        result
    }

    fn is_numeric_css_property(&self, property: &str) -> bool {
        matches!(
            property,
            "font-size"
                | "letter-spacing"
                | "word-spacing"
                | "line-height"
                | "stroke-width"
                | "stroke-dasharray"
                | "stroke-dashoffset"
                | "opacity"
                | "fill-opacity"
                | "stroke-opacity"
                | "stop-opacity"
                | "flood-opacity"
                | "baseline-shift"
                | "kerning"
                | "margin"
                | "padding"
                | "border-width"
                | "border-radius"
        )
    }
}

impl Visitor<'_> for CleanupNumericValuesVisitor {
    fn visit_element_enter(&mut self, element: &mut Element<'_>) -> Result<(), VexyError> {
        // Process regular attributes
        for (name, value) in element.attributes.iter_mut() {
            if self.should_process_attribute(name) && !value.is_empty() {
                if name == "style" {
                    // Special handling for style attribute
                    let optimized = self.process_style_value(value);
                    if optimized != value.as_ref() {
                        *value = optimized.into();
                    }
                } else {
                    let optimized = self.optimize_numeric_string(value, name);
                    if optimized != value.as_ref() {
                        *value = optimized.into();
                    }
                }
            }
        }

        Ok(())
    }
}

#[cfg(test)]
mod unit_tests {
    use super::*;
    use serde_json::json;
    use vexy_vsvg::ast::Document;

    #[test]
    fn test_plugin_creation() {
        let plugin = CleanupNumericValuesPlugin::new();
        assert_eq!(plugin.name(), "cleanupNumericValues");
        assert_eq!(plugin.params.float_precision, 3);
        assert!(!plugin.params.leading_zero);
        assert!(plugin.params.default_px);
        assert!(plugin.params.convert_to_px);
    }

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

        // Valid parameters
        assert!(plugin.validate_params(&json!({})).is_ok());
        assert!(plugin
            .validate_params(&json!({"floatPrecision": 2}))
            .is_ok());
        assert!(plugin
            .validate_params(&json!({"leadingZero": false}))
            .is_ok());
        assert!(plugin
            .validate_params(&json!({"defaultPx": true, "convertToPx": false}))
            .is_ok());

        // Invalid parameters
        assert!(plugin
            .validate_params(&json!({"floatPrecision": "invalid"}))
            .is_err());
        assert!(plugin
            .validate_params(&json!({"leadingZero": 123}))
            .is_err());
    }

    #[test]
    fn test_numeric_rounding() {
        let params = CleanupNumericValuesParams::default();
        let visitor = CleanupNumericValuesVisitor::new(params);

        // Test basic rounding
        assert_eq!(visitor.round_numeric_value(1.23456), "1.235");
        assert_eq!(visitor.round_numeric_value(1.0), "1");
        assert_eq!(visitor.round_numeric_value(0.5), ".5");
        assert_eq!(visitor.round_numeric_value(-1.23456), "-1.235");

        // Test without leading zero
        let params = CleanupNumericValuesParams {
            leading_zero: false,
            ..Default::default()
        };
        let visitor = CleanupNumericValuesVisitor::new(params);
        assert_eq!(visitor.round_numeric_value(0.5), ".5");
        assert_eq!(visitor.round_numeric_value(-0.5), "-.5");
    }

    #[test]
    fn test_unit_handling() {
        let params = CleanupNumericValuesParams::default();
        let visitor = CleanupNumericValuesVisitor::new(params);

        // Test px removal
        assert_eq!(visitor.optimize_numeric_string("10px", "width"), "10");
        assert_eq!(visitor.optimize_numeric_string("10px", "height"), "10");

        // Test keeping other units
        assert_eq!(visitor.optimize_numeric_string("10em", "width"), "10em");
        assert_eq!(visitor.optimize_numeric_string("50%", "width"), "50%");

        // Test non-default-px contexts
        assert_eq!(visitor.optimize_numeric_string("10px", "stroke"), "10px");
    }

    #[test]
    fn test_transform_optimization() {
        let params = CleanupNumericValuesParams::default();
        let visitor = CleanupNumericValuesVisitor::new(params);

        assert_eq!(
            visitor.optimize_numeric_string("translate(10.12345, 20.98765)", "transform"),
            "translate(10.123, 20.988)"
        );

        assert_eq!(
            visitor.optimize_numeric_string("scale(1.00000)", "transform"),
            "scale(1)"
        );
    }

    #[test]
    fn test_style_processing() {
        let params = CleanupNumericValuesParams::default();
        let visitor = CleanupNumericValuesVisitor::new(params);

        assert_eq!(
            visitor.process_style_value("font-size: 14.5678px; stroke-width: 2.0000"),
            "font-size: 14.568; stroke-width: 2"
        );

        assert_eq!(
            visitor.process_style_value("opacity: 0.50000; fill: red"),
            "opacity: .5; fill: red"
        );
    }

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

        // Add attributes to root element for testing
        doc.root.set_attr("width", "100.12345px");
        doc.root.set_attr("height", "50.00000");
        doc.root.set_attr("transform", "scale(1.23456789)");
        doc.root.set_attr("style", "stroke-width: 2.50000px");

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

        // Check that values were cleaned
        assert_eq!(doc.root.attr("width"), Some("100.123"));
        assert_eq!(doc.root.attr("height"), Some("50"));
        assert_eq!(doc.root.attr("transform"), Some("scale(1.235)"));
        assert_eq!(doc.root.attr("style"), Some("stroke-width: 2.5"));
    }
}

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