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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
// this_file: crates/vexy-vsvg-plugin-sdk/src/plugins/prefix_ids.rs

//! Adds namespacing prefixes to IDs and class names to prevent collisions.
//!
//! When embedding multiple SVGs in one page, ID conflicts break references. This plugin
//! prefixes all IDs and class names with a unique string, then updates all references
//! to match (href, url(), animation timing, CSS selectors).
//!
//! **What it does:**
//! - Adds prefix to all `id` attributes (e.g., `myGradient` → `file__myGradient`)
//! - Optionally prefixes class names
//! - Updates all references: `href="#id"`, `fill="url(#id)"`, CSS selectors, animations
//! - Processes inline `<style>` blocks to rewrite selectors
//!
//! **Configuration:**
//! - `prefix`: Custom prefix string (default: derived from filename)
//! - `delim`: Delimiter between prefix and name (default: `__`)
//! - `prefixIds`: Enable ID prefixing (default: `true`)
//! - `prefixClassNames`: Enable class prefixing (default: `true`)
//!
//! **Example:**
//! ```xml
//! <!-- Before (myfile.svg) -->
//! <svg>
//!   <defs>
//!     <linearGradient id="grad">...</linearGradient>
//!   </defs>
//!   <rect fill="url(#grad)"/>
//! </svg>
//!
//! <!-- After (with auto-generated prefix from filename) -->
//! <svg>
//!   <defs>
//!     <linearGradient id="myfile_svg__grad">...</linearGradient>
//!   </defs>
//!   <rect fill="url(#myfile_svg__grad)"/>
//! </svg>
//! ```
//!
//! **Why it's useful:** Prevents ID collisions when embedding multiple SVGs as inline
//! `<svg>` elements in HTML. Each file gets unique IDs while maintaining internal references.
//!
//! Reference: SVGO's prefixIds plugin

use anyhow::Result;
use once_cell::sync::Lazy;
use regex::Regex;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use vexy_vsvg::ast::{Document, Element, Node};
use vexy_vsvg::collections::REFERENCES_PROPS;

use crate::Plugin;

