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
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
// this_file: crates/vexy-vsvg-plugin-sdk/src/plugins/convert_shape_to_path.rs

//! Convert basic shapes to paths for better compression.
//!
//! This plugin ports SVGO's `convertShapeToPath` plugin. SVG has specialized elements for
//! common shapes (`<rect>`, `<circle>`, `<line>`, etc.) but these can often be expressed
//! more compactly as `<path>` elements. Converting to paths also enables further optimizations
//! like path data minification and merging multiple shapes into one path.
//!
//! # Before
//! ```xml
//! <rect x="10" y="20" width="30" height="40"/>
//! <polygon points="20,10 50,40 30,20"/>
//! ```
//!
//! # After
//! ```xml
//! <path d="M10 20H40V60H10z"/>
//! <path d="M20 10 50 40 30 20z"/>
//! ```
//!
//! # Why paths?
//! - Rectangles: `M x y H x+w V y+h H x z` is often shorter than attributes
//! - Lines: `M x1 y1 x2 y2` removes attribute overhead
//! - Polylines/polygons: Already coordinate lists, just need `M` prefix
//! - Circles/ellipses: Convertible to arc commands (optional, disabled by default)
//!
//! # Savings
//! - Simple rect: 35 bytes → 18 bytes (saves 17 bytes)
//! - Line: 30 bytes → 16 bytes (saves 14 bytes)
//! - Sets up further optimizations in the `convertPathData` plugin
//!
//! SVGO Reference: https://github.com/svg/svgo

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

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

/// Configuration for the convert shape to path plugin.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[derive(Default)]
pub struct ConvertShapeToPathConfig {
    /// Whether to convert circles and ellipses to paths using arc commands.
    ///
    /// Disabled by default because `<circle>` and `<ellipse>` are usually more compact
    /// than their path equivalents (which require two arc commands to form a closed loop).
    /// Enable this only if you need all shapes unified as paths for downstream processing.
    #[serde(default)]
    pub convert_arcs: bool,

    /// Number of decimal places for numeric values in path data.
    ///
    /// When `None`, uses default formatting (removes `.0` from integers).
    /// Example: `Some(2)` formats `10.123` as `10.12`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub float_precision: Option<u8>,
}

/// Plugin that converts basic shapes to path elements
pub struct ConvertShapeToPathPlugin {
    config: ConvertShapeToPathConfig,
}

impl ConvertShapeToPathPlugin {
    pub fn new() -> Self {
        Self {
            config: ConvertShapeToPathConfig::default(),
        }
    }

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

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

    /// Recursively convert shapes in an element and its children
    fn convert_shapes_in_element(&self, element: &mut Element) {
        // Process child elements first
        for child in &mut element.children {
            if let Node::Element(child_element) = child {
                self.convert_shapes_in_element(child_element);
            }
        }

        // Convert current element if it's a shape
        self.convert_shape_element(element);
    }

    /// Convert a shape element to a path if applicable
    fn convert_shape_element(&self, element: &mut Element) {
        match element.name.as_ref() {
            "rect" => self.convert_rect(element),
            "line" => self.convert_line(element),
            "polyline" => self.convert_polyline(element),
            "polygon" => self.convert_polygon(element),
            "circle" if self.config.convert_arcs => self.convert_circle(element),
            "ellipse" if self.config.convert_arcs => self.convert_ellipse(element),
            _ => {}
        }
    }

    /// Parse a coordinate value, returning None if it contains units or percentages.
    ///
    /// We only convert shapes with unitless numeric coordinates. Shapes with units
    /// (`100px`, `50%`) require preserving the original element type since path data
    /// doesn't support units on individual coordinates.
    fn parse_coord(value: &str) -> Option<f64> {
        // Reject values with units or percentages (e.g., "100%", "50px", "2em")
        if value.contains('%') || value.contains("px") || value.contains("pt") {
            return None;
        }
        value.parse().ok()
    }

