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

//! Replace pointless gradients with solid colors.
//!
//! This plugin ports SVGO's `convertOneStopGradients` plugin. A gradient with only one
//! `<stop>` element doesn't actually create a gradient—it's just a complicated way to
//! specify a solid color. We find these single-stop gradients, extract the color, replace
//! all `url(#gradient)` references with the color, then delete the gradient definition.
//!
//! # Before
//! ```xml
//! <defs>
//!   <linearGradient id="grad1">
//!     <stop stop-color="#ff0000"/>
//!   </linearGradient>
//! </defs>
//! <rect fill="url(#grad1)" width="100" height="100"/>
//! ```
//!
//! # After
//! ```xml
//! <rect fill="#ff0000" width="100" height="100"/>
//! ```
//!
//! # Savings
//! - Removes entire `<defs>` section (typically 80-120 bytes)
//! - Replaces `url(#id)` (10-20 bytes) with color (4-9 bytes)
//! - Removes empty `<defs>` containers left behind
//! - Cleans up unused `xmlns:xlink` namespace declarations
//!
//! SVGO Reference: https://github.com/svg/svgo

use std::collections::{HashMap, HashSet};

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

use crate::Plugin;

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

/// Main plugin struct
pub struct ConvertOneStopGradientsPlugin {
    #[allow(dead_code)]
    config: ConvertOneStopGradientsConfig,
}

impl ConvertOneStopGradientsPlugin {
    pub fn new() -> Self {
        Self {
            config: ConvertOneStopGradientsConfig::default(),
        }
    }

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

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

    /// First pass: identify single-stop gradients and extract their colors.
    ///
    /// Walks the tree looking for `<linearGradient>` or `<radialGradient>` elements.
    /// When a gradient has exactly one `<stop>` child, we extract the stop color
    /// (from `stop-color` attribute or inline `style`) and record this gradient for removal.
    ///
    /// Gradients that inherit from other gradients via `xlink:href` are skipped—resolving
    /// inherited stops would require complex reference chasing.
    #[allow(clippy::only_used_in_recursion)]
    fn process_element(
        &self,
        element: &mut Element,
        gradients_to_remove: &mut HashMap<String, String>,
        parent_is_defs: bool,
        affected_defs: &mut HashSet<String>,
    ) {
        // Track defs elements (for cleanup later)
        if element.name == "defs" && element.has_attr("id") {
            if let Some(id) = element.attr("id") {
                affected_defs.insert(id.to_string());
            }
        }

        // Check if this element is a gradient
        if element.name == "linearGradient" || element.name == "radialGradient" {
            if let Some(id) = element.attr("id") {
                // Count stop children
                let stops: Vec<&Element> = element
                    .children
                    .iter()
                    .filter_map(|child| {
                        if let Node::Element(ref elem) = child {
                            if elem.name == "stop" {
                                Some(elem)
                            } else {
                                None
                            }
                        } else {
                            None
                        }
                    })
                    .collect();

                // Check if this gradient inherits from another gradient
                let href = element.attr("xlink:href").or_else(|| element.attr("href"));

                // Skip gradients that reference others (they might inherit stops)
                if stops.is_empty() && href.is_some() {
                    return;
                }

                // Only process gradients with exactly one stop
                if stops.len() == 1 {
                    let stop = stops[0];

                    // Extract the stop color (try attribute first, then inline style, then default)
                    let stop_color = stop
                        .attr("stop-color")
                        .map(|s| s.to_string())
                        .or_else(|| {
                            // Parse stop-color from inline style="stop-color: #ff0000; ..."
                            stop.attr("style").and_then(|style| {
                                if let Some(idx) = style.find("stop-color:") {
                                    let start = idx + 11; // Length of "stop-color:"
                                    let rest = &style[start..].trim_start();
                                    let end = rest.find(';').unwrap_or(rest.len());
                                    Some(rest[..end].trim().to_string())
                                } else {
                                    None
                                }
                            })
                        })
                        .unwrap_or_else(|| "black".to_string()); // SVG spec: default stop-color is black

                    // Record this gradient's ID and replacement color
                    gradients_to_remove.insert(id.to_string(), stop_color);

                    if parent_is_defs {
                        affected_defs.insert("parent_defs".to_string());
                    }
                }
            }
        }

        // Recurse into children
        let is_defs = element.name == "defs";
        for child in &mut element.children {
            if let Node::Element(ref mut child_elem) = child {
                self.process_element(child_elem, gradients_to_remove, is_defs, affected_defs);
            }
        }
    }