static BASENAME_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"[/\\]?([^/\\]+)$").unwrap());
static URL_DOUBLE_QUOTE_RE: Lazy<Regex> =
    Lazy::new(|| Regex::new(r#"\burl\("(#[^"]+)"\)"#).unwrap());
static URL_SINGLE_QUOTE_RE: Lazy<Regex> =
    Lazy::new(|| Regex::new(r#"\burl\('(#[^']+)'\)"#).unwrap());
static URL_NO_QUOTE_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r#"\burl\((#[^)]+)\)"#).unwrap());
static CSS_ID_SELECTOR_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"#([a-zA-Z][\w-]*)").unwrap());
static CSS_CLASS_SELECTOR_RE: Lazy<Regex> =
    Lazy::new(|| Regex::new(r"\.([a-zA-Z][\w-]*)").unwrap());

/// Configuration for the prefix IDs plugin.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct PrefixIdsConfig {
    /// The prefix to use. If `None`, auto-generates from filename (e.g., "myfile_svg").
    #[serde(skip_serializing_if = "Option::is_none")]
    pub prefix: Option<String>,
    /// Delimiter between prefix and original ID (default: `__`).
    #[serde(default = "default_delim")]
    pub delim: String,
    /// Whether to prefix IDs (default: `true`).
    #[serde(default = "default_true")]
    pub prefix_ids: bool,
    /// Whether to prefix class names (default: `true`).
    #[serde(default = "default_true")]
    pub prefix_class_names: bool,
}

fn default_delim() -> String {
    "__".to_string()
}

fn default_true() -> bool {
    true
}

impl Default for PrefixIdsConfig {
    fn default() -> Self {
        Self {
            prefix: None,
            delim: default_delim(),
            prefix_ids: default_true(),
            prefix_class_names: default_true(),
        }
    }
}

/// Prefix IDs plugin.
///
/// Namespaces all IDs and class names with a prefix, updating all references throughout
/// the document to maintain working links.
pub struct PrefixIdsPlugin {
    config: PrefixIdsConfig,
}

impl PrefixIdsPlugin {
    pub fn new() -> Self {
        Self {
            config: PrefixIdsConfig::default(),
        }
    }

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

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

    /// Extract filename from path (handles both Unix and Windows paths).
    ///
    /// Returns the last path component after `/` or `\`.
    fn get_basename(path: &str) -> String {
        if let Some(captures) = BASENAME_RE.captures(path) {
            if let Some(matched) = captures.get(1) {
                return matched.as_str().to_string();
            }
        }
        String::new()
    }

    /// Make a string safe for use as CSS/JS identifier.
    ///
    /// Replaces dots and spaces with underscores (e.g., "my file.svg" → "my_file_svg").
    fn escape_identifier_name(s: &str) -> String {
        s.replace(['.', ' '], "_")
    }

    /// Generate the prefix string based on config and document metadata.
    ///
    /// Priority:
    /// 1. Explicit `prefix` from config
    /// 2. Auto-generate from filename (if document has path metadata)
    /// 3. Default fallback: "prefix"
    fn generate_prefix(&self, document: &Document) -> String {
        if let Some(prefix) = &self.config.prefix {
            return format!("{}{}", prefix, self.config.delim);
        }

        if let Some(path) = &document.metadata.path {
            let basename = Self::get_basename(path);
            if !basename.is_empty() {
                return format!(
                    "{}{}",
                    Self::escape_identifier_name(&basename),
                    self.config.delim
                );
            }
        }

        format!("prefix{}", self.config.delim)
    }

    /// Add prefix to an ID if it doesn't already have it.
    ///
    /// Idempotent: won't double-prefix if ID already starts with the prefix.
    fn prefix_id(&self, prefix: &str, id: &str) -> String {
        if id.starts_with(prefix) {
            id.to_string()
        } else {
            format!("{}{}", prefix, id)
        }
    }

    /// Prefix a URL reference (e.g., "#myId" → "#prefix__myId").
    ///
    /// Returns `None` if the reference doesn't start with `#` (not a local reference).
    fn prefix_reference(&self, prefix: &str, reference: &str) -> Option<String> {
        reference
            .strip_prefix('#')
            .map(|id| format!("#{}", self.prefix_id(prefix, id)))
    }

    /// Process an element and its children recursively.
    ///
    /// Prefixes IDs, class names, href attributes, url() references in presentation
    /// attributes, animation timing references, and CSS selectors in style blocks.
    fn process_element(&self, element: &mut Element, prefix: &str) {
        // Prefix ID attribute
        if self.config.prefix_ids {
            if let Some(id) = element.attr("id") {
                if !id.is_empty() {
                    element.set_attr("id", self.prefix_id(prefix, id));
                }
            }
        }

        // Prefix class attribute
        if self.config.prefix_class_names {
            if let Some(class) = element.attr("class") {
                if !class.is_empty() {
                    let classes: Vec<String> = class
                        .split_whitespace()
                        .map(|name| self.prefix_id(prefix, name))
                        .collect();
                    element.set_attr("class", classes.join(" "));
                }
            }
        }

        // Prefix href and xlink:href attributes
        for attr_name in ["href", "xlink:href"] {
            if let Some(href) = element.attr(attr_name) {
                if !href.is_empty() {
                    if let Some(prefixed) = self.prefix_reference(prefix, href) {
                        element.set_attr(attr_name, prefixed);
                    }
                }
            }
        }

        // Prefix URL references in specific attributes
        for attr_name in REFERENCES_PROPS.iter() {
            if let Some(attr_value) = element.attr(attr_name) {
                if !attr_value.is_empty() {
                    let processed = self.process_url_references(attr_value, prefix);
                    element.set_attr(*attr_name, processed);
                }
            }
        }

        // Prefix begin/end attributes (for animation)
        for attr_name in ["begin", "end"] {
            if let Some(attr_value) = element.attr(attr_name) {
                if !attr_value.is_empty() {
                    let processed = self.process_animation_references(attr_value, prefix);
                    element.set_attr(attr_name, processed);
                }
            }
        }

        // Process style elements
        if element.name == "style" {
            let mut new_children = Vec::new();
            for child in &element.children {
                match child {
                    Node::Text(text) => {
                        let processed = self.process_style_content(text, prefix);
                        new_children.push(Node::Text(processed.into()));
                    }
                    _ => new_children.push(child.clone()),
                }
            }
            element.children = new_children;
        }

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

    /// Process url() references in CSS/attribute values.
    ///
    /// Handles three quote styles: `url("#id")`, `url('#id')`, `url(#id)`.
    /// Only prefixes local references (starting with `#`), leaves external URLs unchanged.
    fn process_url_references(&self, value: &str, prefix: &str) -> String {
        let mut result = value.to_string();

        // Process double-quoted URLs
        result = URL_DOUBLE_QUOTE_RE
            .replace_all(&result, |caps: &regex::Captures| {
                let url = caps.get(1).unwrap().as_str();
                if let Some(prefixed) = self.prefix_reference(prefix, url) {
                    format!(r#"url("{}")"#, prefixed)
                } else {
                    caps.get(0).unwrap().as_str().to_string()
                }
            })
            .to_string();

        // Process single-quoted URLs
        result = URL_SINGLE_QUOTE_RE
            .replace_all(&result, |caps: &regex::Captures| {
                let url = caps.get(1).unwrap().as_str();
                if let Some(prefixed) = self.prefix_reference(prefix, url) {
                    format!(r#"url('{}')"#, prefixed)
                } else {
                    caps.get(0).unwrap().as_str().to_string()
                }
            })
            .to_string();

        // Process unquoted URLs
        result = URL_NO_QUOTE_RE
            .replace_all(&result, |caps: &regex::Captures| {
                let url = caps.get(1).unwrap().as_str();
                if let Some(prefixed) = self.prefix_reference(prefix, url) {
                    format!("url({})", prefixed)
                } else {
                    caps.get(0).unwrap().as_str().to_string()
                }
            })
            .to_string();

        result
    }

    /// Process animation timing references (e.g., `begin="elem1.end; elem2.start"`).
    ///
    /// SVG animation elements can reference other elements by ID for timing.
    /// Prefixes the element IDs while preserving the event names (.end, .start).
    fn process_animation_references(&self, value: &str, prefix: &str) -> String {
        let parts: Vec<String> = value
            .split(';')
            .map(|part| {
                let trimmed = part.trim();
                if trimmed.ends_with(".end") || trimmed.ends_with(".start") {
                    let mut split_parts = trimmed.split('.');
                    if let Some(id) = split_parts.next() {
                        let postfix = split_parts.collect::<Vec<_>>().join(".");
                        format!("{}.{}", self.prefix_id(prefix, id), postfix)
                    } else {
                        trimmed.to_string()
                    }
                } else {
                    trimmed.to_string()
                }
            })
            .collect();

        parts.join("; ")
    }

    /// Process CSS content in `<style>` blocks.
    ///
    /// Rewrites ID selectors (`#myId`), class selectors (`.myClass`), and url()
    /// references to use prefixed names. Uses simple regex patterns (not full CSS parser).
    fn process_style_content(&self, content: &str, prefix: &str) -> String {
        let mut result = content.to_string();

        if self.config.prefix_ids {
            result = CSS_ID_SELECTOR_RE
                .replace_all(&result, |caps: &regex::Captures| {
                    let id = caps.get(1).unwrap().as_str();
                    format!("#{}", self.prefix_id(prefix, id))
                })
                .to_string();
        }

        if self.config.prefix_class_names {
            result = CSS_CLASS_SELECTOR_RE
                .replace_all(&result, |caps: &regex::Captures| {
                    let class = caps.get(1).unwrap().as_str();
                    format!(".{}", self.prefix_id(prefix, class))
                })
                .to_string();
        }

        result = self.process_url_references(&result, prefix);

        result
    }
}

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

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

    fn description(&self) -> &'static str {
        "prefix IDs"
    }

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

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

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

    use super::*;

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

    #[test]
    fn test_plugin_info() {
        let plugin = PrefixIdsPlugin::new();
        assert_eq!(plugin.name(), "prefixIds");
        assert_eq!(plugin.description(), "prefix IDs");
    }

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

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

        // Test valid params
        assert!(plugin
            .validate_params(&serde_json::json!({
                "prefix": "custom",
                "delim": "_",
                "prefixIds": false,
                "prefixClassNames": true
            }))
            .is_ok());

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

    #[test]
    fn test_get_basename() {
        assert_eq!(
            PrefixIdsPlugin::get_basename("/path/to/file.svg"),
            "file.svg"
        );
        assert_eq!(
            PrefixIdsPlugin::get_basename("C:\\path\\to\\file.svg"),
            "file.svg"
        );
        assert_eq!(PrefixIdsPlugin::get_basename("file.svg"), "file.svg");
        assert_eq!(PrefixIdsPlugin::get_basename(""), "");
    }

    #[test]
    fn test_escape_identifier_name() {
        assert_eq!(
            PrefixIdsPlugin::escape_identifier_name("my file.svg"),
            "my_file_svg"
        );
        assert_eq!(PrefixIdsPlugin::escape_identifier_name("normal"), "normal");
    }

    #[test]
    fn test_generate_prefix() {
        // Test with custom prefix
        let config = PrefixIdsConfig {
            prefix: Some("custom".to_string()),
            delim: "__".to_string(),
            prefix_ids: true,
            prefix_class_names: true,
        };
        let plugin = PrefixIdsPlugin::with_config(config);
        let doc = create_test_document();
        assert_eq!(plugin.generate_prefix(&doc), "custom__");

        // Test with file path
        let plugin = PrefixIdsPlugin::new();
        let mut doc = create_test_document();
        doc.metadata.path = Some("/path/to/test.svg".to_string());
        assert_eq!(plugin.generate_prefix(&doc), "test_svg__");

        // Test default
        let plugin = PrefixIdsPlugin::new();
        let doc = create_test_document();
        assert_eq!(plugin.generate_prefix(&doc), "prefix__");
    }

    #[test]
    fn test_prefix_id() {
        let plugin = PrefixIdsPlugin::new();

        // Test normal prefixing
        assert_eq!(plugin.prefix_id("test__", "myid"), "test__myid");

        // Test when already prefixed
        assert_eq!(plugin.prefix_id("test__", "test__myid"), "test__myid");
    }

    #[test]
    fn test_prefix_reference() {
        let plugin = PrefixIdsPlugin::new();

        // Test valid reference
        assert_eq!(
            plugin.prefix_reference("test__", "#myid"),
            Some("#test__myid".to_string())
        );

        // Test invalid reference
        assert_eq!(plugin.prefix_reference("test__", "myid"), None);
    }

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

        // Add element with ID
        let mut rect = Element {
            name: "rect".into(),
            attributes: IndexMap::new(),
            namespaces: IndexMap::new(),
            children: vec![],
        };
        rect.set_attr("id", "myId");
        doc.root.children.push(Node::Element(rect));

        let result = plugin.apply(&mut doc);
        assert!(result.is_ok());

        // Check that ID was prefixed
        if let Node::Element(rect) = &doc.root.children[0] {
            assert_eq!(rect.attr("id"), Some("prefix__myId"));
        } else {
            panic!("Expected element");
        }
    }

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

        // Add element with href
        let mut use_elem = Element {
            name: "use".into(),
            attributes: IndexMap::new(),
            namespaces: IndexMap::new(),
            children: vec![],
        };
        use_elem.set_attr("href", "#myTarget");
        doc.root.children.push(Node::Element(use_elem));

        let result = plugin.apply(&mut doc);
        assert!(result.is_ok());

        // Check that href was prefixed
        if let Node::Element(use_elem) = &doc.root.children[0] {
            assert_eq!(use_elem.attr("href"), Some("#prefix__myTarget"));
        } else {
            panic!("Expected element");
        }
    }

    #[test]
    fn test_apply_with_custom_config() {
        let config = PrefixIdsConfig {
            prefix: Some("custom".to_string()),
            delim: "_".to_string(),
            prefix_ids: true,
            prefix_class_names: true,
        };
        let plugin = PrefixIdsPlugin::with_config(config);
        let mut doc = create_test_document();

        // Add element with ID
        let mut rect = Element {
            name: "rect".into(),
            attributes: IndexMap::new(),
            namespaces: IndexMap::new(),
            children: vec![],
        };
        rect.set_attr("id", "myId");
        doc.root.children.push(Node::Element(rect));

        let result = plugin.apply(&mut doc);
        assert!(result.is_ok());

        // Check that ID was prefixed with custom config
        if let Node::Element(rect) = &doc.root.children[0] {
            assert_eq!(rect.attr("id"), Some("custom_myId"));
        } else {
            panic!("Expected element");
        }
    }

    #[test]
    fn test_process_url_references() {
        let plugin = PrefixIdsPlugin::new();

        // Test double-quoted URL
        assert_eq!(
            plugin.process_url_references("url(\"#icon\")", "pre_"),
            "url(\"#pre_icon\")"
        );

        // Test single-quoted URL
        assert_eq!(
            plugin.process_url_references(r#"url('#icon')"#, "pre_"),
            r#"url('#pre_icon')"#
        );

        // Test unquoted URL
        assert_eq!(
            plugin.process_url_references("url(#icon)", "pre_"),
            "url(#pre_icon)"
        );

        // Test non-reference URL
        assert_eq!(
            plugin.process_url_references("url(http://example.com)", "pre_"),
            "url(http://example.com)"
        );
    }

    #[test]
    fn test_process_animation_references() {
        let plugin = PrefixIdsPlugin::new();

        assert_eq!(
            plugin.process_animation_references("elem1.end", "pre_"),
            "pre_elem1.end"
        );

        assert_eq!(
            plugin.process_animation_references("elem1.start; elem2.end", "pre_"),
            "pre_elem1.start; pre_elem2.end"
        );

        assert_eq!(plugin.process_animation_references("5s", "pre_"), "5s");
    }

    #[test]
    fn test_process_style_content() {
        let plugin = PrefixIdsPlugin::new();

        let style = "#myId { fill: red; } .myClass { stroke: blue; } rect { fill: url(#grad); }";
        let processed = plugin.process_style_content(style, "pre_");

        assert!(processed.contains("#pre_myId"));
        assert!(processed.contains(".pre_myClass"));
        assert!(processed.contains("url(#pre_grad)"));
    }
}