    /// Convert a rectangle to a path.
    ///
    /// Generates path data using horizontal and vertical line commands for compactness:
    /// `M x y H x+width V y+height H x z`
    ///
    /// This uses:
    /// - `M` (moveto) to top-left corner
    /// - `H` (horizontal lineto) for top edge
    /// - `V` (vertical lineto) for right edge
    /// - `H` (horizontal lineto) for bottom edge
    /// - `z` (closepath) returns to start, completing left edge
    ///
    /// Skips rectangles with rounded corners (`rx`/`ry` attributes) since path arcs
    /// for rounded corners are more complex and often larger than the original element.
    fn convert_rect(&self, element: &mut Element) {
        // Don't convert rectangles with rounded corners (rx/ry create complex arc paths)
        if element.has_attr("rx") || element.has_attr("ry") {
            return;
        }

        // Extract required attributes (width and height are mandatory)
        let width_str = match element.attr("width") {
            Some(w) => w,
            None => return,
        };
        let height_str = match element.attr("height") {
            Some(h) => h,
            None => return,
        };

        // Parse coordinates (x and y default to 0 per SVG spec)
        let x = match Self::parse_coord(element.attr("x").unwrap_or("0")) {
            Some(x) => x,
            None => return, // Has units, can't convert
        };
        let y = match Self::parse_coord(element.attr("y").unwrap_or("0")) {
            Some(y) => y,
            None => return,
        };
        let width = match Self::parse_coord(width_str) {
            Some(w) => w,
            None => return,
        };
        let height = match Self::parse_coord(height_str) {
            Some(h) => h,
            None => return,
        };

        // Build path: move to top-left, draw three edges, close path for fourth edge
        let path_data = format!(
            "M{} {}H{}V{}H{}z",
            self.format_number(x),
            self.format_number(y),
            self.format_number(x + width),
            self.format_number(y + height),
            self.format_number(x)
        );

        // Replace element type and attributes
        element.name = "path".to_string().into();
        element.set_attr("d", &path_data);
        element.remove_attr("x");
        element.remove_attr("y");
        element.remove_attr("width");
        element.remove_attr("height");
    }

    /// Convert a line to a path.
    ///
    /// Lines become `M x1 y1 x2 y2` (implicit lineto after moveto).
    /// We omit the explicit `L` command because SVG path grammar treats coordinates
    /// after `M` as an implicit `L` command, saving one byte.
    fn convert_line(&self, element: &mut Element) {
        // Parse line endpoints (default to 0 per SVG spec)
        let x1 = match Self::parse_coord(element.attr("x1").unwrap_or("0")) {
            Some(x) => x,
            None => return,
        };
        let y1 = match Self::parse_coord(element.attr("y1").unwrap_or("0")) {
            Some(y) => y,
            None => return,
        };
        let x2 = match Self::parse_coord(element.attr("x2").unwrap_or("0")) {
            Some(x) => x,
            None => return,
        };
        let y2 = match Self::parse_coord(element.attr("y2").unwrap_or("0")) {
            Some(y) => y,
            None => return,
        };

        // Build path: moveto start, implicit lineto end (no 'L' needed)
        let path_data = format!(
            "M{} {} {} {}",
            self.format_number(x1),
            self.format_number(y1),
            self.format_number(x2),
            self.format_number(y2)
        );

        // Replace element type and attributes
        element.name = "path".to_string().into();
        element.set_attr("d", &path_data);
        element.remove_attr("x1");
        element.remove_attr("y1");
        element.remove_attr("x2");
        element.remove_attr("y2");
    }

    /// Convert polyline to a path
    fn convert_polyline(&self, element: &mut Element) {
        self.convert_poly(element, false);
    }

    /// Convert polygon to a path
    fn convert_polygon(&self, element: &mut Element) {
        self.convert_poly(element, true);
    }

