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

//! Plugin to remove unused namespace declarations
//!
//! This plugin removes namespace declarations (xmlns:prefix) that aren't actually used
//! in any element names or attribute names throughout the document.
//!
//! ## What It Removes
//!
//! Namespace declarations like `xmlns:inkscape="http://..."` where:
//! - No element uses the prefix (e.g., no `<inkscape:label>`)
//! - No attribute uses the prefix (e.g., no `inkscape:groupmode`)
//!
//! ## What It Preserves
//!
//! - Namespace declarations that ARE used in element/attribute names
//! - The default `xmlns` declaration (always needed for SVG)
//!
//! ## Why Use This
//!
//! - **File size**: Each xmlns declaration adds ~60-100 bytes
//! - **Cleanliness**: Remove editor-added namespaces after removing their attributes
//! - **Compatibility**: Unused namespaces confuse some parsers
//!
//! ## How It Works
//!
//! 1. Collects all namespace prefixes declared on the root element
//! 2. Scans entire document for element/attribute names using those prefixes
//! 3. Removes declarations for prefixes that are never used
//!
//! ## Configuration
//!
//! This plugin accepts no configuration parameters.
//!
//! ## Example
//!
//! Before:
//! ```xml
//! <svg xmlns="http://www.w3.org/2000/svg"
//!      xmlns:xlink="http://www.w3.org/1999/xlink"
//!      xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape">
//!   <rect/>
//! </svg>
//! ```
//!
//! After (xlink and inkscape unused):
//! ```xml
//! <svg xmlns="http://www.w3.org/2000/svg">
//!   <rect/>
//! </svg>
//! ```
//!
//! ## SVGO Compatibility
//!
//! Ports SVGO's `removeUnusedNS` plugin. Tracks prefix usage identically.
//!
//! Reference: https://github.com/svg/svgo/blob/main/plugins/removeUnusedNS.js

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

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

/// Plugin to remove unused namespace declarations
pub struct RemoveUnusedNSPlugin {
    #[allow(dead_code)]
    config: RemoveUnusedNSConfig,
}

impl RemoveUnusedNSPlugin {
    pub fn new() -> Self {
        Self {
            #[allow(dead_code)]
            config: RemoveUnusedNSConfig::default(),
        }
    }

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

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

