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

//! Bake transforms into path coordinates.
//!
//! This plugin ports SVGO's `applyTransforms` plugin. Transform attributes like
//! `transform="translate(10,20) scale(2)"` modify how paths render but add bytes to the file.
//! We can eliminate the transform attribute entirely by applying the matrix math directly
//! to every coordinate in the path data.
//!
//! # Before
//! ```xml
//! <path transform="translate(10,20)" d="M0 0L10 10"/>
//! ```
//!
//! # After
//! ```xml
//! <path d="M10 20L20 30"/>
//! ```
//!
//! # How it works
//! 1. Parse transform functions (`translate`, `rotate`, `scale`, `matrix`) into a 3×3 matrix
//! 2. Multiply each coordinate in the path data by the transformation matrix
//! 3. Handle special cases: `H`/`V` commands may become `L` after non-axis-aligned transforms
//! 4. Remove the now-redundant `transform` attribute
//!
//! # Savings
//! - Removes `transform="..."` attribute (20-60 bytes typically)
//! - Enables better path data compression in subsequent plugins
//! - Stroked paths: be cautious, transforms can affect stroke width (configurable)
//!
//! SVGO Reference: https://github.com/svg/svgo

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

/// Configuration for the applyTransforms plugin.
///
/// Controls which paths get transforms applied and output precision.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ApplyTransformsConfig {
    /// Apply transforms to stroked paths (⚠️ may change apparent stroke width due to scaling)
    #[serde(default = "default_true")]
    pub apply_to_stroked: bool,

    /// Decimal precision for transformed coordinates (lower = smaller file, less precision)
    #[serde(default = "default_float_precision")]
    pub float_precision: u8,
}

impl Default for ApplyTransformsConfig {
    fn default() -> Self {
        Self {
            apply_to_stroked: true,
            float_precision: 3,
        }
    }
}

fn default_true() -> bool {
    true
}

fn default_float_precision() -> u8 {
    3
}

/// Plugin that bakes transform matrices into path coordinates.
///
/// Eliminates `transform` attributes by applying the matrix math directly to every
/// coordinate in the path data. Reduces bytes and enables better downstream optimizations.
///
/// SVGO equivalent: `applyTransforms`
pub struct ApplyTransformsPlugin {
    config: ApplyTransformsConfig,
}

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

impl ApplyTransformsPlugin {
    pub fn new() -> Self {
        Self {
            config: ApplyTransformsConfig::default(),
        }
    }

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

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