    /// Convert polyline or polygon to a path.
    ///
    /// Both polyline and polygon use a `points` attribute with coordinate pairs.
    /// We parse all numbers from the points string (handles both comma and space separators),
    /// then build path data with an initial `M` command followed by implicit linetos.
    ///
    /// Polygons get a trailing `z` to close the path. Polylines stay open.
    ///
    /// Invalid shapes (fewer than 2 coordinate pairs) are marked for deletion by
    /// setting their name to an empty string.
    fn convert_poly(&self, element: &mut Element, is_polygon: bool) {
        let points_str = match element.attr("points") {
            Some(p) => p,
            None => return,
        };

        // Extract all numbers from the points string using a regex
        // Handles "10,20 30,40" and "10 20 30 40" and "10, 20, 30, 40"
        let coords: Vec<f64> = NUMBER_REGEX
            .find_iter(points_str)
            .filter_map(|m| m.as_str().parse().ok())
            .collect();

        // Need at least 2 coordinate pairs (4 numbers) to form a line
        if coords.len() < 4 {
            // Mark element for removal (invalid shape)
            element.attributes.clear();
            element.children.clear();
            element.name = "".into(); // Empty name signals deletion
            return;
        }

        // Build path data: M x1 y1 x2 y2 x3 y3 ...
        let mut path_data = String::new();

        for (i, chunk) in coords.chunks(2).enumerate() {
            if chunk.len() == 2 {
                if i == 0 {
                    // First point: use M (moveto)
                    path_data.push_str(&format!(
                        "M{} {}",
                        self.format_number(chunk[0]),
                        self.format_number(chunk[1])
                    ));
                } else {
                    // Subsequent points: implicit lineto (just coordinates)
                    path_data.push_str(&format!(
                        " {} {}",
                        self.format_number(chunk[0]),
                        self.format_number(chunk[1])
                    ));
                }
            }
        }

        // Polygons need a closing z command to connect back to start
        if is_polygon {
            path_data.push('z');
        }

        // Replace element type and attributes
        element.name = "path".to_string().into();
        element.set_attr("d", &path_data);
        element.remove_attr("points");
    }

    /// Convert circle to a path using arc commands.
    ///
    /// A circle requires two 180-degree arcs to form a complete loop:
    /// - Arc from top (cx, cy-r) to bottom (cx, cy+r)
    /// - Arc from bottom back to top
    /// - Close path with `z`
    ///
    /// Arc syntax: `A rx ry x-axis-rotation large-arc-flag sweep-flag x y`
    /// - `rx ry`: radii (equal for circles)
    /// - `0`: no rotation
    /// - `1`: large-arc-flag (180-degree arc)
    /// - `0`: sweep-flag (counterclockwise)
    ///
    /// Only runs when `convert_arcs: true` in config (disabled by default since
    /// `<circle>` is usually more compact than the path equivalent).
    fn convert_circle(&self, element: &mut Element) {
        // Parse circle center and radius (default to 0 per SVG spec)
        let cx = match Self::parse_coord(element.attr("cx").unwrap_or("0")) {
            Some(x) => x,
            None => return,
        };
        let cy = match Self::parse_coord(element.attr("cy").unwrap_or("0")) {
            Some(y) => y,
            None => return,
        };
        let r = match Self::parse_coord(element.attr("r").unwrap_or("0")) {
            Some(r) => r,
            None => return,
        };

        // Build path with two 180-degree arcs
        let path_data = format!(
            "M{} {}A{} {} 0 1 0 {} {}A{} {} 0 1 0 {} {}z",
            self.format_number(cx),
            self.format_number(cy - r), // Start at top
            self.format_number(r),
            self.format_number(r),
            self.format_number(cx),
            self.format_number(cy + r), // Arc to bottom
            self.format_number(r),
            self.format_number(r),
            self.format_number(cx),
            self.format_number(cy - r) // Arc back to top
        );

        // Replace element type and attributes
        element.name = "path".to_string().into();
        element.set_attr("d", &path_data);
        element.remove_attr("cx");
        element.remove_attr("cy");
        element.remove_attr("r");
    }

    /// Convert ellipse to a path using arc commands.
    ///
    /// Like circles, ellipses need two 180-degree arcs, but with different x and y radii.
    /// Same arc command structure as `convert_circle`, but with `rx` and `ry` instead of
    /// a single radius.
    ///
    /// Only runs when `convert_arcs: true` in config.
    fn convert_ellipse(&self, element: &mut Element) {
        // Parse ellipse center and radii (default to 0 per SVG spec)
        let cx = match Self::parse_coord(element.attr("cx").unwrap_or("0")) {
            Some(x) => x,
            None => return,
        };
        let cy = match Self::parse_coord(element.attr("cy").unwrap_or("0")) {
            Some(y) => y,
            None => return,
        };
        let rx = match Self::parse_coord(element.attr("rx").unwrap_or("0")) {
            Some(r) => r,
            None => return,
        };
        let ry = match Self::parse_coord(element.attr("ry").unwrap_or("0")) {
            Some(r) => r,
            None => return,
        };

        // Build path with two 180-degree arcs (vertical orientation)
        let path_data = format!(
            "M{} {}A{} {} 0 1 0 {} {}A{} {} 0 1 0 {} {}z",
            self.format_number(cx),
            self.format_number(cy - ry), // Start at top
            self.format_number(rx),
            self.format_number(ry),
            self.format_number(cx),
            self.format_number(cy + ry), // Arc to bottom
            self.format_number(rx),
            self.format_number(ry),
            self.format_number(cx),
            self.format_number(cy - ry) // Arc back to top
        );

        // Replace element type and attributes
        element.name = "path".to_string().into();
        element.set_attr("d", &path_data);
        element.remove_attr("cx");
        element.remove_attr("cy");
        element.remove_attr("rx");
        element.remove_attr("ry");
    }

