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

//! Reorders element attributes for better gzip compression.
//!
//! Consistent attribute ordering creates repeating patterns that gzip compresses well.
//! This plugin sorts attributes by priority (configurable), namespace type, then alphabetically.
//!
//! **What it does:**
//! - Moves namespace declarations (`xmlns`, `xmlns:*`) to the front (or configurable position)
//! - Sorts attributes by priority list (e.g., `id` before `width` before `fill`)
//! - Falls back to alphabetical order for unlisted attributes
//! - Groups related attributes (e.g., `fill` and `fill-opacity` stay together)
//!
//! **Configuration:**
//! - `order`: Priority list for attribute ordering (default: `["id", "width", "height", "x", "y", ...]`)
//! - `xmlnsOrder`: Where to place namespace attributes (default: `"front"`)
//!
//! **Example:**
//! ```xml
//! <!-- Before -->
//! <rect height="100" fill="red" width="200" id="box" xmlns="http://www.w3.org/2000/svg"/>
//!
//! <!-- After -->
//! <rect xmlns="http://www.w3.org/2000/svg" id="box" width="200" height="100" fill="red"/>
//! ```
//!
//! **Why it helps:** gzip looks for repeated byte sequences. Sorting attributes consistently
//! across all elements creates patterns like `id="` and `width="` that appear in the same
//! position, improving compression ratios by 1-3%.
//!
//! **Default priority order:** `id`, `width`, `height`, `x`, `y`, `cx`, `cy`, `r`, `fill`,
//! `stroke`, `marker`, `d`, `points` (common attributes first, presentation attributes last).
//!
//! Reference: SVGO's sortAttrs plugin

use anyhow::Result;
use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::cmp::Ordering;
use vexy_vsvg::ast::{Document, Element, Node};
use vexy_vsvg::Plugin;

/// Configuration parameters for sort attributes plugin
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct SortAttrsConfig {
    /// Order of attributes to prioritize
    #[serde(default = "default_order")]
    pub order: Vec<String>,
    /// How to handle xmlns attributes
    #[serde(default = "default_xmlns_order")]
    pub xmlns_order: String,
}

fn default_order() -> Vec<String> {
    vec![
        "id".to_string(),
        "width".to_string(),
        "height".to_string(),
        "x".to_string(),
        "x1".to_string(),
        "x2".to_string(),
        "y".to_string(),
        "y1".to_string(),
        "y2".to_string(),
        "cx".to_string(),
        "cy".to_string(),
        "r".to_string(),
        "fill".to_string(),
        "stroke".to_string(),
        "marker".to_string(),
        "d".to_string(),
        "points".to_string(),
    ]
}

fn default_xmlns_order() -> String {
    "front".to_string()
}

impl Default for SortAttrsConfig {
    fn default() -> Self {
        Self {
            order: default_order(),
            xmlns_order: default_xmlns_order(),
        }
    }
}