    /// Second pass: replace all `url(#gradient)` references with solid colors.
    ///
    /// Checks color-accepting attributes (`fill`, `stroke`, `stop-color`, etc.) for
    /// `url(#id)` syntax. If the `id` matches a single-stop gradient, replace the entire
    /// `url(#id)` with the gradient's color.
    ///
    /// Also handles inline `style` attributes where colors might appear as
    /// `fill: url(#grad1);`.
    fn replace_gradient_references(
        &self,
        element: &mut Element,
        gradients_to_remove: &HashMap<String, String>,
    ) {
        // Check presentation attributes for gradient references
        for color_prop in COLORS_PROPS.iter() {
            if let Some(value) = element.attr(color_prop) {
                // Parse url(#id) syntax
                if let Some(gradient_id) = self.extract_gradient_id(value) {
                    if let Some(replacement_color) = gradients_to_remove.get(&gradient_id) {
                        element.set_attr(*color_prop, replacement_color);
                    }
                }
            }
        }

        // Replace gradient references in inline style attribute
        if let Some(style) = element.attr("style") {
            let mut new_style = style.to_string();
            for (gradient_id, replacement_color) in gradients_to_remove {
                let url_pattern = format!("url(#{})", gradient_id);
                new_style = new_style.replace(&url_pattern, replacement_color);
            }
            if new_style != style {
                element.set_attr("style", &new_style);
            }
        }

        // Recurse into children
        for child in &mut element.children {
            if let Node::Element(ref mut child_elem) = child {
                self.replace_gradient_references(child_elem, gradients_to_remove);
            }
        }
    }

    /// Extract gradient ID from `url(#id)` syntax.
    ///
    /// Returns the ID portion without the `url(#` prefix or `)` suffix.
    /// Example: `"url(#grad1)"` → `Some("grad1")`.
    fn extract_gradient_id(&self, value: &str) -> Option<String> {
        if value.starts_with("url(#") && value.ends_with(')') {
            let id = &value[5..value.len() - 1]; // Strip "url(#" and ")"
            Some(id.to_string())
        } else {
            None
        }
    }

    /// Third pass: delete the single-stop gradient definitions.
    ///
    /// Removes `<linearGradient>` and `<radialGradient>` elements whose IDs
    /// are in the removal list. This frees up the bytes used by the gradient definition.
    #[allow(clippy::only_used_in_recursion)]
    fn remove_gradients(
        &self,
        element: &mut Element,
        gradients_to_remove: &HashMap<String, String>,
    ) {
        // Filter out gradient elements marked for removal
        element.children.retain(|child| {
            if let Node::Element(ref elem) = child {
                if elem.name == "linearGradient" || elem.name == "radialGradient" {
                    if let Some(id) = elem.attr("id") {
                        // Keep only gradients NOT in the removal list
                        return !gradients_to_remove.contains_key(id);
                    }
                }
            }
            true
        });

        // Recurse into children
        for child in &mut element.children {
            if let Node::Element(ref mut child_elem) = child {
                self.remove_gradients(child_elem, gradients_to_remove);
            }
        }
    }

    /// Fourth pass: clean up empty `<defs>` containers.
    ///
    /// After removing gradients, some `<defs>` elements may be left empty.
    /// Empty `<defs>` serve no purpose and waste bytes, so we remove them.
    #[allow(clippy::only_used_in_recursion)]
    fn remove_empty_defs(&self, element: &mut Element) {
        // Remove defs elements that have no children
        element.children.retain(|child| {
            if let Node::Element(ref elem) = child {
                if elem.name == "defs" && elem.children.is_empty() {
                    return false; // Remove this empty defs
                }
            }
            true
        });

        // Recurse into children
        for child in &mut element.children {
            if let Node::Element(ref mut child_elem) = child {
                self.remove_empty_defs(child_elem);
            }
        }
    }

