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

//! Appends CSS class names to the root `<svg>` element.
//!
//! Merges new class names with any existing classes on the outermost SVG tag,
//! automatically deduplicating. Useful for CSS framework integration (Tailwind,
//! Bootstrap) or adding semantic markers.
//!
//! **What it does:**
//! - Adds class names to the root `<svg>` element's `class` attribute
//! - Preserves existing classes (won't replace, only appends)
//! - Deduplicates classes (each class appears only once)
//! - Maintains insertion order (existing classes first, then new ones)
//!
//! **Configuration:**
//! - `className`: Single class name to add
//! - `classNames`: Array of class names to add
//!
//! At least one must be provided.
//!
//! **Example:**
//! ```json
//! {
//!   "className": "icon",
//!   "classNames": ["w-6", "h-6", "text-blue-500"]
//! }
//! ```
//!
//! ```xml
//! <!-- Before -->
//! <svg class="existing-class" viewBox="0 0 100 100">...</svg>
//!
//! <!-- After -->
//! <svg class="existing-class icon w-6 h-6 text-blue-500" viewBox="0 0 100 100">...</svg>
//! ```
//!
//! **Why it's useful:** Adds framework-specific or semantic classes without manual
//! editing. Perfect for integrating SVGs into CSS-first workflows.
//!
//! Reference: SVGO's addClassesToSVGElement plugin

use crate::Plugin;

use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashSet;
use vexy_vsvg::ast::{Document, Element};

/// Configuration parameters for add classes to SVG element plugin.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[derive(Default)]
pub struct AddClassesToSVGElementConfig {
    /// Single class name to add (optional).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub class_name: Option<String>,
    /// Array of class names to add (optional).
    ///
    /// At least one of `class_name` or `class_names` must be provided.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(alias = "classes")]
    pub class_names: Option<Vec<String>>,
}

/// Plugin that adds classes to the root SVG element.
///
/// Merges new class names with existing ones, deduplicating automatically.
/// Useful for CSS framework integration and semantic markup.
pub struct AddClassesToSVGElementPlugin {
    config: AddClassesToSVGElementConfig,
}

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

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

    /// Parse configuration from JSON
    fn parse_config(params: &Value) -> Result<AddClassesToSVGElementConfig, anyhow::Error> {
        if params.is_null() {
            Ok(AddClassesToSVGElementConfig::default())
        } else if params.is_object() {
            serde_json::from_value(params.clone())
                .map_err(|e| anyhow::anyhow!("Invalid configuration: {}", e))
        } else {
            Err(anyhow::anyhow!("Configuration must be an object"))
        }
    }

    /// Apply classes to the root SVG element.
    ///
    /// Merges configured class names with existing ones:
    /// 1. Preserves existing classes (keeps original order)
    /// 2. Appends new classes (from className and classNames)
    /// 3. Deduplicates (each class appears only once)
    /// 4. Filters empty strings
    fn apply_classes(&self, element: &mut Element) {
        // Gather all classes to apply
        let mut classes_to_add = Vec::new();

        // Add single class if present
        if let Some(ref class_name) = self.config.class_name {
            classes_to_add.push(class_name.clone());
        }

        // Add array of classes if present
        if let Some(ref class_names) = self.config.class_names {
            classes_to_add.extend(class_names.iter().cloned());
        }

        // Preserve class order while deduplicating
        let mut class_list: Vec<String> = Vec::new();
        let mut class_set: HashSet<String> = HashSet::new();

        // First, add existing classes
        if let Some(existing_class) = element.attributes.get("class") {
            for class_name in existing_class.split_whitespace() {
                if class_set.insert(class_name.to_string()) {
                    class_list.push(class_name.to_string());
                }
            }
        }

        // Then, add new classes (skipping duplicates and empty strings)
        for class_name in classes_to_add {
            if !class_name.is_empty() && class_set.insert(class_name.clone()) {
                class_list.push(class_name);
            }
        }

        // Update class attribute
        if !class_list.is_empty() {
            let class_string = class_list.join(" ");
            element
                .attributes
                .insert("class".into(), class_string.into());
        }
    }
}

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

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

    fn description(&self) -> &'static str {
        "adds classnames to an outer <svg> element"
    }

    fn validate_params(&self, params: &Value) -> anyhow::Result<()> {
        let config = Self::parse_config(params)?;

        // Validate that at least one of className or classNames is specified
        if config.class_name.is_none()
            && (config.class_names.is_none() || config.class_names.as_ref().unwrap().is_empty())
        {
            return Err(anyhow::anyhow!(
                "Error in plugin \"addClassesToSVGElement\": absent parameters.\n\
                It should have a list of classes in \"classNames\" or one \"className\"."
            ));
        }

        Ok(())
    }

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

    fn apply(&self, document: &mut Document) -> anyhow::Result<()> {
        // Only apply to root SVG element
        if document.root.name == "svg" {
            self.apply_classes(&mut document.root);
        }
        Ok(())
    }
}

#[cfg(test)]
mod unit_tests {
    use super::*;
    use serde_json::json;
    use std::borrow::Cow;
    use vexy_vsvg::ast::{Document, Element};

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

    #[test]
    fn test_plugin_creation() {
        let plugin = AddClassesToSVGElementPlugin::new();
        assert_eq!(plugin.name(), "addClassesToSVGElement");
        assert_eq!(
            plugin.description(),
            "adds classnames to an outer <svg> element"
        );
    }

    #[test]
    fn test_parameter_validation_missing_params() {
        let plugin = AddClassesToSVGElementPlugin::new();

        // Invalid - no parameters
        assert!(plugin.validate_params(&json!({})).is_err());

        // Invalid - empty classNames array
        assert!(plugin
            .validate_params(&json!({
                "classNames": []
            }))
            .is_err());
    }