    /// Format a number with optional precision control.
    ///
    /// When `float_precision` is set, rounds to that many decimal places and removes
    fn format_number(&self, value: f64) -> String {
        let trimmed = match self.config.float_precision {
            Some(p) => {
                let formatted = format!("{:.1$}", value, p as usize);
                let t = formatted.trim_end_matches('0').trim_end_matches('.');
                if t.is_empty() || t == "-" {
                    return "0".to_string();
                }
                t.to_string()
            }
            None => {
                if value.fract() == 0.0 {
                    return format!("{}", value as i64);
                }
                value.to_string()
            }
        };
        // Strip leading zero: "0.5" → ".5", "-0.5" → "-.5"
        if let Some(rest) = trimmed.strip_prefix("0.") {
            return format!(".{rest}");
        }
        if let Some(rest) = trimmed.strip_prefix("-0.") {
            return format!("-.{rest}");
        }
        trimmed
    }
}

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

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

    fn description(&self) -> &'static str {
        "converts basic shapes to more compact path form"
    }

    fn validate_params(&self, params: &Value) -> Result<()> {
        Self::parse_config(params)?;
        Ok(())
    }

    fn apply(&self, document: &mut Document) -> Result<()> {
        self.convert_shapes_in_element(&mut document.root);

        // Clean up any elements marked for removal (empty name)
        Self::remove_empty_elements(&mut document.root);

        Ok(())
    }
}

