brik 0.10.0

HTML tree manipulation library - a building block for HTML parsing and manipulation
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
use super::{BrikSelectors, Selector, SelectorContext};
use crate::iter::Select;
use crate::node_data_ref::NodeDataRef;
use crate::tree::ElementData;
use selectors::parser::{Parser, SelectorList};
use std::fmt;

/// Parser for CSS selectors.
struct BrikParser<'a> {
    /// Selector context containing namespace mappings and other configuration.
    context: &'a SelectorContext,
}

impl<'a> BrikParser<'a> {
    /// Create a new parser with the given selector context.
    fn new(context: &'a SelectorContext) -> Self {
        BrikParser { context }
    }
}

/// Implements Parser for BrikParser.
///
/// Provides the selectors crate parser interface for CSS selector parsing
/// with support for pseudo-classes and namespace handling.
impl<'i, 'a> Parser<'i> for BrikParser<'a> {
    type Impl = BrikSelectors;
    type Error = selectors::parser::SelectorParseErrorKind<'i>;

    fn parse_non_ts_pseudo_class(
        &self,
        location: cssparser::SourceLocation,
        name: cssparser::CowRcStr<'i>,
    ) -> Result<
        super::PseudoClass,
        cssparser::ParseError<'i, selectors::parser::SelectorParseErrorKind<'i>>,
    > {
        use super::PseudoClass::*;
        use selectors::parser::SelectorParseErrorKind;
        if name.eq_ignore_ascii_case("any-link") {
            Ok(AnyLink)
        } else if name.eq_ignore_ascii_case("link") {
            Ok(Link)
        } else if name.eq_ignore_ascii_case("visited") {
            Ok(Visited)
        } else if name.eq_ignore_ascii_case("active") {
            Ok(Active)
        } else if name.eq_ignore_ascii_case("focus") {
            Ok(Focus)
        } else if name.eq_ignore_ascii_case("hover") {
            Ok(Hover)
        } else if name.eq_ignore_ascii_case("enabled") {
            Ok(Enabled)
        } else if name.eq_ignore_ascii_case("disabled") {
            Ok(Disabled)
        } else if name.eq_ignore_ascii_case("checked") {
            Ok(Checked)
        } else if name.eq_ignore_ascii_case("indeterminate") {
            Ok(Indeterminate)
        } else {
            Err(
                location.new_custom_error(SelectorParseErrorKind::UnsupportedPseudoClassOrElement(
                    name,
                )),
            )
        }
    }

    fn default_namespace(&self) -> Option<html5ever::Namespace> {
        self.context.default_namespace.clone()
    }

    fn namespace_for_prefix(
        &self,
        prefix: &super::LocalNameSelector,
    ) -> Option<html5ever::Namespace> {
        self.context
            .namespaces
            .get(prefix.as_ref().as_ref())
            .cloned()
    }
}

/// A pre-compiled list of CSS Selectors.
pub struct Selectors(pub Vec<Selector>);

impl Selectors {
    /// Compile a list of selectors. This may fail on syntax errors or unsupported selectors.
    ///
    /// # Errors
    ///
    /// Returns `Err(())` if the selector string contains syntax errors or unsupported selectors.
    #[inline]
    pub fn compile(s: &str) -> Result<Selectors, ()> {
        let context = SelectorContext::default();
        Self::compile_with_context(s, &context)
    }

