vexy-vsvg-plugin-sdk 2.3.1

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

//! CSS selector matching for Vexy Vsvg's AST.
//!
//! This module bridges the `selectors` crate (Servo's CSS engine) with Vexy Vsvg's AST,
//! enabling plugins to query elements using CSS selectors like `path[fill="none"]` or
//! `g > rect`. Critical for plugins like `inlineStyles` and `removeAttributesBySelector`.
//!
//! # Architecture
//!
//! The `selectors` crate requires implementing `SelectorImpl` and `Element` traits on your
//! AST. Since Vexy Vsvg's `Element` lives in a different crate, we use wrapper types to
//! satisfy Rust's orphan rule.
//!
//! **Key types:**
//! - `SvgSelectorImpl` - Defines associated types for selector matching
//! - `SvgElement<'a>` - Wraps `Element<'a>` to implement `selectors::Element`
//! - `Svg*` newtypes - Wrap `String` to implement `ToCss`, `PrecomputedHash`, etc.
//!
//! # Usage
//!
//! ```no_run
//! use vexy_vsvg::ast::Element;
//! use vexy_vsvg_plugin_sdk::selector::{matches_selector, SvgSelectorImpl};
//! use selectors::parser::Selector;
//! # let element: &Element = todo!();
//! # let selector: Selector<SvgSelectorImpl> = todo!();
//!
//! if matches_selector(element, &selector) {
//!     // Element matches selector
//! }
//! ```

use selectors::attr::{AttrSelectorOperation, CaseSensitivity, NamespaceConstraint};
use selectors::parser::{Selector, SelectorImpl};
use selectors::{Element as SelectorElement, OpaqueElement};
use std::borrow::Borrow;
use std::fmt;
use vexy_vsvg::ast::{Element, Node};

// Import PrecomputedHash trait - required for SelectorImpl associated types
use precomputed_hash::PrecomputedHash;

/// Wrapper types for `String` that implement traits required by the `selectors` crate.
///
/// The `selectors` crate requires associated types to implement `ToCss`, `PrecomputedHash`,
/// `From<&str>`, and other traits. Since we can't implement external traits on `String`
/// (orphan rule E0117), we wrap it in newtypes.
/// Attribute value (e.g., `"red"` in `fill="red"`).
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct SvgAttrValue(pub String);

/// Identifier (e.g., `"my-id"` in `#my-id` or `.my-class`).
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct SvgIdentifier(pub String);

/// Local element name (e.g., `"path"`, `"rect"`).
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct SvgLocalName(pub String);

/// Namespace prefix (e.g., `"xlink"` in `xlink:href`).
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
pub struct SvgNamespacePrefix(pub String);

/// Namespace URL (e.g., `"http://www.w3.org/2000/svg"`).
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
pub struct SvgNamespaceUrl(pub String);

// Implement required traits for our wrapper types
impl cssparser::ToCss for SvgAttrValue {
    fn to_css<W>(&self, dest: &mut W) -> fmt::Result
    where
        W: fmt::Write,
    {
        dest.write_str(&self.0)
    }
}

impl PrecomputedHash for SvgAttrValue {
    fn precomputed_hash(&self) -> u32 {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};
        let mut hasher = DefaultHasher::new();
        self.0.hash(&mut hasher);
        hasher.finish() as u32
    }
}

impl cssparser::ToCss for SvgIdentifier {
    fn to_css<W>(&self, dest: &mut W) -> fmt::Result
    where
        W: fmt::Write,
    {
        dest.write_str(&self.0)
    }
}

impl PrecomputedHash for SvgIdentifier {
    fn precomputed_hash(&self) -> u32 {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};
        let mut hasher = DefaultHasher::new();
        self.0.hash(&mut hasher);
        hasher.finish() as u32
    }
}

impl cssparser::ToCss for SvgLocalName {
    fn to_css<W>(&self, dest: &mut W) -> fmt::Result
    where
        W: fmt::Write,
    {
        dest.write_str(&self.0)
    }
}

impl PrecomputedHash for SvgLocalName {
    fn precomputed_hash(&self) -> u32 {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};
        let mut hasher = DefaultHasher::new();
        self.0.hash(&mut hasher);
        hasher.finish() as u32
    }
}

impl cssparser::ToCss for SvgNamespacePrefix {
    fn to_css<W>(&self, dest: &mut W) -> fmt::Result
    where
        W: fmt::Write,
    {
        dest.write_str(&self.0)
    }
}

impl PrecomputedHash for SvgNamespacePrefix {
    fn precomputed_hash(&self) -> u32 {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};
        let mut hasher = DefaultHasher::new();
        self.0.hash(&mut hasher);
        hasher.finish() as u32
    }
}

