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

pub mod default_attrs;
pub mod unknown_elements;

use crate::Plugin;
use anyhow::Result;
use vexy_vsvg::ast::{Document, Element, Node};
use vexy_vsvg::error::VexyError;
use vexy_vsvg::visitor::Visitor;

use self::default_attrs::should_remove_attribute;
use self::unknown_elements::should_remove_unknown_element;

/// Configuration parameters for RemoveUnknownsAndDefaults plugin
#[derive(Debug, Clone)]
pub struct RemoveUnknownsAndDefaultsConfig {
    pub unknown_content: bool,
    pub unknown_attrs: bool,
    pub default_attrs: bool,
    pub default_markup_declarations: bool,
    pub useless_overrides: bool,
    pub keep_data_attrs: bool,
    pub keep_aria_attrs: bool,
    pub keep_role_attr: bool,
}

impl Default for RemoveUnknownsAndDefaultsConfig {
    fn default() -> Self {
        Self {
            unknown_content: true,
            unknown_attrs: true,
            default_attrs: true,
            default_markup_declarations: true,
            useless_overrides: true,
            keep_data_attrs: true,
            keep_aria_attrs: true,
            keep_role_attr: false,
        }
    }
}

/// Plugin that removes unknown elements, attributes, and default values
pub struct RemoveUnknownsAndDefaultsPlugin {
    config: RemoveUnknownsAndDefaultsConfig,
}

impl RemoveUnknownsAndDefaultsPlugin {
    /// Create a new RemoveUnknownsAndDefaultsPlugin with default configuration
    pub fn new() -> Self {
        Self {
            config: RemoveUnknownsAndDefaultsConfig::default(),
        }
    }

    /// Create a new RemoveUnknownsAndDefaultsPlugin with custom configuration
    pub fn with_config(config: RemoveUnknownsAndDefaultsConfig) -> Self {
        Self { config }
    }
}

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

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

    fn description(&self) -> &'static str {
        "Remove unknown elements, attributes, and default values"
    }

    fn validate_params(&self, params: &serde_json::Value) -> anyhow::Result<()> {
        if let Some(obj) = params.as_object() {
            for (key, value) in obj {
                match key.as_str() {
                    "unknownContent"
                    | "unknownAttrs"
                    | "defaultAttrs"
                    | "defaultMarkupDeclarations"
                    | "uselessOverrides"
                    | "keepDataAttrs"
                    | "keepAriaAttrs"
                    | "keepRoleAttr" => {
                        if !value.is_boolean() {
                            return Err(anyhow::anyhow!("{} must be a boolean", key));
                        }
                    }
                    _ => {
                        return Err(anyhow::anyhow!("Unknown parameter: {}", key));
                    }
                }
            }
        }
        Ok(())
    }

    fn apply(&self, document: &mut Document) -> anyhow::Result<()> {
        let mut visitor = UnknownsAndDefaultsRemovalVisitor::new(self.config.clone());
        vexy_vsvg::visitor::walk_document(&mut visitor, document)?;
        Ok(())
    }
}

/// Visitor implementation that removes unknowns and defaults
struct UnknownsAndDefaultsRemovalVisitor {
    config: RemoveUnknownsAndDefaultsConfig,
    element_stack: Vec<String>,
    /// Tracks the inherited value of each inheritable presentation attribute
    /// from ancestor elements. When a parent sets `stroke="#000"`, children
    /// must NOT have their `stroke="none"` removed even though "none" is the
    /// SVG default — removing it would cause them to inherit "#000" instead.
    inherited_attrs: Vec<std::collections::HashMap<String, String>>,
}

impl UnknownsAndDefaultsRemovalVisitor {
    fn new(config: RemoveUnknownsAndDefaultsConfig) -> Self {
        Self {
            config,
            element_stack: Vec::new(),
            inherited_attrs: Vec::new(),
        }
    }

    #[allow(dead_code)]
    fn get_parent_element_name(&self) -> Option<&str> {
        self.element_stack
            .get(self.element_stack.len().saturating_sub(2))
            .map(|s| s.as_str())
    }

    /// Returns the inherited value of an attribute from ancestor elements.
    /// Walks the stack from top (nearest ancestor) to bottom.
    fn get_inherited_value(&self, attr_name: &str) -> Option<&str> {
        for frame in self.inherited_attrs.iter().rev() {
            if let Some(value) = frame.get(attr_name) {
                return Some(value.as_str());
            }
        }
        None
    }
}