    fn check_usage(&self, element: &Element, unused_namespaces: &mut HashSet<String>) {
        // Check if element name uses a namespace
        if element.name.contains(':') {
            let parts: Vec<&str> = element.name.split(':').collect();
            if parts.len() >= 2 {
                let ns = parts[0];
                unused_namespaces.remove(ns);
            }
        }

        // Check if any attributes use namespaces
        for attr_name in element.attributes.keys() {
            if attr_name.contains(':') {
                let parts: Vec<&str> = attr_name.split(':').collect();
                if parts.len() >= 2 {
                    let ns = parts[0];
                    unused_namespaces.remove(ns);
                }
            }
        }

        // Recursively check children
        for child in &element.children {
            if let Node::Element(ref elem) = child {
                self.check_usage(elem, unused_namespaces);
            }
        }
    }
}

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

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

    fn description(&self) -> &'static str {
        "removes unused namespaces declaration"
    }

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

    fn apply(&self, document: &mut Document) -> Result<()> {
        // First, collect all namespace declarations from the root SVG element
        let mut unused_namespaces = HashSet::new();

        // Collect xmlns: attributes from root element
        for attr_name in document.root.attributes.keys() {
            if attr_name.starts_with("xmlns:") {
                let local = attr_name.strip_prefix("xmlns:").unwrap();
                unused_namespaces.insert(local.to_string());
            }
        }

        // Traverse the document and remove used namespaces from the unused set
        self.check_usage(&document.root, &mut unused_namespaces);

        // Remove unused namespace declarations from root element
        for ns in &unused_namespaces {
            let xmlns_attr = format!("xmlns:{}", ns);
            document.root.remove_attr(&xmlns_attr);
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use indexmap::IndexMap;
    use vexy_vsvg::ast::{Document, DocumentMetadata, Element, Node};

    fn create_test_document() -> Document<'static> {
        Document {
            prologue: vec![],
            root: Element {
                name: "svg".into(),
                attributes: IndexMap::new(),
                children: vec![],
                namespaces: IndexMap::new(),
            },
            epilogue: vec![],
            metadata: DocumentMetadata::default(),
            memory_budget: None,
        }
    }

    #[test]
    fn test_plugin_info() {
        let plugin = RemoveUnusedNSPlugin::new();
        assert_eq!(plugin.name(), "removeUnusedNS");
        assert_eq!(
            plugin.description(),
            "removes unused namespaces declaration"
        );
    }

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

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

        // Test empty object params
        assert!(plugin.validate_params(&serde_json::json!({})).is_ok());

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

    #[test]
    fn test_remove_unused_namespace() {
        let mut document = create_test_document();

        // Add unused namespace
        document
            .root
            .set_attr("xmlns:unused", "http://example.com/unused");
        document
            .root
            .set_attr("xmlns:xlink", "http://www.w3.org/1999/xlink");

        // Add an element that uses xlink
        let mut rect_element = Element {
            name: "rect".into(),
            attributes: IndexMap::new(),
            children: vec![],
            namespaces: IndexMap::new(),
        };
        rect_element.set_attr("xlink:href", "#test");

        document.root.children = vec![Node::Element(rect_element)];

        let plugin = RemoveUnusedNSPlugin::new();
        let result = plugin.apply(&mut document);
        assert!(result.is_ok());

        // unused namespace should be removed, xlink should remain
        assert!(!document.root.has_attr("xmlns:unused"));
        assert!(document.root.has_attr("xmlns:xlink"));
    }

    #[test]
    fn test_preserve_used_namespace_in_element_name() {
        let mut document = create_test_document();

        // Add namespace
        document
            .root
            .set_attr("xmlns:svg", "http://www.w3.org/2000/svg");

        // Add a child element with namespaced name
        let ns_element = Element {
            name: "svg:g".into(),
            attributes: IndexMap::new(),
            children: vec![],
            namespaces: IndexMap::new(),
        };

        document.root.children = vec![Node::Element(ns_element)];

        let plugin = RemoveUnusedNSPlugin::new();
        let result = plugin.apply(&mut document);
        assert!(result.is_ok());

        // svg namespace should be preserved
        assert!(document.root.has_attr("xmlns:svg"));
    }

    #[test]
    fn test_preserve_used_namespace_in_attributes() {
        let mut document = create_test_document();

        // Add namespace
        document
            .root
            .set_attr("xmlns:custom", "http://example.com/custom");

        // Add an element with namespaced attribute
        let mut element = Element {
            name: "rect".into(),
            attributes: IndexMap::new(),
            children: vec![],
            namespaces: IndexMap::new(),
        };
        element.set_attr("custom:data", "value");

        document.root.children = vec![Node::Element(element)];

        let plugin = RemoveUnusedNSPlugin::new();
        let result = plugin.apply(&mut document);
        assert!(result.is_ok());

        // custom namespace should be preserved
        assert!(document.root.has_attr("xmlns:custom"));
    }

    #[test]
    fn test_remove_all_unused_namespaces() {
        let mut document = create_test_document();

        // Add multiple unused namespaces
        document
            .root
            .set_attr("xmlns:ns1", "http://example.com/ns1");
        document
            .root
            .set_attr("xmlns:ns2", "http://example.com/ns2");
        document
            .root
            .set_attr("xmlns:ns3", "http://example.com/ns3");

        // Add an element without any namespace usage
        let element = Element {
            name: "rect".into(),
            attributes: IndexMap::new(),
            children: vec![],
            namespaces: IndexMap::new(),
        };

        document.root.children = vec![Node::Element(element)];

        let plugin = RemoveUnusedNSPlugin::new();
        let result = plugin.apply(&mut document);
        assert!(result.is_ok());

        // All unused namespaces should be removed
        assert!(!document.root.has_attr("xmlns:ns1"));
        assert!(!document.root.has_attr("xmlns:ns2"));
        assert!(!document.root.has_attr("xmlns:ns3"));
    }

    #[test]
    fn test_no_namespaces_to_remove() {
        let mut document = create_test_document();

        // No xmlns: attributes
        document.root.set_attr("width", "100");
        document.root.set_attr("height", "100");

        let plugin = RemoveUnusedNSPlugin::new();
        let result = plugin.apply(&mut document);
        assert!(result.is_ok());

        // Should still have original attributes
        assert_eq!(document.root.attr("width"), Some("100"));
        assert_eq!(document.root.attr("height"), Some("100"));
    }

    #[test]
    fn test_nested_element_namespace_usage() {
        let mut document = create_test_document();

        // Add namespace
        document
            .root
            .set_attr("xmlns:deep", "http://example.com/deep");

        // Create nested structure where namespace is used deep in the tree
        let mut deep_element = Element {
            name: "text".into(),
            attributes: IndexMap::new(),
            children: vec![],
            namespaces: IndexMap::new(),
        };
        deep_element.set_attr("deep:attr", "value");

        let middle_element = Element {
            name: "g".into(),
            attributes: IndexMap::new(),
            children: vec![Node::Element(deep_element)],
            namespaces: IndexMap::new(),
        };

        let container_element = Element {
            name: "g".into(),
            attributes: IndexMap::new(),
            children: vec![Node::Element(middle_element)],
            namespaces: IndexMap::new(),
        };

        document.root.children = vec![Node::Element(container_element)];

        let plugin = RemoveUnusedNSPlugin::new();
        let result = plugin.apply(&mut document);
        assert!(result.is_ok());

        // deep namespace should be preserved (used in nested element)
        assert!(document.root.has_attr("xmlns:deep"));
    }

    #[test]
    fn test_mixed_used_and_unused_namespaces() {
        let mut document = create_test_document();

        // Add multiple namespaces
        document
            .root
            .set_attr("xmlns:used", "http://example.com/used");
        document
            .root
            .set_attr("xmlns:unused", "http://example.com/unused");
        document
            .root
            .set_attr("xmlns:alsounused", "http://example.com/alsounused");

        // Add an element that uses only one namespace
        let mut element = Element {
            name: "rect".into(),
            attributes: IndexMap::new(),
            children: vec![],
            namespaces: IndexMap::new(),
        };
        element.set_attr("used:data", "value");

        document.root.children = vec![Node::Element(element)];

        let plugin = RemoveUnusedNSPlugin::new();
        let result = plugin.apply(&mut document);
        assert!(result.is_ok());

        // Only used namespace should remain
        assert!(document.root.has_attr("xmlns:used"));
        assert!(!document.root.has_attr("xmlns:unused"));
        assert!(!document.root.has_attr("xmlns:alsounused"));
    }
}