1
//! DOM tree to CSS style tree cascading.
2
//!
3
//! Implements CSS selector matching (`matches_html_element`) and cascade-info
4
//! construction (`construct_html_cascade_tree`). Used by `styled_dom` and
5
//! `prop_cache` to resolve which CSS rules apply to each DOM node.
6

            
7
use alloc::vec::Vec;
8

            
9
use azul_css::css::{
10
    AttributeMatchOp, CssAttributeSelector, CssContentGroup, CssNthChildSelector,
11
    CssNthChildSelector::{Even, Number, Odd, Pattern},
12
    CssPath, CssPathPseudoSelector, CssPathSelector,
13
};
14

            
15
use crate::{
16
    dom::NodeData,
17
    id::{NodeDataContainer, NodeDataContainerRef, NodeHierarchyRef, NodeId},
18
    styled_dom::NodeHierarchyItem,
19
};
20

            
21
/// Has all the necessary information about the style CSS path
22
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
23
#[repr(C)]
24
pub struct CascadeInfo {
25
    pub index_in_parent: u32,
26
    pub is_last_child: bool,
27
}
28

            
29
impl_option!(
30
    CascadeInfo,
31
    OptionCascadeInfo,
32
    [Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
33
);
34

            
35
impl_vec!(
36
    CascadeInfo,
37
    CascadeInfoVec,
38
    CascadeInfoVecDestructor,
39
    CascadeInfoVecDestructorType,
40
    CascadeInfoVecSlice,
41
    OptionCascadeInfo
42
);
43
impl_vec_mut!(CascadeInfo, CascadeInfoVec);
44
impl_vec_debug!(CascadeInfo, CascadeInfoVec);
45
impl_vec_partialord!(CascadeInfo, CascadeInfoVec);
46
impl_vec_clone!(CascadeInfo, CascadeInfoVec, CascadeInfoVecDestructor);
47
impl_vec_partialeq!(CascadeInfo, CascadeInfoVec);
48

            
49
impl CascadeInfoVec {
50
    #[must_use]
51
495
    pub fn as_container(&self) -> NodeDataContainerRef<'_, CascadeInfo> {
52
495
        NodeDataContainerRef {
53
495
            internal: self.as_ref(),
54
495
        }
55
495
    }
56
}
57

            
58
/// Returns if the style CSS path matches the DOM node (i.e. if the DOM node should be styled by
59
/// that element)
60
#[allow(clippy::needless_pass_by_value)] // owned azul value taken by value (public API / ownership-transfer convention)
61
#[allow(clippy::too_many_lines)] // large but cohesive: one branch per selector kind
62
#[must_use]
63
82858511
pub fn matches_html_element(
64
82858511
    css_path: &CssPath,
65
82858511
    node_id: NodeId,
66
82858511
    node_hierarchy: &NodeDataContainerRef<'_, NodeHierarchyItem>,
67
82858511
    node_data: &NodeDataContainerRef<'_, NodeData>,
68
82858511
    html_node_tree: &NodeDataContainerRef<'_, CascadeInfo>,
69
82858511
    expected_path_ending: Option<CssPathPseudoSelector>,
70
82858511
) -> bool {
71
    use self::CssGroupSplitReason::{AdjacentSibling, Children, DirectChildren, GeneralSibling};
72

            
73
82858511
    if css_path.selectors.is_empty() {
74
98
        return false;
75
82858413
    }
76

            
77
    // Skip anonymous nodes - they are not part of the original DOM tree
78
    // and should not participate in CSS selector matching
79
82858413
    if node_data[node_id].is_anonymous() {
80
3
        return false;
81
82858410
    }
82

            
83
    // Collect all selector groups (processed right-to-left from the CSS path).
84
82858410
    let groups: Vec<(CssContentGroup<'_>, CssGroupSplitReason)> =
85
82858410
        CssGroupIterator::new(css_path.selectors.as_ref()).collect();
86

            
87
82858410
    if groups.is_empty() {
88
        return false;
89
82858410
    }
90

            
91
    // The rightmost group must match the target node directly.
92
82858410
    let (ref first_group, first_reason) = groups[0];
93
    // groups[0] is ALWAYS the subject (rightmost) group, so it is the "last content
94
    // group" that an interactive pseudo (:hover/:focus/:active) attaches to — regardless
95
    // of how many ancestor groups precede it. The old `groups.len() == 1` disabled
96
    // :hover on the subject of every multi-group selector (e.g. `body > div:hover`).
97
82858410
    let is_last_content_group = true;
98
82858410
    if !selector_group_matches(
99
82858410
        first_group,
100
82858410
        html_node_tree[node_id],
101
82858410
        &node_data[node_id],
102
82858410
        node_id,
103
82858410
        expected_path_ending.as_ref(),
104
82858410
        is_last_content_group,
105
82858410
    ) {
106
82549363
        return false;
107
309047
    }
108

            
109
    // Navigate from the target node upward/sideways through the DOM,
110
    // matching each remaining selector group with its combinator.
111
309047
    let mut current_node = node_id;
112

            
113
309047
    for (group_idx, (content_group, _reason)) in groups.iter().enumerate().skip(1) {
114
        // The combinator comes from the PREVIOUS group's reason
115
155
        let combinator = groups[group_idx - 1].1;
116
155
        let is_last = group_idx == groups.len() - 1;
117

            
118
155
        match combinator {
119
            DirectChildren => {
120
                // Parent must match directly (child combinator `>`)
121
36
                let parent = find_non_anonymous_parent(current_node, node_hierarchy, node_data);
122
35
                match parent {
123
16
                    Some(p)
124
35
                        if selector_group_matches(
125
35
                            content_group,
126
35
                            html_node_tree[p],
127
35
                            &node_data[p],
128
35
                            p,
129
35
                            expected_path_ending.as_ref(),
130
35
                            is_last,
131
16
                        ) =>
132
16
                    {
133
16
                        current_node = p;
134
16
                    }
135
20
                    _ => return false,
136
                }
137
            }
138
            Children => {
139
                // Search up ancestor chain for a match (descendant combinator ` `)
140
114
                let mut ancestor =
141
114
                    find_non_anonymous_parent(current_node, node_hierarchy, node_data);
142
114
                let mut found = false;
143
178
                while let Some(anc) = ancestor {
144
152
                    if selector_group_matches(
145
152
                        content_group,
146
152
                        html_node_tree[anc],
147
152
                        &node_data[anc],
148
152
                        anc,
149
152
                        expected_path_ending.as_ref(),
150
152
                        is_last,
151
                    ) {
152
88
                        current_node = anc;
153
88
                        found = true;
154
88
                        break;
155
64
                    }
156
64
                    ancestor = find_non_anonymous_parent(anc, node_hierarchy, node_data);
157
                }
158
114
                if !found {
159
26
                    return false;
160
88
                }
161
            }
162
            AdjacentSibling => {
163
                // Immediate previous sibling must match (adjacent sibling `+`)
164
3
                let sibling =
165
3
                    find_non_anonymous_prev_sibling(current_node, node_hierarchy, node_data);
166
3
                match sibling {
167
2
                    Some(s)
168
3
                        if selector_group_matches(
169
3
                            content_group,
170
3
                            html_node_tree[s],
171
3
                            &node_data[s],
172
3
                            s,
173
3
                            expected_path_ending.as_ref(),
174
3
                            is_last,
175
2
                        ) =>
176
2
                    {
177
2
                        current_node = s;
178
2
                    }
179
1
                    _ => return false,
180
                }
181
            }
182
            GeneralSibling => {
183
                // Search previous siblings for a match (general sibling `~`)
184
2
                let mut sibling =
185
2
                    find_non_anonymous_prev_sibling(current_node, node_hierarchy, node_data);
186
2
                let mut found = false;
187
3
                while let Some(sib) = sibling {
188
2
                    if selector_group_matches(
189
2
                        content_group,
190
2
                        html_node_tree[sib],
191
2
                        &node_data[sib],
192
2
                        sib,
193
2
                        expected_path_ending.as_ref(),
194
2
                        is_last,
195
                    ) {
196
1
                        current_node = sib;
197
1
                        found = true;
198
1
                        break;
199
1
                    }
200
1
                    sibling = find_non_anonymous_prev_sibling(sib, node_hierarchy, node_data);
201
                }
202
2
                if !found {
203
1
                    return false;
204
1
                }
205
            }
206
        }
207
    }
208

            
209
308999
    true
210
82858511
}
211

            
212
/// Find the first non-anonymous parent of a node.
213
218
fn find_non_anonymous_parent(
214
218
    node_id: NodeId,
215
218
    node_hierarchy: &NodeDataContainerRef<'_, NodeHierarchyItem>,
216
218
    node_data: &NodeDataContainerRef<'_, NodeData>,
217
218
) -> Option<NodeId> {
218
218
    let mut next = node_hierarchy[node_id].parent_id();
219
221
    while let Some(n) = next {
220
192
        if !node_data[n].is_anonymous() {
221
189
            return Some(n);
222
3
        }
223
3
        next = node_hierarchy[n].parent_id();
224
    }
225
29
    None
226
218
}
227

            
228
/// Find the first previous sibling of a node that the `+`/`~` combinators can target:
229
/// an element, skipping anonymous boxes AND non-element (text) nodes.
230
///
231
/// CSS sibling combinators operate on ELEMENTS (Selectors L4 §15.2), so an intervening
232
/// text node must not block `.a + .b` from reaching the preceding element. Skipping only
233
/// anonymous boxes left text siblings in the way.
234
11
fn find_non_anonymous_prev_sibling(
235
11
    node_id: NodeId,
236
11
    node_hierarchy: &NodeDataContainerRef<'_, NodeHierarchyItem>,
237
11
    node_data: &NodeDataContainerRef<'_, NodeData>,
238
11
) -> Option<NodeId> {
239
11
    let mut next = node_hierarchy[node_id].previous_sibling_id();
240
16
    while let Some(n) = next {
241
12
        if !node_data[n].is_anonymous() && !node_data[n].is_text_node() {
242
7
            return Some(n);
243
5
        }
244
5
        next = node_hierarchy[n].previous_sibling_id();
245
    }
246
4
    None
247
11
}
248

            
249
/// A CSS group is a group of css selectors in a path that specify the rule that a
250
/// certain node has to match, i.e. "div.main.foo" has to match three requirements:
251
///
252
/// - the node has to be of type div
253
/// - the node has to have the class "main"
254
/// - the node has to have the class "foo"
255
///
256
/// If any of these requirements are not met, the CSS block is discarded.
257
///
258
/// The `CssGroupIterator` splits the CSS path into semantic blocks, i.e.:
259
///
260
/// `"body > .foo.main > #baz"` will be split into `["body", ".foo.main", "#baz"]`
261
#[derive(Debug)]
262
pub struct CssGroupIterator<'a> {
263
    pub css_path: &'a [CssPathSelector],
264
    current_idx: usize,
265
    last_reason: CssGroupSplitReason,
266
}
267

            
268
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
269
pub enum CssGroupSplitReason {
270
    /// ".foo .main" - match any children
271
    Children,
272
    /// ".foo > .main" - match only direct children
273
    DirectChildren,
274
    /// ".foo + .main" - match adjacent sibling (immediately preceding)
275
    AdjacentSibling,
276
    /// ".foo ~ .main" - match general sibling (any preceding sibling)
277
    GeneralSibling,
278
}
279

            
280
impl<'a> CssGroupIterator<'a> {
281
    #[must_use]
282
82858420
    pub const fn new(css_path: &'a [CssPathSelector]) -> Self {
283
82858420
        let initial_len = css_path.len();
284
82858420
        Self {
285
82858420
            css_path,
286
82858420
            current_idx: initial_len,
287
82858420
            last_reason: CssGroupSplitReason::Children,
288
82858420
        }
289
82858420
    }
290
}
291

            
292
impl<'a> Iterator for CssGroupIterator<'a> {
293
    type Item = (CssContentGroup<'a>, CssGroupSplitReason);
294

            
295
165722808
    fn next(&mut self) -> Option<(CssContentGroup<'a>, CssGroupSplitReason)> {
296
        use self::CssPathSelector::{AdjacentSibling, Children, DirectChildren, GeneralSibling};
297

            
298
165722808
        let mut new_idx = self.current_idx;
299

            
300
165722808
        if new_idx == 0 {
301
82858418
            return None;
302
82864390
        }
303

            
304
82864390
        let mut current_path = Vec::new();
305

            
306
248195359
        while new_idx != 0 {
307
165336943
            match self.css_path.get(new_idx - 1)? {
308
                Children => {
309
5902
                    self.last_reason = CssGroupSplitReason::Children;
310
5902
                    break;
311
                }
312
                DirectChildren => {
313
65
                    self.last_reason = CssGroupSplitReason::DirectChildren;
314
65
                    break;
315
                }
316
                AdjacentSibling => {
317
4
                    self.last_reason = CssGroupSplitReason::AdjacentSibling;
318
4
                    break;
319
                }
320
                GeneralSibling => {
321
3
                    self.last_reason = CssGroupSplitReason::GeneralSibling;
322
3
                    break;
323
                }
324
165330969
                other => current_path.push(other),
325
            }
326
165330969
            new_idx -= 1;
327
        }
328

            
329
        // NOTE: Order inside of a ContentGroup is not important
330
        // for matching elements, only important for testing
331
        #[cfg(test)]
332
7704
        current_path.reverse();
333

            
334
82864390
        if new_idx == 0 {
335
82858416
            if current_path.is_empty() {
336
                None
337
            } else {
338
                // Last element of path
339
82858416
                self.current_idx = 0;
340
82858416
                Some((current_path, self.last_reason))
341
            }
342
        } else {
343
            // skip the "Children | DirectChildren" element itself
344
5974
            self.current_idx = new_idx - 1;
345
5974
            Some((current_path, self.last_reason))
346
        }
347
165722808
    }
348
}
349

            
350
#[must_use]
351
42107
pub fn construct_html_cascade_tree(
352
42107
    node_hierarchy: &NodeHierarchyRef<'_>,
353
42107
    node_depths_sorted: &[(usize, NodeId)],
354
42107
    node_data: &NodeDataContainerRef<'_, NodeData>,
355
42107
) -> NodeDataContainer<CascadeInfo> {
356
42107
    let mut nodes = (0..node_hierarchy.len())
357
42107
        .map(|_| CascadeInfo {
358
            index_in_parent: 0,
359
            is_last_child: false,
360
858138
        })
361
42107
        .collect::<Vec<_>>();
362

            
363
485946
    for (_depth, parent_id) in node_depths_sorted {
364
        // Per CSS Selectors Level 4 §13: "Standalone text and other non-element
365
        // nodes are not counted when calculating the position of an element in
366
        // the list of children of its parent."
367
        //
368
        // We count only element siblings when computing index_in_parent.
369
443839
        let element_index_in_parent = parent_id
370
443839
            .preceding_siblings(node_hierarchy)
371
8108781
            .filter(|sib_id| !node_data[*sib_id].is_text_node())
372
443839
            .count();
373

            
374
443839
        let parent_html_matcher = CascadeInfo {
375
443839
            index_in_parent: u32::try_from(element_index_in_parent.saturating_sub(1))
376
443839
                .unwrap_or(u32::MAX),
377
            // Necessary for :last selectors — find last element sibling
378
            is_last_child: {
379
443839
                let mut is_last_element = true;
380
443839
                let mut next = node_hierarchy[*parent_id].next_sibling;
381
468147
                while let Some(sib_id) = next {
382
255081
                    if !node_data[sib_id].is_text_node() {
383
230773
                        is_last_element = false;
384
230773
                        break;
385
24308
                    }
386
24308
                    next = node_hierarchy[sib_id].next_sibling;
387
                }
388
443839
                is_last_element
389
            },
390
        };
391

            
392
443839
        nodes[parent_id.index()] = parent_html_matcher;
393

            
394
        // Count only element children for index_in_parent
395
443839
        let mut element_idx: u32 = 0;
396
816104
        for child_id in parent_id.children(node_hierarchy) {
397
816104
            let is_text = node_data[child_id].is_text_node();
398

            
399
            // Find whether this is the last element child (skip trailing text nodes)
400
816104
            let is_last_element_child = if is_text {
401
268638
                false
402
            } else {
403
547466
                let mut is_last = true;
404
547466
                let mut next = node_hierarchy[child_id].next_sibling;
405
573970
                while let Some(sib_id) = next {
406
353888
                    if !node_data[sib_id].is_text_node() {
407
327384
                        is_last = false;
408
327384
                        break;
409
26504
                    }
410
26504
                    next = node_hierarchy[sib_id].next_sibling;
411
                }
412
547466
                is_last
413
            };
414

            
415
816104
            let child_html_matcher = CascadeInfo {
416
816104
                index_in_parent: element_idx,
417
816104
                is_last_child: is_last_element_child,
418
816104
            };
419

            
420
816104
            nodes[child_id.index()] = child_html_matcher;
421

            
422
816104
            if !is_text {
423
547466
                element_idx += 1;
424
547814
            }
425
        }
426
    }
427

            
428
42107
    NodeDataContainer { internal: nodes }
429
42107
}
430

            
431
/// Checks whether the last selector in `path` matches the given pseudo-selector `target`.
432
///
433
/// Known limitation: this only inspects the final selector in the path, so compound
434
/// selectors like `div:hover:first-child` may not be filtered correctly when `target`
435
/// is `None` — only the very last pseudo-selector is tested.
436
#[inline]
437
#[must_use]
438
84370732
pub fn rule_ends_with(path: &CssPath, target: Option<CssPathPseudoSelector>) -> bool {
439
    // Helper to check if a pseudo-selector is "interactive" (requires user interaction state)
440
    // vs "structural" (based on DOM structure only)
441
8509
    const fn is_interactive_pseudo(p: &CssPathPseudoSelector) -> bool {
442
3
        matches!(
443
8509
            p,
444
            CssPathPseudoSelector::Hover
445
                | CssPathPseudoSelector::Active
446
                | CssPathPseudoSelector::Focus
447
                | CssPathPseudoSelector::SeatFocus
448
                | CssPathPseudoSelector::Backdrop
449
                | CssPathPseudoSelector::Dragging
450
                | CssPathPseudoSelector::DragOver
451
                | CssPathPseudoSelector::Placeholder
452
        )
453
8509
    }
454

            
455
84370732
    let Some(last) = path.selectors.as_ref().last() else {
456
3
        return false;
457
    };
458
84370729
    target.map_or_else(
459
82884232
        || match last {
460
            // Only reject interactive pseudo-selectors (hover, active, focus).
461
            // Structural pseudo-selectors (nth-child, first, last) should be allowed.
462
8509
            CssPathSelector::PseudoSelector(p) => !is_interactive_pseudo(p),
463
82875723
            _ => true,
464
82884232
        },
465
12348
        |s| matches!(last, CssPathSelector::PseudoSelector(q) if *q == s),
466
    )
467
84370732
}
468

            
469
/// Matches a single group of CSS selectors against a DOM node.
470
///
471
/// Returns true if all selectors in the group match the given node.
472
/// Combinator selectors (>, +, ~, space) should not appear in the group.
473
82858609
fn selector_group_matches(
474
82858609
    selectors: &[&CssPathSelector],
475
82858609
    html_node: CascadeInfo,
476
82858609
    node_data: &NodeData,
477
82858609
    node_id: NodeId,
478
82858609
    expected_path_ending: Option<&CssPathPseudoSelector>,
479
82858609
    is_last_content_group: bool,
480
82858609
) -> bool {
481
    // Inline-style detection for the `Global` arm: a bare-declaration
482
    // `with_css` rule is scoped to EXACTLY its owner node when the scope is
483
    // pushed (`push_front_scope_for` collapses the range to `[owner, owner]`
484
    // for INLINE-priority bare `*` wrappers). Such a rule is the author
485
    // addressing THIS node directly — it must style a text node too.
486
165325014
    let node_scoped_to_self = selectors.iter().any(|s| {
487
82457655
        matches!(s, CssPathSelector::Root(r)
488
82457655
            if r.start == r.end && r.start == node_id.index())
489
165325014
    });
490
139347217
    selectors.iter().all(|selector| {
491
139347217
        match_single_selector(
492
139347217
            selector,
493
139347217
            html_node,
494
139347217
            node_data,
495
139347217
            node_id,
496
139347217
            expected_path_ending,
497
139347217
            is_last_content_group,
498
139347217
            node_scoped_to_self,
499
        )
500
139347217
    })
501
82858609
}
502

            
503
/// Matches a single CSS selector against a DOM node.
504
139347247
fn match_single_selector(
505
139347247
    selector: &CssPathSelector,
506
139347247
    html_node: CascadeInfo,
507
139347247
    node_data: &NodeData,
508
139347247
    node_id: NodeId,
509
139347247
    expected_path_ending: Option<&CssPathPseudoSelector>,
510
139347247
    is_last_content_group: bool,
511
139347247
    node_scoped_to_self: bool,
512
139347247
) -> bool {
513
    use self::CssPathSelector::{
514
        AdjacentSibling, Attribute, Children, Class, DirectChildren, GeneralSibling, Global, Id,
515
        PseudoSelector, Root, Type,
516
    };
517

            
518
8507
    match selector {
519
        // Per CSS, `*` matches ELEMENTS - never text nodes: letting a
520
        // stylesheet's universal selector hit text nodes made
521
        // `* { color: #666 }` overwrite the color a text child had just
522
        // inherited from its `p { color: red }` parent. The one exception is
523
        // a rule scoped to EXACTLY this node (`node_scoped_to_self`) — that
524
        // is a bare-declaration `with_css` ON the text node itself, i.e.
525
        // inline-style semantics:
526
        // `create_text_do_not_use_without_block_level_wrapper("x").with_css("color: white")`
527
        // must apply. Subtree-scoped and unscoped `*` rules keep refusing
528
        // text nodes.
529
82086895
        Global => !node_data.is_text_node() || node_scoped_to_self,
530
        // `Root(range)` (scope marker, #47): matches any node WITHIN the subtree
531
        // range `[start, end]`. The range is chosen when the scope is pushed
532
        // (`CssPath::push_front_scope`):
533
        //  - a bare-decl `with_css` rule (`* { … }`) is scoped node-only (`[start, start]`) →
534
        //    inline-style semantics: it applies to the OWNER only, so a non-root `background` can't
535
        //    leak to descendants/siblings (#47 leak fix).
536
        //  - a component rule with a real selector (`.menu-item`, from `add_component_css`) is
537
        //    scoped to the whole subtree (`[start, end]`) so its selector matches descendants of
538
        //    the owner (a menu container styling its `.menu-item` children). Compounded with the
539
        //    rest of the path, `[Root(range), Class(x)]` means "a node in range that also matches
540
        //    `.x`".
541
56480027
        Root(range) => range.contains(node_id.index()),
542
367315
        Type(t) => node_data.get_node_type().get_path() == *t,
543
394433
        Class(c) => node_data.has_class(c.as_str()),
544
9743
        Id(id) => node_data.has_id(id.as_str()),
545
        // `:root` matches the document root element (NodeId::ZERO, the topmost
546
        // element). Handled here rather than in `match_pseudo_selector` because it
547
        // needs `node_id`. Equivalent to `html` but with pseudo-class specificity.
548
        PseudoSelector(CssPathPseudoSelector::Root) => node_id.index() == 0,
549
8507
        PseudoSelector(p) => {
550
8507
            match_pseudo_selector(p, html_node, expected_path_ending, is_last_content_group)
551
        }
552
323
        Attribute(a) => match_attribute_selector(a, node_data),
553
4
        DirectChildren | Children | AdjacentSibling | GeneralSibling => false,
554
    }
555
139347247
}
556

            
557
/// Matches an attribute selector (`[name]`, `[name="v"]`, `[name~="v"]`, ...) against a node.
558
///
559
/// Some attributes (notably `class`) are stored as multiple separate entries in
560
/// `node_data.attributes()` rather than a single space-joined string. We collect
561
/// every matching value and treat the matcher as "any value satisfies the op",
562
/// so that `[class~="primary"]` matches a node with classes `foo primary bar`.
563
376
fn match_attribute_selector(sel: &CssAttributeSelector, node_data: &NodeData) -> bool {
564
376
    let name = sel.name.as_str();
565
376
    let target = sel.value.as_ref().map(azul_css::AzString::as_str);
566

            
567
376
    let check = |actual: &str| -> bool {
568
364
        match (&sel.op, target) {
569
21
            (AttributeMatchOp::Exists, _) => true,
570
62
            (AttributeMatchOp::Eq, Some(t)) => actual == t,
571
69
            (AttributeMatchOp::Includes, Some(t)) => {
572
69
                if t.is_empty() || t.contains(char::is_whitespace) {
573
7
                    return false;
574
62
                }
575
62
                actual.split_whitespace().any(|word| word == t)
576
            }
577
64
            (AttributeMatchOp::DashMatch, Some(t)) => {
578
64
                actual == t || actual.starts_with(&alloc::format!("{t}-"))
579
            }
580
60
            (AttributeMatchOp::Prefix, Some(t)) => !t.is_empty() && actual.starts_with(t),
581
41
            (AttributeMatchOp::Suffix, Some(t)) => !t.is_empty() && actual.ends_with(t),
582
41
            (AttributeMatchOp::Substring, Some(t)) => !t.is_empty() && actual.contains(t),
583
            // Operator with a missing value (parser should reject these — be defensive).
584
6
            (_, None) => false,
585
        }
586
364
    };
587

            
588
376
    for attr in node_data.attributes() {
589
369
        if attr.name() != name {
590
5
            continue;
591
364
        }
592
364
        if check(attr.value().as_str()) {
593
186
            return true;
594
178
        }
595
    }
596

            
597
190
    false
598
376
}
599

            
600
/// Matches a pseudo-selector (:first, :last, :nth-child, :hover, etc.) against a node.
601
8544
fn match_pseudo_selector(
602
8544
    pseudo: &CssPathPseudoSelector,
603
8544
    html_node: CascadeInfo,
604
8544
    expected_path_ending: Option<&CssPathPseudoSelector>,
605
8544
    is_last_content_group: bool,
606
8544
) -> bool {
607
8544
    match pseudo {
608
7
        CssPathPseudoSelector::First => match_first_child(html_node),
609
4
        CssPathPseudoSelector::Last => match_last_child(html_node),
610
5
        CssPathPseudoSelector::NthChild(pattern) => match_nth_child(html_node, pattern),
611
8386
        CssPathPseudoSelector::Hover => match_interactive_pseudo(
612
8386
            &CssPathPseudoSelector::Hover,
613
8386
            expected_path_ending,
614
8386
            is_last_content_group,
615
        ),
616
3
        CssPathPseudoSelector::Active => match_interactive_pseudo(
617
3
            &CssPathPseudoSelector::Active,
618
3
            expected_path_ending,
619
3
            is_last_content_group,
620
        ),
621
105
        CssPathPseudoSelector::Focus => match_interactive_pseudo(
622
105
            &CssPathPseudoSelector::Focus,
623
105
            expected_path_ending,
624
105
            is_last_content_group,
625
        ),
626
18
        CssPathPseudoSelector::SeatFocus => match_interactive_pseudo(
627
18
            &CssPathPseudoSelector::SeatFocus,
628
18
            expected_path_ending,
629
18
            is_last_content_group,
630
        ),
631
3
        CssPathPseudoSelector::Backdrop => match_interactive_pseudo(
632
3
            &CssPathPseudoSelector::Backdrop,
633
3
            expected_path_ending,
634
3
            is_last_content_group,
635
        ),
636
3
        CssPathPseudoSelector::Dragging => match_interactive_pseudo(
637
3
            &CssPathPseudoSelector::Dragging,
638
3
            expected_path_ending,
639
3
            is_last_content_group,
640
        ),
641
3
        CssPathPseudoSelector::DragOver => match_interactive_pseudo(
642
3
            &CssPathPseudoSelector::DragOver,
643
3
            expected_path_ending,
644
3
            is_last_content_group,
645
        ),
646
7
        CssPathPseudoSelector::Lang(lang) => {
647
            // :lang() is matched via DynamicSelector at runtime, not during CSS cascade
648
            // During cascade, we just check if this is the expected ending
649
6
            if let Some(CssPathPseudoSelector::Lang(expected_lang)) = expected_path_ending {
650
5
                return lang == expected_lang;
651
2
            }
652
            // If not specifically looking for :lang, it doesn't match structurally
653
2
            false
654
        }
655
        // `::placeholder` styles PAINTED GLYPHS, not the node, so it can only
656
        // match the dedicated resolve the engine does for the prompt - the
657
        // same "expected ending" gate the interactive pseudos use.
658
        CssPathPseudoSelector::Placeholder => match_interactive_pseudo(
659
            &CssPathPseudoSelector::Placeholder,
660
            expected_path_ending,
661
            is_last_content_group,
662
        ),
663
        // `:root` is matched in `match_single_selector` (it needs `node_id`), so it
664
        // never reaches here — return false defensively.
665
        CssPathPseudoSelector::Root => false,
666
    }
667
8544
}
668

            
669
/// Returns true if the node is the first child of its parent.
670
10
const fn match_first_child(html_node: CascadeInfo) -> bool {
671
10
    html_node.index_in_parent == 0
672
10
}
673

            
674
/// Returns true if the node is the last child of its parent.
675
7
const fn match_last_child(html_node: CascadeInfo) -> bool {
676
7
    html_node.is_last_child
677
7
}
678

            
679
/// Matches :nth-child(n), :nth-child(even), :nth-child(odd), or :nth-child(An+B) patterns.
680
7209
fn match_nth_child(html_node: CascadeInfo, pattern: &CssNthChildSelector) -> bool {
681
    use azul_css::css::CssNthChildPattern;
682

            
683
    // nth-child is 1-indexed, index_in_parent is 0-indexed
684
7209
    let index = html_node.index_in_parent + 1;
685

            
686
7209
    match pattern {
687
4105
        Number(n) => index == *n,
688
1259
        Even => index.is_multiple_of(2),
689
1259
        Odd => index % 2 == 1,
690
        Pattern(CssNthChildPattern {
691
586
            pattern_repeat,
692
586
            offset,
693
        }) => {
694
586
            if *pattern_repeat == 0 {
695
64
                index == *offset
696
            } else {
697
522
                index >= *offset && (index - offset).is_multiple_of(*pattern_repeat)
698
            }
699
        }
700
    }
701
7209
}
702

            
703
/// Matches interactive pseudo-selectors (:hover, :active, :focus).
704
/// These only apply if they appear in the last content group of the CSS path.
705
8526
fn match_interactive_pseudo(
706
8526
    pseudo: &CssPathPseudoSelector,
707
8526
    expected_path_ending: Option<&CssPathPseudoSelector>,
708
8526
    is_last_content_group: bool,
709
8526
) -> bool {
710
8526
    is_last_content_group && expected_path_ending == Some(pseudo)
711
8526
}
712

            
713
#[cfg(test)]
714
#[path = "style_test.rs"]
715
mod style_test;