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

//! Remove deprecated attributes
//!
//! This plugin removes deprecated SVG attributes from elements. It has a safe mode
//! that removes attributes known to be safe to remove, and an unsafe mode that
//! removes additional deprecated attributes that might affect rendering.
//!
//! Reference: SVGO's removeDeprecatedAttrs plugin

use crate::Plugin;
use anyhow::Result;
use once_cell::sync::Lazy;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::{HashMap, HashSet};
use vexy_vsvg::ast::{Document, Element, Node};

/// Configuration for the plugin
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[derive(Default)]
pub struct RemoveDeprecatedAttrsConfig {
    /// Whether to remove unsafe deprecated attributes
    #[serde(default)]
    pub remove_unsafe: bool,
}

/// Main plugin struct
pub struct RemoveDeprecatedAttrsPlugin {
    config: RemoveDeprecatedAttrsConfig,
}

impl RemoveDeprecatedAttrsPlugin {
    pub fn new() -> Self {
        Self {
            config: RemoveDeprecatedAttrsConfig::default(),
        }
    }

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

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

    fn process_element(&self, element: &mut Element) {
        // Process children first
        let mut i = 0;
        while i < element.children.len() {
            if let Node::Element(child) = &mut element.children[i] {
                self.process_element(child);
            }
            i += 1;
        }

        // Get element configuration
        if let Some(elem_config) = ELEMENT_CONFIGS.get(element.name.as_ref()) {
            // Special case: Remove xml:lang if lang attribute exists
            if elem_config.attrs_groups.contains("core")
                && element.has_attr("xml:lang")
                && element.has_attr("lang")
            {
                element.remove_attr("xml:lang");
            }

            // Process deprecated attributes from attribute groups
            for attrs_group in &elem_config.attrs_groups {
                if let Some(deprecated_attrs) = ATTRS_GROUPS_DEPRECATED.get(attrs_group) {
                    self.process_attributes(element, deprecated_attrs);
                }
            }

            // Process element-specific deprecated attributes
            if let Some(ref deprecated) = elem_config.deprecated {
                self.process_attributes(element, deprecated);
            }
        }
    }

    fn process_attributes(&self, element: &mut Element, deprecated_attrs: &DeprecatedAttrs) {
        // Remove safe deprecated attributes
        for attr_name in &deprecated_attrs.safe {
            element.remove_attr(attr_name);
        }

        // Remove unsafe deprecated attributes if requested
        if self.config.remove_unsafe {
            for attr_name in &deprecated_attrs.unsafe_attrs {
                element.remove_attr(attr_name);
            }
        }
    }
}

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

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

    fn description(&self) -> &'static str {
        "removes deprecated attributes"
    }

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

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

/// Deprecated attributes structure
#[derive(Debug, Clone)]
struct DeprecatedAttrs {
    safe: HashSet<String>,
    unsafe_attrs: HashSet<String>,
}

/// Element configuration
#[derive(Debug, Clone)]
struct ElementConfig {
    attrs_groups: HashSet<&'static str>,
    deprecated: Option<DeprecatedAttrs>,
}

/// Deprecated attributes grouped by attribute group
static ATTRS_GROUPS_DEPRECATED: Lazy<HashMap<&'static str, DeprecatedAttrs>> = Lazy::new(|| {
    let mut map = HashMap::new();

    map.insert(
        "animationAttributeTarget",
        DeprecatedAttrs {
            safe: HashSet::new(),
            unsafe_attrs: vec!["attributeType"]
                .into_iter()
                .map(String::from)
                .collect(),
        },
    );

    map.insert(
        "conditionalProcessing",
        DeprecatedAttrs {
            safe: HashSet::new(),
            unsafe_attrs: vec!["requiredFeatures"]
                .into_iter()
                .map(String::from)
                .collect(),
        },
    );

    map.insert(
        "core",
        DeprecatedAttrs {
            safe: HashSet::new(),
            unsafe_attrs: vec!["xml:base", "xml:lang", "xml:space"]
                .into_iter()
                .map(String::from)
                .collect(),
        },
    );

    map.insert(
        "presentation",
        DeprecatedAttrs {
            safe: HashSet::new(),
            unsafe_attrs: vec![
                "clip",
                "color-profile",
                "enable-background",
                "glyph-orientation-horizontal",
                "glyph-orientation-vertical",
                "kerning",
            ]
            .into_iter()
            .map(String::from)
            .collect(),
        },
    );

    map
});