    /// Parse SVG transform attribute into a 3×3 transformation matrix.
    ///
    /// Handles chained transforms like `"translate(10,20) rotate(45) scale(2)"` by
    /// multiplying matrices from right to left (SVG applies transforms right-to-left).
    ///
    /// Supported transform functions:
    /// - `translate(tx [ty])`: moves by tx, ty (ty defaults to 0)
    /// - `scale(sx [sy])`: scales by sx, sy (sy defaults to sx for uniform scaling)
    /// - `rotate(angle [cx cy])`: rotates by angle degrees, optionally around point (cx, cy)
    /// - `matrix(a b c d e f)`: direct 2D affine transform matrix
    ///
    /// For `rotate(angle cx cy)`, we decompose into: translate(cx,cy) × rotate(angle) × translate(-cx,-cy)
    fn parse_transform(transform: &str) -> Option<Matrix3<f64>> {
        let mut matrix = Matrix3::identity();

        // Split on ')' to extract individual transform functions
        let transforms = transform.trim().split(')').filter(|s| !s.is_empty());

        for transform_fn in transforms {
            let transform_fn = transform_fn.trim();
            if transform_fn.is_empty() {
                continue;
            }

            if let Some(params_start) = transform_fn.find('(') {
                let fn_name = transform_fn[..params_start].trim();
                let params_str = &transform_fn[params_start + 1..];
                // Parse comma-separated or space-separated numbers
                let params: Vec<f64> = params_str
                    .split(|c: char| c == ',' || c.is_whitespace())
                    .filter(|s| !s.is_empty())
                    .filter_map(|s| s.trim().parse().ok())
                    .collect();

                match fn_name {
                    "translate" => {
                        if !params.is_empty() {
                            let tx = params[0];
                            let ty = params.get(1).copied().unwrap_or(0.0);
                            // Translation matrix: [[1, 0, tx], [0, 1, ty], [0, 0, 1]]
                            let translate = Matrix3::new(1.0, 0.0, tx, 0.0, 1.0, ty, 0.0, 0.0, 1.0);
                            matrix = translate * matrix;
                        }
                    }
                    "scale" => {
                        if !params.is_empty() {
                            let sx = params[0];
                            let sy = params.get(1).copied().unwrap_or(sx); // Uniform scaling if sy omitted
                                                                           // Scale matrix: [[sx, 0, 0], [0, sy, 0], [0, 0, 1]]
                            let scale = Matrix3::new(sx, 0.0, 0.0, 0.0, sy, 0.0, 0.0, 0.0, 1.0);
                            matrix = scale * matrix;
                        }
                    }
                    "rotate" => {
                        if !params.is_empty() {
                            let angle = params[0].to_radians(); // SVG uses degrees, math uses radians
                            let cos_a = angle.cos();
                            let sin_a = angle.sin();

                            if params.len() >= 3 {
                                // Rotate around point (cx, cy): translate to origin, rotate, translate back
                                let cx = params[1];
                                let cy = params[2];
                                let t1 = Matrix3::new(1.0, 0.0, cx, 0.0, 1.0, cy, 0.0, 0.0, 1.0);
                                let r = Matrix3::new(
                                    cos_a, -sin_a, 0.0, sin_a, cos_a, 0.0, 0.0, 0.0, 1.0,
                                );
                                let t2 = Matrix3::new(1.0, 0.0, -cx, 0.0, 1.0, -cy, 0.0, 0.0, 1.0);
                                matrix = t1 * r * t2 * matrix;
                            } else {
                                // Rotate around origin
                                let rotate = Matrix3::new(
                                    cos_a, -sin_a, 0.0, sin_a, cos_a, 0.0, 0.0, 0.0, 1.0,
                                );
                                matrix = rotate * matrix;
                            }
                        }
                    }
                    "matrix" => {
                        if params.len() >= 6 {
                            // Direct matrix: matrix(a b c d e f) → [[a, c, e], [b, d, f], [0, 0, 1]]
                            let custom = Matrix3::new(
                                params[0], params[2], params[4], params[1], params[3], params[5],
                                0.0, 0.0, 1.0,
                            );
                            matrix = custom * matrix;
                        }
                    }
                    _ => {} // Skip unknown transform functions (skewX, skewY not implemented)
                }
            }
        }

        Some(matrix)
    }

    /// Apply transforms to the document recursively
    fn apply_transforms_recursive(&self, element: &mut Element) {
        // Check if element has both transform and is a path
        if element.name == "path" {
            if let Some(transform) = element.attributes.get("transform") {
                // Check if we should skip stroked paths
                let has_stroke = element
                    .attributes
                    .get("stroke")
                    .map(|s| s != "none")
                    .unwrap_or(false);

                if !has_stroke || self.config.apply_to_stroked {
                    // Parse transform matrix
                    if let Some(matrix) = Self::parse_transform(transform) {
                        // Apply to path data
                        if let Some(d) = element.attributes.get("d") {
                            let transformed = self.transform_path_data(d, &matrix);
                            element.attributes.insert("d".into(), transformed.into());
                            // Remove transform attribute after applying
                            element.attributes.shift_remove("transform");
                        }
                    }
                }
            }
        }

        // Process child elements recursively
        for child in &mut element.children {
            if let Node::Element(child_element) = child {
                self.apply_transforms_recursive(child_element);
            }
        }
    }