impl cssparser::ToCss for SvgNamespaceUrl {
    fn to_css<W>(&self, dest: &mut W) -> fmt::Result
    where
        W: fmt::Write,
    {
        dest.write_str(&self.0)
    }
}

impl PrecomputedHash for SvgNamespaceUrl {
    fn precomputed_hash(&self) -> u32 {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};
        let mut hasher = DefaultHasher::new();
        self.0.hash(&mut hasher);
        hasher.finish() as u32
    }
}

// Implement Borrow<str> for types that need it
impl Borrow<str> for SvgLocalName {
    fn borrow(&self) -> &str {
        &self.0
    }
}

impl Borrow<str> for SvgNamespaceUrl {
    fn borrow(&self) -> &str {
        &self.0
    }
}

// Implement From<&str> for our wrapper types as required by selectors crate
impl<'a> From<&'a str> for SvgAttrValue {
    fn from(s: &'a str) -> Self {
        SvgAttrValue(s.to_string())
    }
}

impl<'a> From<&'a str> for SvgIdentifier {
    fn from(s: &'a str) -> Self {
        SvgIdentifier(s.to_string())
    }
}

impl<'a> From<&'a str> for SvgLocalName {
    fn from(s: &'a str) -> Self {
        SvgLocalName(s.to_string())
    }
}

impl<'a> From<&'a str> for SvgNamespacePrefix {
    fn from(s: &'a str) -> Self {
        SvgNamespacePrefix(s.to_string())
    }
}

impl<'a> From<&'a str> for SvgNamespaceUrl {
    fn from(s: &'a str) -> Self {
        SvgNamespaceUrl(s.to_string())
    }
}

/// Selector implementation that defines associated types for SVG matching.
///
/// This zero-sized type configures the `selectors` crate's generic machinery for SVG.
/// Each associated type corresponds to a CSS concept (attribute values, identifiers, etc.)
/// and uses our wrapper newtypes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SvgSelectorImpl;

impl SelectorImpl for SvgSelectorImpl {
    type ExtraMatchingData<'a> = ();
    type AttrValue = SvgAttrValue;
    type Identifier = SvgIdentifier;
    type LocalName = SvgLocalName;
    type NamespacePrefix = SvgNamespacePrefix;
    type NamespaceUrl = SvgNamespaceUrl;
    type BorrowedNamespaceUrl = str;
    type BorrowedLocalName = str;

    type NonTSPseudoClass = NonTSPseudoClass;
    type PseudoElement = PseudoElement;
}

/// Non-tree-structural pseudo-class (e.g., `:hover`, `:active`).
///
/// Vexy Vsvg doesn't support pseudo-classes (SVG is static), so this is an uninhabited
/// enum. Required by `selectors` crate's trait bounds.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum NonTSPseudoClass {}

impl fmt::Display for NonTSPseudoClass {
    fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result {
        match *self {}
    }
}

impl cssparser::ToCss for NonTSPseudoClass {
    fn to_css<W>(&self, _dest: &mut W) -> fmt::Result
    where
        W: fmt::Write,
    {
        match *self {}
    }
}

impl selectors::parser::NonTSPseudoClass for NonTSPseudoClass {
    type Impl = SvgSelectorImpl;

    fn is_active_or_hover(&self) -> bool {
        match *self {}
    }

    fn is_user_action_state(&self) -> bool {
        match *self {}
    }
}

/// Pseudo-element (e.g., `::before`, `::after`).
///
/// Not applicable to SVG. Uninhabited enum required by `selectors` crate.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PseudoElement {}

impl fmt::Display for PseudoElement {
    fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result {
        match *self {}
    }
}

impl cssparser::ToCss for PseudoElement {
    fn to_css<W>(&self, _dest: &mut W) -> fmt::Result
    where
        W: fmt::Write,
    {
        match *self {}
    }
}

impl selectors::parser::PseudoElement for PseudoElement {
    type Impl = SvgSelectorImpl;
}

/// Wrapper around Vexy Vsvg's `Element` that implements `selectors::Element`.
///
/// This adapter allows the `selectors` crate to traverse and query Vexy Vsvg's AST.
/// It implements methods like `has_id`, `has_class`, `attr_matches`, and tree traversal.
///
/// # Limitations
///
/// - `parent_element()`, `prev_sibling_element()`, `next_sibling_element()` return `None`
///   because the AST doesn't store parent/sibling pointers. Tree traversal is handled
///   externally via `walk_element_tree_with_parent`.
/// - Shadow DOM methods return `false`/`None` (not applicable to SVG).
#[derive(Debug)]
pub struct SvgElement<'a> {
    pub element: &'a Element<'a>,
}