impl ConvertShapeToPathPlugin {
    /// Remove elements that were marked for deletion (empty name)
    fn remove_empty_elements(element: &mut Element) {
        element.children.retain(|child| {
            if let Node::Element(elem) = child {
                !elem.name.is_empty()
            } else {
                true
            }
        });

        // Recursively clean children
        for child in &mut element.children {
            if let Node::Element(child_elem) = child {
                Self::remove_empty_elements(child_elem);
            }
        }
    }
}

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

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

    #[test]
    fn test_plugin_info() {
        let plugin = ConvertShapeToPathPlugin::new();
        assert_eq!(plugin.name(), "convertShapeToPath");
        assert_eq!(
            plugin.description(),
            "converts basic shapes to more compact path form"
        );
    }

    #[test]
    fn test_param_validation() {
        let plugin = ConvertShapeToPathPlugin::new();

        // Test null params
        assert!(plugin.validate_params(&Value::Null).is_ok());

        // Test empty object
        assert!(plugin.validate_params(&serde_json::json!({})).is_ok());

        // Test valid params
        assert!(plugin
            .validate_params(&serde_json::json!({
                "convertArcs": true,
                "floatPrecision": 3
            }))
            .is_ok());

        // Test invalid params
        assert!(plugin
            .validate_params(&serde_json::json!({
                "invalidParam": true
            }))
            .is_err());
    }

    #[test]
    fn test_convert_rect_basic() {
        let mut element = create_element("rect", vec![("width", "32"), ("height", "32")]);
        let plugin = ConvertShapeToPathPlugin::new();

        plugin.convert_rect(&mut element);

        assert_eq!(element.name, "path");
        assert_eq!(element.attr("d").unwrap(), "M0 0H32V32H0z");
        assert!(!element.has_attr("width"));
        assert!(!element.has_attr("height"));
    }

    #[test]
    fn test_convert_rect_with_position() {
        let mut element = create_element(
            "rect",
            vec![("x", "20"), ("y", "10"), ("width", "50"), ("height", "40")],
        );
        let plugin = ConvertShapeToPathPlugin::new();

        plugin.convert_rect(&mut element);

        assert_eq!(element.name, "path");
        assert_eq!(element.attr("d").unwrap(), "M20 10H70V50H20z");
    }

    #[test]
    fn test_rect_with_rounded_corners_not_converted() {
        let mut element = create_element(
            "rect",
            vec![
                ("x", "10"),
                ("y", "10"),
                ("width", "50"),
                ("height", "50"),
                ("rx", "4"),
            ],
        );
        let plugin = ConvertShapeToPathPlugin::new();

        plugin.convert_rect(&mut element);

        // Should not be converted
        assert_eq!(element.name, "rect");
        assert!(element.has_attr("rx"));
    }

    #[test]
    fn test_convert_line() {
        let mut element = create_element(
            "line",
            vec![("x1", "10"), ("y1", "10"), ("x2", "50"), ("y2", "20")],
        );
        let plugin = ConvertShapeToPathPlugin::new();

        plugin.convert_line(&mut element);

        assert_eq!(element.name, "path");
        assert_eq!(element.attr("d").unwrap(), "M10 10 50 20");
        assert!(!element.has_attr("x1"));
        assert!(!element.has_attr("y1"));
        assert!(!element.has_attr("x2"));
        assert!(!element.has_attr("y2"));
    }

    #[test]
    fn test_convert_polyline() {
        let mut element = create_element("polyline", vec![("points", "10,80 20,50 50,20 80,10")]);
        let plugin = ConvertShapeToPathPlugin::new();

        plugin.convert_polyline(&mut element);

        assert_eq!(element.name, "path");
        assert_eq!(element.attr("d").unwrap(), "M10 80 20 50 50 20 80 10");
        assert!(!element.has_attr("points"));
    }

    #[test]
    fn test_convert_polygon() {
        let mut element = create_element("polygon", vec![("points", "20 10 50 40 30 20")]);
        let plugin = ConvertShapeToPathPlugin::new();

        plugin.convert_polygon(&mut element);

        assert_eq!(element.name, "path");
        assert_eq!(element.attr("d").unwrap(), "M20 10 50 40 30 20z");
        assert!(!element.has_attr("points"));
    }

    #[test]
    fn test_convert_circle() {
        let mut element = create_element("circle", vec![("cx", "50"), ("cy", "50"), ("r", "25")]);
        let config = ConvertShapeToPathConfig {
            convert_arcs: true,
            float_precision: None,
        };
        let plugin = ConvertShapeToPathPlugin::with_config(config);

        plugin.convert_circle(&mut element);

        assert_eq!(element.name, "path");
        assert_eq!(
            element.attr("d").unwrap(),
            "M50 25A25 25 0 1 0 50 75A25 25 0 1 0 50 25z"
        );
        assert!(!element.has_attr("cx"));
        assert!(!element.has_attr("cy"));
        assert!(!element.has_attr("r"));
    }

    #[test]
    fn test_precision_formatting() {
        let config = ConvertShapeToPathConfig {
            convert_arcs: false,
            float_precision: Some(3),
        };
        let plugin = ConvertShapeToPathPlugin::with_config(config);

        assert_eq!(plugin.format_number(10.123456), "10.123");
        assert_eq!(plugin.format_number(20.987654), "20.988");
        assert_eq!(plugin.format_number(30.0), "30");

        let plugin_no_precision = ConvertShapeToPathPlugin::new();
        assert_eq!(plugin_no_precision.format_number(40.5), "40.5");
        assert_eq!(plugin_no_precision.format_number(50.0), "50");
    }

    #[test]
    fn test_polyline_insufficient_points() {
        let mut element = create_element("polyline", vec![("points", "10 20")]);
        let plugin = ConvertShapeToPathPlugin::new();

        plugin.convert_poly(&mut element, false);

        // Should be marked for removal
        assert_eq!(element.name, "");
        assert!(element.attributes.is_empty());
    }

    #[test]
    fn test_skip_unit_values() {
        let mut element = create_element("rect", vec![("width", "100%"), ("height", "50")]);
        let plugin = ConvertShapeToPathPlugin::new();

        plugin.convert_rect(&mut element);

        // Should not be converted due to percentage width
        assert_eq!(element.name, "rect");
        assert!(element.has_attr("width"));
    }
}

// Uncomment when ready to enable fixture tests
// vexy_vsvg_test_utils::plugin_fixture_tests!(ConvertShapeToPathPlugin, "convertShapeToPath");