    /// Apply transformation matrix to path data
    fn transform_path_data(&self, path_data: &str, matrix: &Matrix3<f64>) -> String {
        let mut result = String::new();
        let mut chars = path_data.chars().peekable();
        let mut current_x = 0.0;
        let mut current_y = 0.0;

        // Append a number with minimal separator: no space after a command letter,
        // no space before '-' or a second '.', space otherwise.
        let push_num = |res: &mut String, s: &str| {
            let last = res.chars().last();
            let needs_sep = match last {
                None => false,
                Some(c) if c.is_alphabetic() => false, // no space after command letter
                Some(_) => {
                    // no space before '-' (negative acts as separator)
                    // no space before '.' when prev already has a '.' (dot separator)
                    let starts_neg = s.starts_with('-');
                    let starts_dot = s.starts_with('.');
                    let prev = res.as_str();
                    let prev_has_dot = prev
                        .chars()
                        .rev()
                        .take_while(|c| c.is_ascii_digit() || *c == '.' || *c == '-')
                        .any(|c| c == '.');
                    !(starts_neg || (starts_dot && prev_has_dot))
                }
            };
            if needs_sep {
                res.push(' ');
            }
            res.push_str(s);
        };

        while let Some(ch) = chars.next() {
            if ch.is_alphabetic() {
                // No space before command letters — letters are unambiguous separators.
                result.push(ch);

                // Parse coordinates based on command type
                match ch {
                    'M' | 'L' => {
                        // Absolute moveto/lineto
                        if let (Some(x), Some(y)) =
                            (self.parse_coord(&mut chars), self.parse_coord(&mut chars))
                        {
                            let point = Point2::new(x, y);
                            let transformed = matrix.transform_point(&point);
                            push_num(&mut result, &self.format_number(transformed.x));
                            push_num(&mut result, &self.format_number(transformed.y));
                            current_x = transformed.x;
                            current_y = transformed.y;
                        }
                    }
                    'm' | 'l' => {
                        // Relative moveto/lineto
                        if let (Some(dx), Some(dy)) =
                            (self.parse_coord(&mut chars), self.parse_coord(&mut chars))
                        {
                            // For relative commands, we need to transform the delta
                            let start = Point2::new(current_x, current_y);
                            let end = Point2::new(current_x + dx, current_y + dy);
                            let transformed_start = matrix.transform_point(&start);
                            let transformed_end = matrix.transform_point(&end);
                            let new_dx = transformed_end.x - transformed_start.x;
                            let new_dy = transformed_end.y - transformed_start.y;
                            push_num(&mut result, &self.format_number(new_dx));
                            push_num(&mut result, &self.format_number(new_dy));
                            current_x = transformed_end.x;
                            current_y = transformed_end.y;
                        }
                    }
                    'H' => {
                        // Absolute horizontal lineto
                        if let Some(x) = self.parse_coord(&mut chars) {
                            let point = Point2::new(x, current_y);
                            let transformed = matrix.transform_point(&point);
                            // After transformation, H command might need to become L
                            if (transformed.y - current_y).abs() > 1e-6 {
                                // Convert to L command (replace 'H' already pushed)
                                result.pop(); // Remove 'H'
                                result.push('L');
                                push_num(&mut result, &self.format_number(transformed.x));
                                push_num(&mut result, &self.format_number(transformed.y));
                            } else {
                                push_num(&mut result, &self.format_number(transformed.x));
                            }
                            current_x = transformed.x;
                            current_y = transformed.y;
                        }
                    }
                    'V' => {
                        // Absolute vertical lineto
                        if let Some(y) = self.parse_coord(&mut chars) {
                            let point = Point2::new(current_x, y);
                            let transformed = matrix.transform_point(&point);
                            // After transformation, V command might need to become L
                            if (transformed.x - current_x).abs() > 1e-6 {
                                // Convert to L command (replace 'V' already pushed)
                                result.pop(); // Remove 'V'
                                result.push('L');
                                push_num(&mut result, &self.format_number(transformed.x));
                                push_num(&mut result, &self.format_number(transformed.y));
                            } else {
                                push_num(&mut result, &self.format_number(transformed.y));
                            }
                            current_x = transformed.x;
                            current_y = transformed.y;
                        }
                    }
                    'C' => {
                        // Absolute cubic bezier
                        for _ in 0..3 {
                            if let (Some(x), Some(y)) =
                                (self.parse_coord(&mut chars), self.parse_coord(&mut chars))
                            {
                                let point = Point2::new(x, y);
                                let transformed = matrix.transform_point(&point);
                                push_num(&mut result, &self.format_number(transformed.x));
                                push_num(&mut result, &self.format_number(transformed.y));
                                current_x = transformed.x;
                                current_y = transformed.y;
                            }
                        }
                    }
                    'Z' | 'z' => {
                        // Close path - no coordinates to transform
                    }
                    _ => {
                        // For other commands, just copy coordinates as-is for now
                        // A complete implementation would handle all SVG path commands
                        while let Some(next_ch) = chars.peek() {
                            if next_ch.is_alphabetic() {
                                break;
                            }
                            result.push(chars.next().unwrap());
                        }
                    }
                }
            }
        }

        result.trim().to_string()
    }