/// Type alias for compatibility with other modules.
pub type SvgElementWrapper<'a> = SvgElement<'a>;

impl<'a> SvgElement<'a> {
    /// Creates a new wrapper around an SVG element.
    pub fn new(element: &'a Element<'a>) -> Self {
        SvgElement { element }
    }
}

impl<'a> Clone for SvgElement<'a> {
    fn clone(&self) -> Self {
        SvgElement {
            element: self.element,
        }
    }
}

impl<'a> SelectorElement for SvgElement<'a> {
    type Impl = SvgSelectorImpl;

    fn opaque(&self) -> OpaqueElement {
        OpaqueElement::new(self.element)
    }

    fn apply_selector_flags(&self, _flags: selectors::matching::ElementSelectorFlags) {
        // No-op for SVG elements - we don't need to track selector flags
    }

    fn parent_element(&self) -> Option<Self> {
        None // Simplified implementation for now
    }

    fn parent_node_is_shadow_root(&self) -> bool {
        false
    }

    fn containing_shadow_host(&self) -> Option<Self> {
        None
    }

    fn is_pseudo_element(&self) -> bool {
        false
    }

    fn prev_sibling_element(&self) -> Option<Self> {
        None // Simplified implementation for now
    }

    fn next_sibling_element(&self) -> Option<Self> {
        None // Simplified implementation for now
    }

    fn first_element_child(&self) -> Option<Self> {
        self.element.children.iter().find_map(|child| {
            if let Node::Element(element) = child {
                Some(SvgElement::new(element))
            } else {
                None
            }
        })
    }

    fn is_html_element_in_html_document(&self) -> bool {
        false
    }

    fn has_local_name(&self, local_name: &str) -> bool {
        self.element.name == local_name
    }

    fn has_namespace(&self, _namespace: &str) -> bool {
        true // SVG elements are in the SVG namespace
    }

    fn is_same_type(&self, other: &Self) -> bool {
        self.element.name == other.element.name
    }

    fn attr_matches(
        &self,
        ns: &NamespaceConstraint<&SvgNamespaceUrl>,
        local_name: &SvgLocalName,
        operation: &AttrSelectorOperation<&SvgAttrValue>,
    ) -> bool {
        // Only match attributes without namespace for now
        if !matches!(ns, NamespaceConstraint::Specific(ns_val) if ns_val.0.is_empty())
            && !matches!(ns, NamespaceConstraint::Any)
        {
            return false;
        }

        if let Some(attr_value) = self.element.attr(&local_name.0) {
            match operation {
                AttrSelectorOperation::Exists => true,
                AttrSelectorOperation::WithValue {
                    operator,
                    case_sensitivity,
                    value,
                } => {
                    let case_insensitive =
                        matches!(case_sensitivity, CaseSensitivity::AsciiCaseInsensitive);

                    match operator {
                        selectors::attr::AttrSelectorOperator::Equal => {
                            if case_insensitive {
                                attr_value.to_lowercase() == value.0.to_lowercase()
                            } else {
                                attr_value == value.0
                            }
                        }
                        selectors::attr::AttrSelectorOperator::Includes => {
                            let values: Vec<&str> = attr_value.split_whitespace().collect();
                            if case_insensitive {
                                values
                                    .iter()
                                    .any(|v| v.to_lowercase() == value.0.to_lowercase())
                            } else {
                                values.contains(&value.0.as_str())
                            }
                        }
                        selectors::attr::AttrSelectorOperator::DashMatch => {
                            if case_insensitive {
                                let attr_lower = attr_value.to_lowercase();
                                let expected_lower = value.0.to_lowercase();
                                attr_lower == expected_lower
                                    || attr_lower.starts_with(&format!("{}-", expected_lower))
                            } else {
                                attr_value == value.0
                                    || attr_value.starts_with(&format!("{}-", value.0))
                            }
                        }
                        selectors::attr::AttrSelectorOperator::Prefix => {
                            if case_insensitive {
                                attr_value
                                    .to_lowercase()
                                    .starts_with(&value.0.to_lowercase())
                            } else {
                                attr_value.starts_with(&value.0)
                            }
                        }
                        selectors::attr::AttrSelectorOperator::Suffix => {
                            if case_insensitive {
                                attr_value.to_lowercase().ends_with(&value.0.to_lowercase())
                            } else {
                                attr_value.ends_with(&value.0)
                            }
                        }
                        selectors::attr::AttrSelectorOperator::Substring => {
                            if case_insensitive {
                                attr_value.to_lowercase().contains(&value.0.to_lowercase())
                            } else {
                                attr_value.contains(&value.0)
                            }
                        }
                    }
                }
            }
        } else {
            false
        }
    }