    /// Compile a list of selectors with a selector context.
    ///
    /// This method allows selectors to use namespace prefixes in both type selectors
    /// (e.g., `svg|rect`) and attribute selectors (e.g., `[tmpl|if]`).
    ///
    /// **Note:** Namespace-aware selector features require the `namespaces` feature to be enabled.
    /// Without the feature, namespace prefixes in selectors will fail to parse or match.
    ///
    /// This is the recommended method when using namespace-aware selectors.
    ///
    /// # Arguments
    ///
    /// * `s` - The selector string to compile
    /// * `context` - A selector context containing namespace mappings
    ///
    /// # Examples
    ///
    /// ```
    /// #[cfg(feature = "namespaces")]
    /// {
    /// use brik::{Selectors, SelectorContext};
    /// use html5ever::ns;
    ///
    /// let mut context = SelectorContext::new();
    /// context.add_namespace("svg".to_string(), ns!(svg));
    ///
    /// // Select SVG rect elements
    /// let selectors = Selectors::compile_with_context("svg|rect", &context).unwrap();
    /// }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns `Err(())` if the selector string contains syntax errors, unsupported selectors,
    /// or references undefined namespace prefixes.
    #[inline]
    pub fn compile_with_context(s: &str, context: &SelectorContext) -> Result<Selectors, ()> {
        let mut input = cssparser::ParserInput::new(s);
        match SelectorList::parse(
            &BrikParser::new(context),
            &mut cssparser::Parser::new(&mut input),
            selectors::parser::ParseRelative::No,
        ) {
            Ok(list) => Ok(Selectors(
                list.slice().iter().cloned().map(Selector).collect(),
            )),
            Err(_) => Err(()),
        }
    }

    /// Returns whether the given element matches this list of selectors.
    #[inline]
    pub fn matches(&self, element: &NodeDataRef<ElementData>) -> bool {
        self.0.iter().any(|s| s.matches(element))
    }

    /// Filter an element iterator, yielding those matching this list of selectors.
    #[inline]
    pub fn filter<I>(&self, iter: I) -> Select<I, &Selectors>
    where
        I: Iterator<Item = NodeDataRef<ElementData>>,
    {
        Select {
            iter,
            selectors: self,
        }
    }
}

/// Implements FromStr for Selectors.
///
/// Enables parsing selector strings using the standard `.parse()` method,
/// providing a convenient alternative to `Selectors::compile()`.
impl ::std::str::FromStr for Selectors {
    type Err = ();
    #[inline]
    fn from_str(s: &str) -> Result<Selectors, ()> {
        Selectors::compile(s)
    }
}

/// Implements Display for Selectors.
///
/// Formats the selector list as a comma-separated CSS selector string,
/// useful for debugging and serialization.
impl fmt::Display for Selectors {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use cssparser::ToCss;
        let mut iter = self.0.iter();
        let first = iter
            .next()
            .expect("Empty Selectors, should contain at least one selector");
        first.0.to_css(f)?;
        for selector in iter {
            f.write_str(", ")?;
            selector.0.to_css(f)?;
        }
        Ok(())
    }
}

/// Implements Debug for Selectors.
///
/// Formats the selector list using the Display implementation for
/// more readable debug output.
impl fmt::Debug for Selectors {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(self, f)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::html5ever::tendril::TendrilSink;
    use crate::iter::NodeIterator;
    use crate::parse_html;

    /// Tests compiling a simple type selector.
    ///
    /// Verifies that a basic element selector compiles successfully.
    #[test]
    fn compile_simple_selector() {
        let selectors = Selectors::compile("div").unwrap();
        assert_eq!(selectors.0.len(), 1);
    }

    /// Tests compiling multiple comma-separated selectors.
    ///
    /// Verifies that a selector list with multiple selectors compiles
    /// to separate selector entries.
    #[test]
    fn compile_multiple_selectors() {
        let selectors = Selectors::compile("div, p, span").unwrap();
        assert_eq!(selectors.0.len(), 3);
    }

    /// Tests compiling a class selector.
    ///
    /// Verifies that class selectors compile correctly.
    #[test]
    fn compile_class_selector() {
        let selectors = Selectors::compile(".myClass").unwrap();
        assert_eq!(selectors.0.len(), 1);
    }

    /// Tests compiling an ID selector.
    ///
    /// Verifies that ID selectors compile correctly.
    #[test]
    fn compile_id_selector() {
        let selectors = Selectors::compile("#myId").unwrap();
        assert_eq!(selectors.0.len(), 1);
    }

    /// Tests compiling :any-link pseudo-class.
    ///
    /// Verifies that the :any-link pseudo-class compiles correctly.
    #[test]
    fn compile_pseudo_class_any_link() {
        let selectors = Selectors::compile("a:any-link").unwrap();
        assert_eq!(selectors.0.len(), 1);
    }