    /// Parse a coordinate from the character stream
    fn parse_coord(&self, chars: &mut std::iter::Peekable<std::str::Chars>) -> Option<f64> {
        let mut coord = String::new();
        let mut has_dot = false;

        // Skip whitespace and commas
        while let Some(&ch) = chars.peek() {
            if ch.is_whitespace() || ch == ',' {
                chars.next();
            } else {
                break;
            }
        }

        // Handle sign
        if let Some(&ch) = chars.peek() {
            if ch == '-' || ch == '+' {
                coord.push(chars.next().unwrap());
            }
        }

        // Parse number
        while let Some(&ch) = chars.peek() {
            if ch.is_numeric() {
                coord.push(chars.next().unwrap());
            } else if ch == '.' && !has_dot {
                coord.push(chars.next().unwrap());
                has_dot = true;
            } else {
                break;
            }
        }

        coord.parse().ok()
    }

    /// Format a number with the configured precision, using SVGO-compatible compact output.
    ///
    /// Trims trailing zeros/decimal point and strips leading zero from fractions
    /// (`0.5` → `.5`, `-0.5` → `-.5`) to minimize byte count.
    fn format_number(&self, num: f64) -> String {
        let trimmed = format!(
            "{:.prec$}",
            num,
            prec = self.config.float_precision as usize
        )
        .trim_end_matches('0')
        .trim_end_matches('.')
        .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 Plugin for ApplyTransformsPlugin {
    fn name(&self) -> &'static str {
        "applyTransforms"
    }

    fn description(&self) -> &'static str {
        "Apply transform matrices to path data"
    }

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

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

impl Clone for ApplyTransformsPlugin {
    fn clone(&self) -> Self {
        Self {
            config: self.config.clone(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_transform_translate() {
        let transform = "translate(10, 20)";
        let matrix = ApplyTransformsPlugin::parse_transform(transform).unwrap();
        let point = Point2::new(0.0, 0.0);
        let transformed = matrix.transform_point(&point);
        assert_eq!(transformed.x, 10.0);
        assert_eq!(transformed.y, 20.0);
    }

    #[test]
    fn test_parse_transform_scale() {
        let transform = "scale(2)";
        let matrix = ApplyTransformsPlugin::parse_transform(transform).unwrap();
        let point = Point2::new(5.0, 5.0);
        let transformed = matrix.transform_point(&point);
        assert_eq!(transformed.x, 10.0);
        assert_eq!(transformed.y, 10.0);
    }

    #[test]
    fn test_format_number() {
        let plugin = ApplyTransformsPlugin::new();
        assert_eq!(plugin.format_number(1.0), "1");
        assert_eq!(plugin.format_number(1.500), "1.5");
        assert_eq!(plugin.format_number(1.234567), "1.235");
    }
}