    #[test]
    fn test_parameter_validation_single_class() {
        let plugin = AddClassesToSVGElementPlugin::new();

        // Valid - single class
        assert!(plugin
            .validate_params(&json!({
                "className": "myClass"
            }))
            .is_ok());
    }

    #[test]
    fn test_parameter_validation_multiple_classes() {
        let plugin = AddClassesToSVGElementPlugin::new();

        // Valid - array of classes
        assert!(plugin
            .validate_params(&json!({
                "classNames": ["class1", "class2"]
            }))
            .is_ok());
    }

    #[test]
    fn test_add_single_class() {
        let config = AddClassesToSVGElementConfig {
            class_name: Some("myClass".to_string()),
            class_names: None,
        };
        let plugin = AddClassesToSVGElementPlugin::with_config(config);

        let mut doc = Document::new();
        doc.root = create_element("svg");

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

        // Check that class was added
        assert_eq!(doc.root.attr("class"), Some("myClass"));
    }

    #[test]
    fn test_add_multiple_classes() {
        let config = AddClassesToSVGElementConfig {
            class_name: None,
            class_names: Some(vec![
                "class1".to_string(),
                "class2".to_string(),
                "class3".to_string(),
            ]),
        };
        let plugin = AddClassesToSVGElementPlugin::with_config(config);

        let mut doc = Document::new();
        doc.root = create_element("svg");

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

        // Check that all classes were added
        let class_attr = doc.root.attr("class").unwrap();
        let classes: HashSet<&str> = class_attr.split_whitespace().collect();
        assert!(classes.contains("class1"));
        assert!(classes.contains("class2"));
        assert!(classes.contains("class3"));
    }

    #[test]
    fn test_preserves_existing_classes() {
        let config = AddClassesToSVGElementConfig {
            class_name: Some("newClass".to_string()),
            class_names: None,
        };
        let plugin = AddClassesToSVGElementPlugin::with_config(config);

        let mut doc = Document::new();
        doc.root = create_element("svg");
        doc.root.set_attr("class", "existingClass1 existingClass2");

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

        // Check that both existing and new classes are present
        let class_attr = doc.root.attr("class").unwrap();
        let classes: HashSet<&str> = class_attr.split_whitespace().collect();
        assert!(classes.contains("existingClass1"));
        assert!(classes.contains("existingClass2"));
        assert!(classes.contains("newClass"));
    }

    #[test]
    fn test_deduplicates_classes() {
        let config = AddClassesToSVGElementConfig {
            class_name: Some("duplicateClass".to_string()),
            class_names: Some(vec![
                "duplicateClass".to_string(),
                "uniqueClass".to_string(),
            ]),
        };
        let plugin = AddClassesToSVGElementPlugin::with_config(config);

        let mut doc = Document::new();
        doc.root = create_element("svg");
        doc.root.set_attr("class", "duplicateClass");

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

        // Check that duplicate class appears only once
        let class_attr = doc.root.attr("class").unwrap();
        let classes: Vec<&str> = class_attr.split_whitespace().collect();
        assert_eq!(
            classes.iter().filter(|&&c| c == "duplicateClass").count(),
            1
        );
        assert!(classes.contains(&"uniqueClass"));
    }

    #[test]
    fn test_only_applies_to_svg_element() {
        let config = AddClassesToSVGElementConfig {
            class_name: Some("myClass".to_string()),
            class_names: None,
        };
        let plugin = AddClassesToSVGElementPlugin::with_config(config);

        let mut doc = Document::new();
        doc.root = create_element("div"); // Not an SVG element

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

        // Check that no class was added
        assert!(!doc.root.attributes.contains_key("class"));
    }

    #[test]
    fn test_both_class_name_and_class_names() {
        let config = AddClassesToSVGElementConfig {
            class_name: Some("single".to_string()),
            class_names: Some(vec!["multiple1".to_string(), "multiple2".to_string()]),
        };
        let plugin = AddClassesToSVGElementPlugin::with_config(config);

        let mut doc = Document::new();
        doc.root = create_element("svg");

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

        // Check that all classes were added
        let class_attr = doc.root.attr("class").unwrap();
        let classes: HashSet<&str> = class_attr.split_whitespace().collect();
        assert!(classes.contains("single"));
        assert!(classes.contains("multiple1"));
        assert!(classes.contains("multiple2"));
    }

    #[test]
    fn test_empty_class_names_are_ignored() {
        let config = AddClassesToSVGElementConfig {
            class_name: Some("".to_string()), // Empty string
            class_names: Some(vec!["valid".to_string(), "".to_string()]), // Contains empty
        };
        let plugin = AddClassesToSVGElementPlugin::with_config(config);

        let mut doc = Document::new();
        doc.root = create_element("svg");

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

        // Check that only valid class was added
        let class_attr = doc.root.attr("class").unwrap();
        assert_eq!(class_attr, "valid");
    }

    #[test]
    fn test_config_parsing() {
        // Test single class
        let config = AddClassesToSVGElementPlugin::parse_config(&json!({
            "className": "test"
        }))
        .unwrap();
        assert_eq!(config.class_name, Some("test".to_string()));

        // Test array of classes
        let config = AddClassesToSVGElementPlugin::parse_config(&json!({
            "classNames": ["class1", "class2"]
        }))
        .unwrap();
        assert_eq!(
            config.class_names,
            Some(vec!["class1".to_string(), "class2".to_string()])
        );
    }
}

// Use parameterized testing framework for SVGO fixture tests
#[cfg(test)]
#[cfg(test)]
vexy_vsvg_test_utils::plugin_fixture_tests_with_params!(
    AddClassesToSVGElementPlugin,
    "addClassesToSVGElement"
);