    fn match_non_ts_pseudo_class(
        &self,
        _pc: &NonTSPseudoClass,
        _context: &mut selectors::matching::MatchingContext<SvgSelectorImpl>,
    ) -> bool {
        match *_pc {}
    }

    fn match_pseudo_element(
        &self,
        _pe: &PseudoElement,
        _context: &mut selectors::matching::MatchingContext<SvgSelectorImpl>,
    ) -> bool {
        match *_pe {}
    }

    fn is_link(&self) -> bool {
        false
    }

    fn is_html_slot_element(&self) -> bool {
        false
    }

    fn has_id(&self, id: &SvgIdentifier, _case_sensitivity: CaseSensitivity) -> bool {
        self.element.attr("id") == Some(id.0.as_str())
    }

    fn has_class(&self, name: &SvgIdentifier, _case_sensitivity: CaseSensitivity) -> bool {
        if let Some(class_attr) = self.element.attr("class") {
            class_attr.split_whitespace().any(|c| c == name.0)
        } else {
            false
        }
    }

    fn imported_part(&self, _name: &SvgIdentifier) -> Option<SvgIdentifier> {
        None
    }

    fn is_part(&self, _name: &SvgIdentifier) -> bool {
        false
    }

    fn has_custom_state(&self, _name: &SvgIdentifier) -> bool {
        false
    }

    fn add_element_unique_hashes(
        &self,
        _filter: &mut selectors::bloom::CountingBloomFilter<selectors::bloom::BloomStorageU8>,
    ) -> bool {
        true
    }

    fn is_empty(&self) -> bool {
        self.element.children.is_empty()
    }

    fn is_root(&self) -> bool {
        self.element.name == "svg"
    }
}

/// Recursively traverses the SVG element tree, calling a visitor for each element.
///
/// # Arguments
///
/// * `element` - Current element to visit
/// * `parent` - Parent element (if any)
/// * `visitor` - Closure called for each `(element, parent)` pair
///
/// # Implementation
///
/// Uses dynamic dispatch (`dyn FnMut`) instead of generics to avoid hitting Rust's
/// recursion limit during monomorphization. This function is recursive, and generic
/// closures would create exponentially complex types.
///
/// # Example
///
/// ```no_run
/// # use vexy_vsvg::ast::Element;
/// # use vexy_vsvg_plugin_sdk::selector::walk_element_tree_with_parent;
/// # let root: &Element = todo!();
/// walk_element_tree_with_parent(root, None, &mut |elem, parent| {
///     println!("Element: {}, Parent: {:?}", elem.name, parent.map(|p| p.name.as_ref()));
/// });
/// ```
pub fn walk_element_tree_with_parent<'a>(
    element: &Element<'a>,
    parent: Option<&Element<'a>>,
    visitor: &mut dyn FnMut(&Element<'a>, Option<&Element<'a>>),
) {
    visitor(element, parent);

    for child in &element.children {
        if let Node::Element(child_element) = child {
            walk_element_tree_with_parent(child_element, Some(element), visitor);
        }
    }
}

/// Tests whether a CSS selector matches an SVG element.
///
/// This is the primary entry point for selector matching in plugins. It wraps the
/// `selectors` crate's matching logic with Vexy Vsvg-specific setup.
///
/// # Arguments
///
/// * `element` - Element to test
/// * `selector` - Parsed CSS selector (use `cssparser` and `selectors::parser` to create)
///
/// # Returns
///
/// `true` if the selector matches, `false` otherwise.
///
/// # Example
///
/// ```no_run
/// use vexy_vsvg::ast::Element;
/// use vexy_vsvg_plugin_sdk::selector::matches_selector;
/// use selectors::parser::Selector;
/// # let element: &Element = todo!();
/// # let selector: Selector<vexy_vsvg_plugin_sdk::selector::SvgSelectorImpl> = todo!();
///
/// if matches_selector(element, &selector) {
///     // Element matches the selector
/// }
/// ```
pub fn matches_selector(element: &Element<'_>, selector: &Selector<SvgSelectorImpl>) -> bool {
    use selectors::matching::SelectorCaches;
    use selectors::matching::{
        MatchingForInvalidation, MatchingMode, NeedsSelectorFlags, QuirksMode,
    };

    let svg_element = SvgElement::new(element);
    let mut selector_caches = SelectorCaches::default();
    let mut context = selectors::matching::MatchingContext::new(
        MatchingMode::Normal,
        None,
        &mut selector_caches,
        QuirksMode::NoQuirks,
        NeedsSelectorFlags::No,
        MatchingForInvalidation::No,
    );

    selectors::matching::matches_selector(selector, 0, None, &svg_element, &mut context)
}