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

//! Consolidates multiple `<style>` elements into a single block.
//!
//! SVGs often accumulate multiple `<style>` tags from authoring tools or post-processing.
//! This plugin merges them to reduce element overhead and improve browser parsing speed.
//!
//! **What it does:**
//! - Combines all `<style>` elements within the same parent into one
//! - Wraps media-specific styles in `@media` queries (e.g., `@media print { ... }`)
//! - Removes empty or whitespace-only `<style>` blocks
//! - Preserves text/CDATA content types (uses CDATA if any source uses it)
//!
//! **Example:**
//! ```xml
//! <!-- Before -->
//! <svg>
//!   <style>.a { fill: red; }</style>
//!   <style media="print">.b { fill: blue; }</style>
//!   <style>.c { stroke: green; }</style>
//! </svg>
//!
//! <!-- After -->
//! <svg>
//!   <style>.a { fill: red; }@media print{.b { fill: blue; }}.c { stroke: green; }</style>
//! </svg>
//! ```
//!
//! **Why it's useful:** Browsers must parse each `<style>` element separately. Merging
//! them reduces DOM nodes and parsing overhead, especially for SVGs with many style blocks.
//!
//! **Configuration:** None (no parameters accepted).
//!
//! Reference: SVGO's mergeStyles plugin

use once_cell::sync::Lazy;

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

use crate::Plugin;

/// Configuration parameters for merge styles plugin (currently empty)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[derive(Default)]
pub struct MergeStylesConfig {
    // No configuration options - matches SVGO behavior
}

/// Plugin that merges multiple style elements into one
pub struct MergeStylesPlugin {
    #[allow(dead_code)]
    config: MergeStylesConfig,
}

impl MergeStylesPlugin {
    /// Create a new MergeStylesPlugin
    pub fn new() -> Self {
        Self {
            config: MergeStylesConfig::default(),
        }
    }

    /// Create a new MergeStylesPlugin with config
    pub fn with_config(config: MergeStylesConfig) -> Self {
        Self { config }
    }

    /// Parse configuration from JSON
    #[allow(dead_code)]
    fn parse_config(params: &Value) -> Result<MergeStylesConfig> {
        if params.is_object() {
            serde_json::from_value(params.clone())
                .map_err(|e| anyhow::anyhow!("Invalid configuration: {}", e))
        } else {
            Ok(MergeStylesConfig::default())
        }
    }
}

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

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

    fn description(&self) -> &'static str {
        "merge multiple style elements into one"
    }

    fn validate_params(&self, params: &Value) -> Result<()> {
        if let Some(obj) = params.as_object() {
            if !obj.is_empty() {
                return Err(anyhow::anyhow!(
                    "mergeStyles plugin does not accept any parameters"
                ));
            }
        }
        Ok(())
    }

    fn apply(&self, document: &mut Document) -> Result<()> {
        // Use a simple recursive approach instead of visitor pattern for this plugin
        self.merge_styles_recursive(&mut document.root);
        Ok(())
    }
}

impl MergeStylesPlugin {
    /// Recursively merge styles in an element and all its children
    fn merge_styles_recursive(&self, element: &mut Element) {
        // Skip foreignObject content
        if element.name == "foreignObject" {
            return;
        }

        // Process children first (post-order)
        for child in &mut element.children {
            if let Node::Element(child_element) = child {
                self.merge_styles_recursive(child_element);
            }
        }

        // Now merge styles in this element
        self.merge_styles_in_element(element);
    }

    /// Merge style elements within a single parent element
    fn merge_styles_in_element(&self, element: &mut Element) {
        let mut style_data = Vec::new();
        let mut first_style_index = None;
        let mut uses_cdata = false;

        // First pass: collect style elements and their data
        for (index, child) in element.children.iter().enumerate() {
            if let Node::Element(elem) = child {
                if elem.name == "style" && Self::is_valid_style_type(elem) {
                    let css = Self::extract_css_content(elem);

                    // Skip empty styles
                    if css.trim().is_empty() {
                        continue;
                    }

                    // Track if we need CDATA
                    if Self::has_cdata_content(elem) {
                        uses_cdata = true;
                    }

                    // Get media attribute
                    let media = elem.attributes.get("media").cloned();

                    // Save data for merging
                    style_data.push((css, media));

                    // Remember the first style element index
                    if first_style_index.is_none() {
                        first_style_index = Some(index);
                    }
                }
            }
        }

        // If we have styles to merge
        if style_data.len() > 1 {
            // Build merged CSS content
            let mut merged_css = String::new();
            for (index, (css, media)) in style_data.iter().enumerate() {
                let css_content = css.trim_end();
                let normalized_content = if uses_cdata || index == 0 {
                    css_content
                } else {
                    css_content.trim_start()
                };

                if let Some(media_value) = media {
                    let trimmed_len = merged_css.trim_end().len();
                    merged_css.truncate(trimmed_len);
                    merged_css.push_str(&format!(
                        "@media {}{{{}}}",
                        media_value,
                        normalized_content.trim()
                    ));
                } else {
                    merged_css.push_str(normalized_content);
                }
            }

            // Clean up multiple newlines to match SVGO output
            static NEWLINE_CLEANUP_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"\n\s*\n").unwrap());
            let merged_css_cow = NEWLINE_CLEANUP_RE.replace_all(&merged_css, "\n");
            let merged_css_cleaned = merged_css_cow.to_string();