/// Element configurations with their attribute groups
static ELEMENT_CONFIGS: Lazy<HashMap<&'static str, ElementConfig>> = Lazy::new(|| {
    let mut map = HashMap::new();

    // Common attribute groups
    let common_groups = vec![
        "conditionalProcessing",
        "core",
        "graphicalEvent",
        "presentation",
    ];

    // Define configurations for various elements
    map.insert(
        "a",
        ElementConfig {
            attrs_groups: common_groups.iter().copied().chain(vec!["xlink"]).collect(),
            deprecated: None,
        },
    );

    map.insert(
        "circle",
        ElementConfig {
            attrs_groups: common_groups.clone().into_iter().collect(),
            deprecated: None,
        },
    );

    map.insert(
        "ellipse",
        ElementConfig {
            attrs_groups: common_groups.clone().into_iter().collect(),
            deprecated: None,
        },
    );

    map.insert(
        "g",
        ElementConfig {
            attrs_groups: common_groups.clone().into_iter().collect(),
            deprecated: None,
        },
    );

    map.insert(
        "image",
        ElementConfig {
            attrs_groups: common_groups.iter().copied().chain(vec!["xlink"]).collect(),
            deprecated: None,
        },
    );

    map.insert(
        "line",
        ElementConfig {
            attrs_groups: common_groups.clone().into_iter().collect(),
            deprecated: None,
        },
    );

    map.insert(
        "path",
        ElementConfig {
            attrs_groups: common_groups.clone().into_iter().collect(),
            deprecated: None,
        },
    );

    map.insert(
        "polygon",
        ElementConfig {
            attrs_groups: common_groups.clone().into_iter().collect(),
            deprecated: None,
        },
    );

    map.insert(
        "polyline",
        ElementConfig {
            attrs_groups: common_groups.clone().into_iter().collect(),
            deprecated: None,
        },
    );

    map.insert(
        "rect",
        ElementConfig {
            attrs_groups: common_groups.clone().into_iter().collect(),
            deprecated: None,
        },
    );

    map.insert(
        "svg",
        ElementConfig {
            attrs_groups: vec![
                "conditionalProcessing",
                "core",
                "documentEvent",
                "graphicalEvent",
                "presentation",
            ]
            .into_iter()
            .collect(),
            deprecated: None,
        },
    );

    map.insert(
        "text",
        ElementConfig {
            attrs_groups: common_groups.clone().into_iter().collect(),
            deprecated: None,
        },
    );

    map.insert(
        "use",
        ElementConfig {
            attrs_groups: common_groups.iter().copied().chain(vec!["xlink"]).collect(),
            deprecated: None,
        },
    );

    // Animation elements
    map.insert(
        "animate",
        ElementConfig {
            attrs_groups: vec![
                "conditionalProcessing",
                "core",
                "animationEvent",
                "xlink",
                "animationAttributeTarget",
                "animationTiming",
                "animationValue",
                "animationAddition",
                "presentation",
            ]
            .into_iter()
            .collect(),
            deprecated: None,
        },
    );

    map.insert(
        "animateTransform",
        ElementConfig {
            attrs_groups: vec![
                "conditionalProcessing",
                "core",
                "animationEvent",
                "xlink",
                "animationAttributeTarget",
                "animationTiming",
                "animationValue",
                "animationAddition",
            ]
            .into_iter()
            .collect(),
            deprecated: None,
        },
    );

    // Add more elements as needed
    map
});

#[cfg(test)]
mod tests {
    use super::*;
    use indexmap::IndexMap;
    use serde_json::json;

    fn create_test_document() -> Document<'static> {
        let mut doc = Document::default();

        let mut svg = Element {
            name: "svg".into(),
            namespaces: IndexMap::new(),
            attributes: IndexMap::new(),
            children: vec![],
        };
        svg.set_attr("xml:lang", "en");
        svg.set_attr("lang", "en");
        svg.set_attr("xml:space", "preserve");