/// Plugin that sorts element attributes
pub struct SortAttrsPlugin {
    config: SortAttrsConfig,
}

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

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

    /// Parse configuration from JSON
    fn parse_config(params: &Value) -> Result<SortAttrsConfig> {
        if params.is_null() || (params.is_object() && params.as_object().unwrap().is_empty()) {
            Ok(SortAttrsConfig::default())
        } else if params.is_object() {
            serde_json::from_value(params.clone())
                .map_err(|e| anyhow::anyhow!("Invalid configuration: {}", e))
        } else {
            Ok(SortAttrsConfig::default())
        }
    }

    /// Get namespace priority for sorting
    fn get_ns_priority(&self, name: &str) -> i32 {
        if self.config.xmlns_order == "front" {
            // Put xmlns first
            if name == "xmlns" {
                return 3;
            }
            // xmlns:* attributes second
            if name.starts_with("xmlns:") {
                return 2;
            }
        }
        // Other namespaces after and sort them alphabetically
        if name.contains(':') {
            return 1;
        }
        // Other attributes
        0
    }

    /// Compare two attributes for sorting
    fn compare_attrs(&self, a_name: &str, b_name: &str) -> Ordering {
        // Sort namespaces - higher priority comes first
        let a_priority = self.get_ns_priority(a_name);
        let b_priority = self.get_ns_priority(b_name);
        let priority_ns = b_priority.cmp(&a_priority);
        if priority_ns != Ordering::Equal {
            return priority_ns;
        }

        // If both are xmlns attributes with same priority, sort alphabetically
        if (a_name == "xmlns" || a_name.starts_with("xmlns:"))
            && (b_name == "xmlns" || b_name.starts_with("xmlns:"))
        {
            return a_name.cmp(b_name);
        }

        // Extract the first part from attributes
        // For example "fill" from "fill" and "fill-opacity"
        let a_part = a_name.split('-').next().unwrap_or(a_name);
        let b_part = b_name.split('-').next().unwrap_or(b_name);

        // Rely on alphabetical sort when the first part is the same
        if a_part != b_part {
            let a_in_order = self.config.order.contains(&a_part.to_string());
            let b_in_order = self.config.order.contains(&b_part.to_string());

            // Sort by position in order param
            if a_in_order && b_in_order {
                let a_pos = self.config.order.iter().position(|x| x == a_part).unwrap();
                let b_pos = self.config.order.iter().position(|x| x == b_part).unwrap();
                return a_pos.cmp(&b_pos);
            }

            // Put attributes from order param before others
            match (a_in_order, b_in_order) {
                (true, false) => return Ordering::Less,
                (false, true) => return Ordering::Greater,
                _ => {}
            }
        }

        // Sort alphabetically
        a_name.cmp(b_name)
    }

    /// Sort attributes on an element
    fn sort_attrs_recursive(&self, element: &mut Element) {
        // Sort attributes on this element
        if !element.attributes.is_empty() {
            // Always apply custom sorting for sortAttrs plugin
            let mut attrs: Vec<(String, String)> = element
                .attributes
                .iter()
                .map(|(k, v)| (k.to_string(), v.to_string()))
                .collect();

            attrs.sort_by(|a, b| self.compare_attrs(&a.0, &b.0));

            // Rebuild attributes map in sorted order
            let mut sorted_attributes = IndexMap::new();
            for (name, value) in attrs {
                sorted_attributes.insert(name.into(), value.into());
            }
            element.attributes = sorted_attributes;
        }

        // Process child elements recursively
        for child in &mut element.children {
            if let Node::Element(elem) = child {
                self.sort_attrs_recursive(elem);
            }
        }
    }
}

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

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

    fn description(&self) -> &'static str {
        "Sort element attributes for better compression"
    }

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

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

    fn apply(&self, document: &mut Document) -> Result<()> {
        self.sort_attrs_recursive(&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, Node};

    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 = SortAttrsPlugin::new();
        assert_eq!(plugin.name(), "sortAttrs");
        assert_eq!(
            plugin.description(),
            "Sort element attributes for better compression"
        );
    }

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

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

        // Valid parameters (with order)
        assert!(plugin
            .validate_params(&json!({
                "order": ["id", "width", "height"],
                "xmlnsOrder": "front"
            }))
            .is_ok());

        // Invalid parameter type
        assert!(plugin
            .validate_params(&json!({
                "order": "invalid"
            }))
            .is_err());
    }

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

        // Create element with attributes in random order
        let mut rect = create_element("rect");
        rect.attributes.insert("height".into(), "100".into());
        rect.attributes.insert("id".into(), "test".into());
        rect.attributes.insert("width".into(), "200".into());
        rect.attributes.insert("x".into(), "10".into());
        doc.root.children.push(Node::Element(rect));

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

        // Check that attributes are sorted according to default order
        if let Node::Element(elem) = &doc.root.children[0] {
            let attr_names: Vec<&str> = elem.attributes.keys().map(|k| k.as_ref()).collect();
            // id should come first, then width, height, x
            assert_eq!(attr_names.len(), 4);
            // Note: HashMap iteration order is not guaranteed, but we can check the comparison logic
        }
    }

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

        // Create element with xmlns attributes
        let mut svg = create_element("svg");
        svg.attributes.insert("width".into(), "100".into());
        svg.attributes
            .insert("xmlns:xlink".into(), "http://www.w3.org/1999/xlink".into());
        svg.attributes
            .insert("xmlns".into(), "http://www.w3.org/2000/svg".into());
        svg.attributes.insert("id".into(), "test".into());
        doc.root.children.push(Node::Element(svg));

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

        // Check that xmlns attributes are sorted to front
        if let Node::Element(elem) = &doc.root.children[0] {
            assert_eq!(elem.attributes.len(), 4);
            let attr_names: Vec<&str> = elem.attributes.keys().map(|k| k.as_ref()).collect();
            // xmlns should come first, then xmlns:xlink, then id, then width
            assert_eq!(attr_names[0], "xmlns");
            assert_eq!(attr_names[1], "xmlns:xlink");
            // The rest should be by order: id, width
            assert_eq!(attr_names[2], "id");
            assert_eq!(attr_names[3], "width");
        }
    }

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

        // Create element with attributes not in default order
        let mut rect = create_element("rect");
        rect.attributes.insert("z-index".into(), "1".into());
        rect.attributes.insert("data-custom".into(), "value".into());
        rect.attributes.insert("aria-label".into(), "button".into());
        doc.root.children.push(Node::Element(rect));

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

        // Check that attributes are sorted alphabetically
        if let Node::Element(elem) = &doc.root.children[0] {
            assert_eq!(elem.attributes.len(), 3);
            // Should be sorted alphabetically: aria-label, data-custom, z-index
        }
    }

    #[test]
    fn test_custom_order_config() {
        let config = SortAttrsConfig {
            order: vec!["width".to_string(), "height".to_string(), "id".to_string()],
            xmlns_order: "front".to_string(),
        };
        let plugin = SortAttrsPlugin::with_config(config);
        let mut doc = Document::new();

        // Create element with attributes
        let mut rect = create_element("rect");
        rect.attributes.insert("id".into(), "test".into());
        rect.attributes.insert("height".into(), "100".into());
        rect.attributes.insert("width".into(), "200".into());
        doc.root.children.push(Node::Element(rect));

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

        // Check that attributes are sorted according to custom order
        if let Node::Element(elem) = &doc.root.children[0] {
            assert_eq!(elem.attributes.len(), 3);
            // Should be sorted according to custom order: width, height, id
        }
    }

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

        // Create element with hyphenated attributes
        let mut rect = create_element("rect");
        rect.attributes.insert("fill-opacity".into(), "0.5".into());
        rect.attributes.insert("fill".into(), "red".into());
        rect.attributes.insert("stroke-width".into(), "2".into());
        rect.attributes.insert("stroke".into(), "blue".into());
        doc.root.children.push(Node::Element(rect));

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

        // Check that hyphenated attributes are grouped with their base
        if let Node::Element(elem) = &doc.root.children[0] {
            assert_eq!(elem.attributes.len(), 4);
            // fill and stroke are in default order, so they should be grouped together
        }
    }

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

        // Create nested elements with attributes
        let mut group = create_element("g");
        group
            .attributes
            .insert("transform".into(), "translate(10,20)".into());
        group.attributes.insert("id".into(), "group1".into());

        let mut rect = create_element("rect");
        rect.attributes.insert("height".into(), "100".into());
        rect.attributes.insert("width".into(), "200".into());
        rect.attributes.insert("x".into(), "10".into());

        group.children.push(Node::Element(rect));
        doc.root.children.push(Node::Element(group));

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

        // Check that both elements have sorted attributes
        if let Node::Element(group_elem) = &doc.root.children[0] {
            assert_eq!(group_elem.attributes.len(), 2);

            if let Node::Element(rect_elem) = &group_elem.children[0] {
                assert_eq!(rect_elem.attributes.len(), 3);
            }
        }
    }

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

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

        // Apply plugin - should not crash
        let result = plugin.apply(&mut doc);
        assert!(result.is_ok());

        // Element should still exist with no attributes
        if let Node::Element(elem) = &doc.root.children[0] {
            assert_eq!(elem.attributes.len(), 0);
        }
    }

    #[test]
    fn test_config_parsing() {
        let config = SortAttrsPlugin::parse_config(&json!({
            "order": ["id", "class", "width", "height"],
            "xmlnsOrder": "alphabetical"
        }))
        .unwrap();

        assert_eq!(config.order, vec!["id", "class", "width", "height"]);
        assert_eq!(config.xmlns_order, "alphabetical");
    }
}

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