    /// Tests compiling :link pseudo-class.
    ///
    /// Verifies that the :link pseudo-class compiles correctly.
    #[test]
    fn compile_pseudo_class_link() {
        let selectors = Selectors::compile("a:link").unwrap();
        assert_eq!(selectors.0.len(), 1);
    }

    /// Tests compiling :visited pseudo-class.
    ///
    /// Verifies that the :visited pseudo-class compiles correctly.
    #[test]
    fn compile_pseudo_class_visited() {
        let selectors = Selectors::compile("a:visited").unwrap();
        assert_eq!(selectors.0.len(), 1);
    }

    /// Tests compiling :active pseudo-class.
    ///
    /// Verifies that the :active pseudo-class compiles correctly.
    #[test]
    fn compile_pseudo_class_active() {
        let selectors = Selectors::compile("button:active").unwrap();
        assert_eq!(selectors.0.len(), 1);
    }

    /// Tests compiling :focus pseudo-class.
    ///
    /// Verifies that the :focus pseudo-class compiles correctly.
    #[test]
    fn compile_pseudo_class_focus() {
        let selectors = Selectors::compile("input:focus").unwrap();
        assert_eq!(selectors.0.len(), 1);
    }

    /// Tests compiling :hover pseudo-class.
    ///
    /// Verifies that the :hover pseudo-class compiles correctly.
    #[test]
    fn compile_pseudo_class_hover() {
        let selectors = Selectors::compile("div:hover").unwrap();
        assert_eq!(selectors.0.len(), 1);
    }

    /// Tests compiling :enabled pseudo-class.
    ///
    /// Verifies that the :enabled pseudo-class compiles correctly.
    #[test]
    fn compile_pseudo_class_enabled() {
        let selectors = Selectors::compile("input:enabled").unwrap();
        assert_eq!(selectors.0.len(), 1);
    }

    /// Tests compiling :disabled pseudo-class.
    ///
    /// Verifies that the :disabled pseudo-class compiles correctly.
    #[test]
    fn compile_pseudo_class_disabled() {
        let selectors = Selectors::compile("input:disabled").unwrap();
        assert_eq!(selectors.0.len(), 1);
    }

    /// Tests compiling :checked pseudo-class.
    ///
    /// Verifies that the :checked pseudo-class compiles correctly.
    #[test]
    fn compile_pseudo_class_checked() {
        let selectors = Selectors::compile("input:checked").unwrap();
        assert_eq!(selectors.0.len(), 1);
    }

    /// Tests compiling :indeterminate pseudo-class.
    ///
    /// Verifies that the :indeterminate pseudo-class compiles correctly.
    #[test]
    fn compile_pseudo_class_indeterminate() {
        let selectors = Selectors::compile("input:indeterminate").unwrap();
        assert_eq!(selectors.0.len(), 1);
    }

    /// Tests compiling unsupported pseudo-class.
    ///
    /// Verifies that unsupported pseudo-classes fail to compile with
    /// an error.
    #[test]
    fn compile_unsupported_pseudo_class() {
        let result = Selectors::compile(":unsupported");
        assert!(result.is_err());
    }

    /// Tests compiling invalid selector syntax.
    ///
    /// Verifies that malformed selectors fail to compile with an error.
    #[test]
    fn compile_invalid_syntax() {
        let result = Selectors::compile(":::");
        assert!(result.is_err());
    }

    /// Tests matches method when element matches selector.
    ///
    /// Verifies that matches() returns true when the element matches
    /// the compiled selector.
    #[test]
    fn matches_true() {
        let html = r#"<div class="test">content</div>"#;
        let doc = parse_html().one(html);
        let div = doc.select("div").unwrap().next().unwrap();

        let selectors = Selectors::compile(".test").unwrap();
        assert!(selectors.matches(&div));
    }

    /// Tests matches method when element doesn't match selector.
    ///
    /// Verifies that matches() returns false when the element doesn't
    /// match the compiled selector.
    #[test]
    fn matches_false() {
        let html = r#"<div class="test">content</div>"#;
        let doc = parse_html().one(html);
        let div = doc.select("div").unwrap().next().unwrap();

        let selectors = Selectors::compile(".other").unwrap();
        assert!(!selectors.matches(&div));
    }