            // Replace the first style element with merged content
            if let Some(first_index) = first_style_index {
                let mut merged_style = Element::new("style");
                merged_style.name = std::borrow::Cow::Borrowed("style");

                // Add merged content as appropriate node type
                if uses_cdata {
                    let mut cdata_content = merged_css_cleaned.trim_start().to_string();
                    cdata_content.push_str("\n        "); // Indent closing ]]>
                    merged_style
                        .children
                        .push(Node::Text("\n        ".to_string().into()));
                    merged_style
                        .children
                        .push(Node::CData(cdata_content.into()));
                    merged_style
                        .children
                        .push(Node::Text("\n    ".to_string().into()));
                } else {
                    merged_style
                        .children
                        .push(Node::Text(merged_css_cleaned.into()));
                }

                // Replace first style element
                element.children[first_index] = Node::Element(merged_style);
            }
        }

        // Second pass: remove empty styles and duplicates (keep only first merged style)
        if style_data.len() > 1 {
            let mut found_first = false;
            element.children.retain(|child| {
                if let Node::Element(elem) = child {
                    if elem.name == "style" && Self::is_valid_style_type(elem) {
                        if !found_first {
                            found_first = true;
                            true // Keep the first style element
                        } else {
                            false // Remove subsequent style elements
                        }
                    } else {
                        true // Keep non-style elements
                    }
                } else {
                    true // Keep non-element nodes
                }
            });
        } else {
            // Just remove empty styles when no merging occurred
            element.children.retain(|child| {
                if let Node::Element(elem) = child {
                    if elem.name == "style" && Self::is_valid_style_type(elem) {
                        let css = Self::extract_css_content(elem);
                        !css.trim().is_empty()
                    } else {
                        true // Keep non-style elements
                    }
                } else {
                    true // Keep non-element nodes
                }
            });
        }
    }

    /// Check if style element has valid type attribute
    fn is_valid_style_type(element: &Element) -> bool {
        if let Some(type_attr) = element.attributes.get("type") {
            type_attr.is_empty() || type_attr == "text/css"
        } else {
            true // No type attribute is valid
        }
    }

    /// Extract CSS content from style element
    fn extract_css_content(element: &Element) -> String {
        let mut css = String::new();
        for child in &element.children {
            match child {
                Node::Text(text) => css.push_str(text),
                Node::CData(cdata) => css.push_str(cdata),
                _ => {}
            }
        }
        css
    }

    /// Check if any child has CDATA content
    fn has_cdata_content(element: &Element) -> bool {
        element
            .children
            .iter()
            .any(|child| matches!(child, Node::CData(_)))
    }
}

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

    use serde_json::json;
    use vexy_vsvg::ast::{Document, Element, Node};

    use super::*;

    fn create_element(name: &'static str) -> Element<'static> {
        let mut element = Element::new(name);
        element.name = Cow::Borrowed(name);
        element
    }

    fn count_style_elements(element: &Element) -> usize {
        let mut count = 0;
        for child in &element.children {
            if let Node::Element(elem) = child {
                if elem.name == "style" {
                    count += 1;
                }
                count += count_style_elements(elem);
            }
        }
        count
    }

    fn get_style_content(element: &Element) -> Option<String> {
        for child in &element.children {
            if let Node::Element(elem) = child {
                if elem.name == "style" {
                    for style_child in &elem.children {
                        match style_child {
                            Node::Text(text) => return Some(text.to_string()),
                            Node::CData(cdata) => return Some(cdata.to_string()),
                            _ => {}
                        }
                    }
                }
            }
        }
        None
    }

    #[test]
    fn test_plugin_creation() {
        let plugin = MergeStylesPlugin::new();
        assert_eq!(plugin.name(), "mergeStyles");
    }

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

        // Valid parameters (empty object)
        assert!(plugin.validate_params(&json!({})).is_ok());

        // Invalid parameters (non-empty object)
        assert!(plugin.validate_params(&json!({"param": "value"})).is_err());
    }

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

        // Create first style element
        let mut style1 = create_element("style");
        style1
            .children
            .push(Node::Text(".a{fill:red}".to_string().into()));

        // Create second style element
        let mut style2 = create_element("style");
        style2
            .children
            .push(Node::Text(".b{fill:blue}".to_string().into()));

        // Add both styles to document
        doc.root.children.push(Node::Element(style1));
        doc.root.children.push(Node::Element(style2));

        plugin.apply(&mut doc).unwrap();

        // Should have only one style element
        assert_eq!(count_style_elements(&doc.root), 1);

        // Content should be merged
        let merged_content = get_style_content(&doc.root).unwrap();
        assert!(merged_content.contains(".a{fill:red}"));
        assert!(merged_content.contains(".b{fill:blue}"));
    }

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

        // Create style with media attribute
        let mut style1 = create_element("style");
        style1.set_attr("media", "print");
        style1
            .children
            .push(Node::Text(".a{fill:red}".to_string().into()));

        // Create regular style
        let mut style2 = create_element("style");
        style2
            .children
            .push(Node::Text(".b{fill:blue}".to_string().into()));

        // Add both styles to document
        doc.root.children.push(Node::Element(style1));
        doc.root.children.push(Node::Element(style2));

        plugin.apply(&mut doc).unwrap();

        // Should have only one style element
        assert_eq!(count_style_elements(&doc.root), 1);

        // Content should include @media wrapper
        let merged_content = get_style_content(&doc.root).unwrap();
        assert!(merged_content.contains("@media print{.a{fill:red}}"));
        assert!(merged_content.contains(".b{fill:blue}"));
    }

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

        // Create empty style
        let mut empty_style = create_element("style");
        empty_style
            .children
            .push(Node::Text("   ".to_string().into()));

        // Create style with content
        let mut content_style = create_element("style");
        content_style
            .children
            .push(Node::Text(".a{fill:red}".to_string().into()));

        // Add both styles to document
        doc.root.children.push(Node::Element(empty_style));
        doc.root.children.push(Node::Element(content_style));

        plugin.apply(&mut doc).unwrap();

        // Should have only one style element (empty one removed)
        assert_eq!(count_style_elements(&doc.root), 1);

        // Content should only be the non-empty style
        let merged_content = get_style_content(&doc.root).unwrap();
        assert_eq!(merged_content, ".a{fill:red}");
    }

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

        // Create style with invalid type
        let mut invalid_style = create_element("style");
        invalid_style.set_attr("type", "text/javascript");
        invalid_style
            .children
            .push(Node::Text("console.log('test')".into()));

        // Create valid style
        let mut valid_style = create_element("style");
        valid_style
            .children
            .push(Node::Text(".a{fill:red}".to_string().into()));

        // Add both styles to document
        doc.root.children.push(Node::Element(invalid_style));
        doc.root.children.push(Node::Element(valid_style));

        plugin.apply(&mut doc).unwrap();

        // Should have two style elements (invalid one not merged)
        assert_eq!(count_style_elements(&doc.root), 2);
    }

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

        // Create style with empty type
        let mut style1 = create_element("style");
        style1.set_attr("type", "");
        style1
            .children
            .push(Node::Text(".a{fill:red}".to_string().into()));

        // Create style with text/css type
        let mut style2 = create_element("style");
        style2.set_attr("type", "text/css");
        style2
            .children
            .push(Node::Text(".b{fill:blue}".to_string().into()));

        // Create style with no type attribute
        let mut style3 = create_element("style");
        style3
            .children
            .push(Node::Text(".c{fill:green}".to_string().into()));

        // Add all styles to document
        doc.root.children.push(Node::Element(style1));
        doc.root.children.push(Node::Element(style2));
        doc.root.children.push(Node::Element(style3));

        plugin.apply(&mut doc).unwrap();

        // Should have only one style element (all merged)
        assert_eq!(count_style_elements(&doc.root), 1);

        // Content should include all styles
        let merged_content = get_style_content(&doc.root).unwrap();
        assert!(merged_content.contains(".a{fill:red}"));
        assert!(merged_content.contains(".b{fill:blue}"));
        assert!(merged_content.contains(".c{fill:green}"));
    }

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

        // Create style with CDATA content
        let mut style1 = create_element("style");
        style1.children.push(Node::CData(".a{fill:red}".into()));

        // Create style with text content
        let mut style2 = create_element("style");
        style2
            .children
            .push(Node::Text(".b{fill:blue}".to_string().into()));

        // Add both styles to document
        doc.root.children.push(Node::Element(style1));
        doc.root.children.push(Node::Element(style2));

        plugin.apply(&mut doc).unwrap();

        // Should have only one style element
        assert_eq!(count_style_elements(&doc.root), 1);

        // Check that result uses CDATA (since one of the sources was CDATA)
        for child in &doc.root.children {
            if let Node::Element(elem) = child {
                if elem.name == "style" {
                    // Should have CDATA content
                    assert!(elem.children.iter().any(|c| matches!(c, Node::CData(_))));
                }
            }
        }
    }

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

        // Create a rect element (no styles)
        let rect = create_element("rect");
        doc.root.children.push(Node::Element(rect));

        plugin.apply(&mut doc).unwrap();

        // Should have no style elements
        assert_eq!(count_style_elements(&doc.root), 0);
    }

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

        // Create single style element
        let mut style = create_element("style");
        style
            .children
            .push(Node::Text(".a{fill:red}".to_string().into()));
        doc.root.children.push(Node::Element(style));

        plugin.apply(&mut doc).unwrap();

        // Should still have one style element
        assert_eq!(count_style_elements(&doc.root), 1);

        // Content should be unchanged
        let content = get_style_content(&doc.root).unwrap();
        assert_eq!(content, ".a{fill:red}");
    }

    #[test]
    fn test_config_parsing() {
        let config = MergeStylesPlugin::parse_config(&json!({})).unwrap();
        // No fields to check since config is empty
        let _ = config;
    }
}

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