impl Visitor<'_> for UnknownsAndDefaultsRemovalVisitor {
    fn visit_element_enter(&mut self, element: &mut Element<'_>) -> Result<(), VexyError> {
        self.element_stack.push(element.name.to_string());

        let mut attrs_to_remove = Vec::new();
        for (attr_name, attr_value) in &element.attributes {
            if should_remove_attribute(
                attr_name,
                attr_value,
                element,
                self.get_inherited_value(attr_name),
                &self.config,
            ) {
                attrs_to_remove.push(attr_name.clone());
            }
        }

        for attr_name in attrs_to_remove {
            element.attributes.shift_remove(&attr_name);
        }

        // Record this element's inheritable attrs so descendants can check them
        let mut frame = std::collections::HashMap::new();
        for (attr_name, attr_value) in &element.attributes {
            if default_attrs::is_inheritable_presentation_attr_pub(attr_name) {
                frame.insert(attr_name.to_string(), attr_value.to_string());
            }
        }
        self.inherited_attrs.push(frame);

        Ok(())
    }

    fn visit_element_exit(&mut self, element: &mut Element<'_>) -> Result<(), VexyError> {
        self.element_stack.pop();
        self.inherited_attrs.pop();

        // Remove unknown child elements
        let _plugin = RemoveUnknownsAndDefaultsPlugin::with_config(self.config.clone());

        element.children.retain(|child| {
            match child {
                Node::Element(child_element) => {
                    !should_remove_unknown_element(child_element, self.config.unknown_content)
                }
                _ => true, // Keep non-element nodes
            }
        });

        Ok(())
    }
}

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

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

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

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

    #[test]
    fn test_configuration_defaults() {
        let config = RemoveUnknownsAndDefaultsConfig::default();
        assert!(config.unknown_content);
        assert!(config.unknown_attrs);
        assert!(config.default_attrs);
        assert!(config.default_markup_declarations);
        assert!(config.useless_overrides);
        assert!(config.keep_data_attrs);
        assert!(config.keep_aria_attrs);
        assert!(!config.keep_role_attr);
    }

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

        // Valid parameters
        assert!(plugin.validate_params(&json!({})).is_ok());
        assert!(plugin
            .validate_params(&json!({"unknownContent": true}))
            .is_ok());
        assert!(plugin
            .validate_params(&json!({"keepDataAttrs": false}))
            .is_ok());

        // Invalid parameters
        assert!(plugin
            .validate_params(&json!({"unknownContent": "invalid"}))
            .is_err());
        assert!(plugin
            .validate_params(&json!({"invalidParam": true}))
            .is_err());
    }

    #[test]
    fn test_known_elements() {
        let known = unknown_elements::known_elements();
        assert!(known.contains("svg"));
        assert!(known.contains("rect"));
        assert!(known.contains("circle"));
        assert!(known.contains("path"));
        assert!(!known.contains("unknown-element"));
    }

    #[test]
    fn test_known_attributes() {
        let known = default_attrs::known_attributes();
        assert!(known.contains("id"));
        assert!(known.contains("class"));
        assert!(known.contains("fill"));
        assert!(known.contains("stroke"));
        assert!(!known.contains("unknown-attr"));
    }

    #[test]
    fn test_default_values() {
        let defaults = default_attrs::default_attribute_values();
        assert_eq!(defaults.get("x"), Some(&"0"));
        assert_eq!(defaults.get("y"), Some(&"0"));
        assert_eq!(defaults.get("fill"), Some(&"black"));
        assert_eq!(defaults.get("stroke"), Some(&"none"));
    }

    #[test]
    fn test_should_remove_unknown_element() {
        let plugin = RemoveUnknownsAndDefaultsPlugin::new();

        // Known elements should not be removed
        let rect = create_element("rect");
        assert!(!should_remove_unknown_element(
            &rect,
            plugin.config.unknown_content
        ));

        // Unknown elements should be removed
        let unknown = create_element("unknown-element");
        assert!(should_remove_unknown_element(
            &unknown,
            plugin.config.unknown_content
        ));

        // Namespaced elements should not be removed
        let mut namespaced = create_element("custom:element");
        namespaced.name = Cow::Borrowed("custom:element");
        assert!(!should_remove_unknown_element(
            &namespaced,
            plugin.config.unknown_content
        ));
    }

    #[test]
    fn test_should_remove_attribute_unknown() {
        let plugin = RemoveUnknownsAndDefaultsPlugin::new();
        let element = create_element("rect");

        // Known attributes should not be removed
        assert!(!should_remove_attribute(
            "fill",
            "red",
            &element,
            None,
            &plugin.config
        ));

        // Unknown attributes should be removed
        assert!(should_remove_attribute(
            "unknown-attr",
            "value",
            &element,
            None,
            &plugin.config
        ));

        // Data attributes should be preserved by default
        assert!(!should_remove_attribute(
            "data-test",
            "value",
            &element,
            None,
            &plugin.config
        ));

        // ARIA attributes should be preserved by default
        assert!(!should_remove_attribute(
            "aria-label",
            "test",
            &element,
            None,
            &plugin.config
        ));

        // Role attribute should be removed by default (keepRoleAttr is false)
        assert!(should_remove_attribute(
            "role",
            "button",
            &element,
            None,
            &plugin.config
        ));

        // Role attribute should be kept when keepRoleAttr is true
        let config = RemoveUnknownsAndDefaultsConfig {
            keep_role_attr: true,
            ..RemoveUnknownsAndDefaultsConfig::default()
        };
        let plugin_keep_role = RemoveUnknownsAndDefaultsPlugin::with_config(config);
        assert!(!should_remove_attribute(
            "role",
            "button",
            &element,
            None,
            &plugin_keep_role.config
        ));
    }

    #[test]
    fn test_should_remove_attribute_defaults() {
        let plugin = RemoveUnknownsAndDefaultsPlugin::new();
        let element = create_element("rect");

        // Default values should be removed
        assert!(should_remove_attribute(
            "x",
            "0",
            &element,
            None,
            &plugin.config
        ));
        assert!(should_remove_attribute(
            "fill",
            "black",
            &element,
            None,
            &plugin.config
        ));

        // Non-default values should not be removed
        assert!(!should_remove_attribute(
            "x",
            "10",
            &element,
            None,
            &plugin.config
        ));
        assert!(!should_remove_attribute(
            "fill",
            "red",
            &element,
            None,
            &plugin.config
        ));

        // Elements with id should keep their default values
        let element_with_id = create_element_with_attrs("rect", &[("id", "test")]);
        assert!(!should_remove_attribute(
            "x",
            "0",
            &element_with_id,
            None,
            &plugin.config
        ));
    }

    #[test]
    fn test_should_remove_attribute_namespaced() {
        let plugin = RemoveUnknownsAndDefaultsPlugin::new();
        let element = create_element("rect");

        // xmlns attributes should be preserved
        assert!(!should_remove_attribute(
            "xmlns",
            "http://www.w3.org/2000/svg",
            &element,
            None,
            &plugin.config
        ));
        assert!(!should_remove_attribute(
            "xmlns:xlink",
            "http://www.w3.org/1999/xlink",
            &element,
            None,
            &plugin.config
        ));

        // xml: and xlink: attributes should be preserved
        assert!(!should_remove_attribute(
            "xml:space",
            "preserve",
            &element,
            None,
            &plugin.config
        ));
        assert!(!should_remove_attribute(
            "xlink:href",
            "#test",
            &element,
            None,
            &plugin.config
        ));

        // Other namespaced attributes should be removed if unknown
        assert!(should_remove_attribute(
            "custom:attr",
            "value",
            &element,
            None,
            &plugin.config
        ));
    }

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

        // Add known and unknown elements
        doc.root
            .children
            .push(Node::Element(create_element("rect")));
        doc.root
            .children
            .push(Node::Element(create_element("unknown-element")));
        doc.root
            .children
            .push(Node::Element(create_element("circle")));

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

        // Unknown element should be removed
        assert_eq!(doc.root.children.len(), 2);

        // Check that known elements remain
        let element_names: Vec<&str> = doc
            .root
            .children
            .iter()
            .filter_map(|child| match child {
                Node::Element(elem) => Some(elem.name.as_ref()),
                _ => None,
            })
            .collect();

        assert!(element_names.contains(&"rect"));
        assert!(element_names.contains(&"circle"));
        assert!(!element_names.contains(&"unknown-element"));
    }

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

        // Create element with known and unknown attributes
        let element = create_element_with_attrs(
            "rect",
            &[
                ("width", "100"),
                ("height", "100"),
                ("unknown-attr", "value"),
                ("data-test", "keep"),
            ],
        );

        doc.root.children.push(Node::Element(element));

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

        if let Some(Node::Element(rect)) = doc.root.children.first() {
            assert!(rect.attributes.contains_key("width"));
            assert!(rect.attributes.contains_key("height"));
            assert!(rect.attributes.contains_key("data-test"));
            assert!(!rect.attributes.contains_key("unknown-attr"));
        }
    }

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

        // Create element with default and non-default values
        let element = create_element_with_attrs(
            "rect",
            &[
                ("x", "0"),        // default
                ("y", "10"),       // non-default
                ("fill", "black"), // default
                ("stroke", "red"), // non-default
            ],
        );

        doc.root.children.push(Node::Element(element));

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

        if let Some(Node::Element(rect)) = doc.root.children.first() {
            assert!(!rect.attributes.contains_key("x"));
            assert!(rect.attributes.contains_key("y"));
            assert!(!rect.attributes.contains_key("fill"));
            assert!(rect.attributes.contains_key("stroke"));
        }
    }

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

        // Create element with id and default values
        let element = create_element_with_attrs(
            "rect",
            &[
                ("id", "test"),
                ("x", "0"),        // default, but should be kept
                ("fill", "black"), // default, but should be kept
            ],
        );

        doc.root.children.push(Node::Element(element));

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

        if let Some(Node::Element(rect)) = doc.root.children.first() {
            assert!(rect.attributes.contains_key("id"));
            assert!(rect.attributes.contains_key("x"));
            assert!(rect.attributes.contains_key("fill"));
        }
    }
}