        let mut rect = Element {
            name: "rect".into(),
            namespaces: IndexMap::new(),
            attributes: IndexMap::new(),
            children: vec![],
        };
        rect.set_attr("x", "0");
        rect.set_attr("y", "0");
        rect.set_attr("width", "100");
        rect.set_attr("height", "100");
        rect.set_attr("enable-background", "new");
        rect.set_attr("clip", "rect(0 0 100 100)");

        svg.children.push(Node::Element(rect));
        doc.root = svg;
        doc
    }

    #[test]
    fn test_plugin_info() {
        let plugin = RemoveDeprecatedAttrsPlugin::new();
        assert_eq!(plugin.name(), "removeDeprecatedAttrs");
        assert_eq!(plugin.description(), "removes deprecated attributes");
    }

    #[test]
    fn test_param_validation() {
        let plugin = RemoveDeprecatedAttrsPlugin::new();

        // Test null params
        assert!(plugin.validate_params(&Value::Null).is_ok());

        // Test valid params
        assert!(plugin
            .validate_params(&json!({
                "removeUnsafe": true
            }))
            .is_ok());

        // Test invalid params
        assert!(plugin
            .validate_params(&json!({
                "invalidParam": true
            }))
            .is_err());
    }

    #[test]
    fn test_remove_xml_lang_when_lang_exists() {
        let mut doc = create_test_document();
        let plugin = RemoveDeprecatedAttrsPlugin::new();

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

        // xml:lang should be removed because lang exists
        assert_eq!(doc.root.attr("xml:lang"), None);
        assert_eq!(doc.root.attr("lang"), Some("en"));
        // xml:space should still exist (unsafe attribute)
        assert_eq!(doc.root.attr("xml:space"), Some("preserve"));
    }

    #[test]
    fn test_remove_unsafe_attributes() {
        let mut doc = create_test_document();
        let config = RemoveDeprecatedAttrsConfig {
            remove_unsafe: true,
        };
        let plugin = RemoveDeprecatedAttrsPlugin::with_config(config);

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

        // xml:space should be removed with removeUnsafe
        assert_eq!(doc.root.attr("xml:space"), None);

        // Check rect element - unsafe presentation attributes should be removed
        if let Some(Node::Element(ref rect)) = doc.root.children.first() {
            assert_eq!(rect.attr("enable-background"), None);
            assert_eq!(rect.attr("clip"), None);
            // Regular attributes should remain
            assert_eq!(rect.attr("width"), Some("100"));
        }
    }

    #[test]
    fn test_keep_xml_lang_without_lang() {
        let mut doc = Document::default();

        let mut svg = Element {
            name: "svg".into(),
            namespaces: IndexMap::new(),
            attributes: IndexMap::new(),
            children: vec![],
        };
        svg.set_attr("xml:lang", "en");
        // No lang attribute

        doc.root = svg;

        let plugin = RemoveDeprecatedAttrsPlugin::new();

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

        // xml:lang should be kept because lang doesn't exist
        assert_eq!(doc.root.attr("xml:lang"), Some("en"));
    }

    #[test]
    fn test_animation_attribute_target() {
        let mut doc = Document::default();

        let mut svg = Element {
            name: "svg".into(),
            namespaces: IndexMap::new(),
            attributes: IndexMap::new(),
            children: vec![],
        };

        let mut animate = Element {
            name: "animate".into(),
            namespaces: IndexMap::new(),
            attributes: IndexMap::new(),
            children: vec![],
        };
        animate.set_attr("attributeType", "XML");
        animate.set_attr("attributeName", "x");

        svg.children.push(Node::Element(animate));
        doc.root = svg;

        let config = RemoveDeprecatedAttrsConfig {
            remove_unsafe: true,
        };
        let plugin = RemoveDeprecatedAttrsPlugin::with_config(config);

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

        // attributeType is an unsafe deprecated attribute
        if let Some(Node::Element(ref animate)) = doc.root.children.first() {
            assert_eq!(animate.attr("attributeType"), None);
            assert_eq!(animate.attr("attributeName"), Some("x"));
        }
    }
}