    /// Clean up unused `xmlns:xlink` namespace declaration.
    ///
    /// Gradients sometimes use `xlink:href` to reference other gradients. If we removed
    /// all gradients and no other elements use `xlink:href`, the namespace declaration
    /// `xmlns:xlink="http://www.w3.org/1999/xlink"` is dead weight (saves ~40 bytes).
    fn remove_unused_xlink_namespace(&self, document: &mut Document) {
        // Recursively check if any element still has xlink:href
        fn check_xlink(element: &Element) -> bool {
            if element.has_attr("xlink:href") {
                return true;
            }

            for child in &element.children {
                if let Node::Element(ref elem) = child {
                    if check_xlink(elem) {
                        return true;
                    }
                }
            }
            false
        }

        let has_xlink = check_xlink(&document.root);

        // If no xlink:href attributes remain, remove the namespace declaration
        if !has_xlink {
            document.root.namespaces.shift_remove("xlink");
            document.root.remove_attr("xmlns:xlink");
        }
    }
}

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

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

    fn description(&self) -> &'static str {
        "converts one-stop (single color) gradients to a plain color"
    }

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

    fn apply(&self, document: &mut Document) -> Result<()> {
        let mut gradients_to_remove = HashMap::new();
        let mut affected_defs = HashSet::new();

        // Pass 1: Find all single-stop gradients and extract their colors
        self.process_element(
            &mut document.root,
            &mut gradients_to_remove,
            false,
            &mut affected_defs,
        );

        // Only proceed if we found single-stop gradients to optimize
        if !gradients_to_remove.is_empty() {
            // Pass 2: Replace all url(#gradient) references with the solid color
            self.replace_gradient_references(&mut document.root, &gradients_to_remove);

            // Pass 3: Delete the now-unused gradient definitions
            self.remove_gradients(&mut document.root, &gradients_to_remove);

            // Pass 4: Delete any <defs> elements left empty by gradient removal
            self.remove_empty_defs(&mut document.root);

            // Pass 5: Clean up unused xmlns:xlink namespace if no xlink:href remains
            self.remove_unused_xlink_namespace(document);
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use std::borrow::Cow;

    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_one_stop_gradient_conversion() {
        let plugin = ConvertOneStopGradientsPlugin::new();
        let mut doc = create_test_document();

        // Add defs with a one-stop gradient
        let mut defs_elem = Element {
            name: "defs".into(),
            attributes: IndexMap::new(),
            namespaces: IndexMap::new(),
            children: vec![],
        };

        let mut gradient_attrs = IndexMap::new();
        gradient_attrs.insert(Cow::Borrowed("id"), Cow::Borrowed("grad1"));

        let mut stop_attrs = IndexMap::new();
        stop_attrs.insert(Cow::Borrowed("stop-color"), Cow::Borrowed("#ff0000"));

        let gradient_elem = Element {
            name: "linearGradient".into(),
            attributes: gradient_attrs,
            namespaces: IndexMap::new(),
            children: vec![Node::Element(Element {
                name: "stop".into(),
                attributes: stop_attrs,
                namespaces: IndexMap::new(),
                children: vec![],
            })],
        };

        defs_elem.children.push(Node::Element(gradient_elem));
        doc.root.children.push(Node::Element(defs_elem));

        // Add rect using the gradient
        let mut rect_attrs = IndexMap::new();
        rect_attrs.insert(Cow::Borrowed("fill"), Cow::Borrowed("url(#grad1)"));
        rect_attrs.insert(Cow::Borrowed("width"), Cow::Borrowed("100"));
        rect_attrs.insert(Cow::Borrowed("height"), Cow::Borrowed("100"));

        doc.root.children.push(Node::Element(Element {
            name: "rect".into(),
            attributes: rect_attrs,
            namespaces: IndexMap::new(),
            children: vec![],
        }));

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

        // Check that gradient was removed and rect now has solid fill
        // The defs should be empty and removed
        let has_gradient = doc.root.children.iter().any(|child| {
            if let Node::Element(elem) = child {
                elem.children.iter().any(|child| {
                    if let Node::Element(e) = child {
                        e.name == "linearGradient" || e.name == "radialGradient"
                    } else {
                        false
                    }
                })
            } else {
                false
            }
        });
        assert!(!has_gradient);

        // Find the rect and check its fill
        let rect = doc.root.children.iter().find_map(|child| {
            if let Node::Element(elem) = child {
                if elem.name == "rect" {
                    Some(elem)
                } else {
                    None
                }
            } else {
                None
            }
        });

        assert!(rect.is_some());
        let rect = rect.unwrap();
        assert_eq!(rect.attr("fill"), Some("#ff0000"));
    }
}