    /// Tests matches method with multiple selectors.
    ///
    /// Verifies that matches() returns true when the element matches
    /// any selector in a selector list.
    #[test]
    fn matches_multiple_selectors() {
        let html = r#"<div class="test">content</div>"#;
        let doc = parse_html().one(html);
        let div = doc.select("div").unwrap().next().unwrap();

        let selectors = Selectors::compile(".other, .test").unwrap();
        assert!(selectors.matches(&div));
    }

    /// Tests filter method.
    ///
    /// Verifies that filter() correctly filters an element iterator to
    /// include only elements matching the selector.
    #[test]
    fn filter() {
        let html = r#"<div><p class="keep">1</p><span>2</span><p class="keep">3</p></div>"#;
        let doc = parse_html().one(html);
        let div = doc.select("div").unwrap().next().unwrap();

        let selectors = Selectors::compile(".keep").unwrap();
        let filtered: Vec<_> = selectors
            .filter(div.as_node().descendants().elements())
            .collect();

        assert_eq!(filtered.len(), 2);
        assert!(filtered.iter().all(|e| e.name.local.as_ref() == "p"));
    }

    /// Tests FromStr implementation.
    ///
    /// Verifies that selectors can be parsed using the .parse() method.
    #[test]
    fn from_str() {
        let selectors: Selectors = "div.test".parse().unwrap();
        assert_eq!(selectors.0.len(), 1);
    }

    /// Tests FromStr implementation with invalid syntax.
    ///
    /// Verifies that parsing invalid selectors returns an error.
    #[test]
    fn from_str_error() {
        let result: Result<Selectors, ()> = ":::".parse();
        assert!(result.is_err());
    }

    /// Tests Display implementation with single selector.
    ///
    /// Verifies that Display formats a single selector correctly.
    #[test]
    fn display_single() {
        let selectors = Selectors::compile("div").unwrap();
        let display = format!("{selectors}");
        assert_eq!(display, "div");
    }

    /// Tests Display implementation with multiple selectors.
    ///
    /// Verifies that Display formats multiple selectors as a comma-separated
    /// list.
    #[test]
    fn display_multiple() {
        let selectors = Selectors::compile("div, p").unwrap();
        let display = format!("{selectors}");
        assert!(display.contains("div"));
        assert!(display.contains("p"));
        assert!(display.contains(", "));
    }

    /// Tests Debug implementation.
    ///
    /// Verifies that Debug formats selectors using the Display implementation.
    #[test]
    fn debug() {
        let selectors = Selectors::compile("div.test").unwrap();
        let debug = format!("{selectors:?}");
        assert!(debug.contains("div"));
        assert!(debug.contains("test"));
    }

    /// Tests compile_with_context with namespace-qualified selectors.
    ///
    /// Verifies that namespace-qualified selectors compile when the
    /// namespace is defined in the context.
    #[test]
    #[cfg(feature = "namespaces")]
    fn compile_with_context_namespace() {
        let mut context = SelectorContext::new();
        context.add_namespace("svg".to_string(), html5ever::ns!(svg));

        let selectors = Selectors::compile_with_context("svg|rect", &context).unwrap();
        assert_eq!(selectors.0.len(), 1);
    }

    /// Tests compile_with_context with undefined namespace prefix.
    ///
    /// Verifies that using an undefined namespace prefix results in a
    /// compilation error.
    #[test]
    #[cfg(feature = "namespaces")]
    fn compile_with_context_undefined_namespace() {
        let context = SelectorContext::new();

        let result = Selectors::compile_with_context("svg|rect", &context);
        assert!(result.is_err());
    }

    /// Tests compile_with_context without namespace-qualified selectors.
    ///
    /// Verifies that regular selectors work correctly with the context-aware
    /// compilation method.
    #[test]
    fn compile_with_context_no_namespace() {
        let context = SelectorContext::default();

        let selectors = Selectors::compile_with_context("div", &context).unwrap();
        assert_eq!(selectors.0.len(), 1);
    }
}