Skip to main content

strata/runtime/
hover.rs

1//! Hierarchical hover path tracking, boundary event dispatch, and restyling.
2
3use super::*;
4
5impl AppRuntime {
6    /// Locates the blueprint and layout node at a hierarchical index path in the tree.
7    pub fn find_node_by_path<'a>(
8        blueprint: &'a NodeBlueprint,
9        layout: &'a LayoutNode,
10        path: &[usize],
11    ) -> Option<(&'a NodeBlueprint, &'a LayoutNode)> {
12        let mut cur_bp = blueprint;
13        let mut cur_layout = layout;
14
15        for &idx in path {
16            match cur_bp {
17                NodeBlueprint::Element { children, .. } => {
18                    let mut flat = Vec::new();
19                    for c in children {
20                        Self::flatten_blueprints(c, &mut flat);
21                    }
22                    if idx >= flat.len() || idx >= cur_layout.children.len() {
23                        return None;
24                    }
25                    cur_bp = flat[idx];
26                    cur_layout = &cur_layout.children[idx];
27                }
28                NodeBlueprint::Fragment(children) => {
29                    let mut flat = Vec::new();
30                    for c in children {
31                        Self::flatten_blueprints(c, &mut flat);
32                    }
33                    if idx >= flat.len() || idx >= cur_layout.children.len() {
34                        return None;
35                    }
36                    cur_bp = flat[idx];
37                    cur_layout = &cur_layout.children[idx];
38                }
39                _ => return None,
40            }
41        }
42
43        Some((cur_bp, cur_layout))
44    }
45
46    /// Recursively hit tests a coordinate point against the blueprint and computed layout hierarchy,
47    /// returning the hierarchical index path of the deepest matching element node.
48    pub fn hit_test_node_path(
49        blueprint: &NodeBlueprint,
50        layout: &LayoutNode,
51        px: f32,
52        py: f32,
53    ) -> Option<Vec<usize>> {
54        let mut path = Vec::new();
55        Self::hit_test_node_path_rec(blueprint, layout, px, py, &mut path)
56    }
57
58    fn collect_top_layer_hover_portals<'a>(
59        bp: &'a NodeBlueprint,
60        layout: &'a LayoutNode,
61        current_path: &mut Vec<usize>,
62        out: &mut Vec<(&'a NodeBlueprint, &'a LayoutNode, Vec<usize>)>,
63    ) {
64        if current_path.len() >= 256 {
65            return;
66        }
67        for (idx, child_bp, child_layout) in Self::paired_blueprint_children(bp, layout) {
68            if matches!(
69                child_layout.style.display,
70                strata_style::types::Display::None
71            ) {
72                continue;
73            }
74            current_path.push(idx);
75            if child_layout.is_top_layer {
76                out.push((child_bp, child_layout, current_path.clone()));
77            }
78            if !child_layout.children.is_empty()
79                && ((child_layout.subtree_hit_flags & strata_layout::tree::SUBTREE_META_VALID)
80                    == 0
81                    || (child_layout.subtree_hit_flags & strata_layout::tree::SUBTREE_HAS_TOP_LAYER)
82                        != 0)
83            {
84                Self::collect_top_layer_hover_portals(child_bp, child_layout, current_path, out);
85            }
86            current_path.pop();
87        }
88    }
89
90    pub(crate) fn hit_test_node_path_rec(
91        blueprint: &NodeBlueprint,
92        layout: &LayoutNode,
93        px: f32,
94        py: f32,
95        current_path: &mut Vec<usize>,
96    ) -> Option<Vec<usize>> {
97        if current_path.is_empty()
98            && ((layout.subtree_hit_flags & strata_layout::tree::SUBTREE_META_VALID) == 0
99                || (layout.subtree_hit_flags & strata_layout::tree::SUBTREE_HAS_TOP_LAYER) != 0)
100        {
101            let mut portals = Vec::new();
102            let mut scan_path = Vec::new();
103            Self::collect_top_layer_hover_portals(blueprint, layout, &mut scan_path, &mut portals);
104            for (p_bp, p_layout, mut p_path) in portals.into_iter().rev() {
105                if let Some(hit) =
106                    Self::hit_test_node_path_sc(p_bp, p_layout, px, py, &[], &mut p_path)
107                {
108                    return Some(hit);
109                }
110            }
111        }
112        Self::hit_test_node_path_sc(blueprint, layout, px, py, &[], current_path)
113    }
114
115    #[allow(clippy::too_many_arguments, clippy::type_complexity)]
116    fn collect_hoisted_hover_participants<'a>(
117        bp: &'a NodeBlueprint,
118        layout: &'a LayoutNode,
119        steps: &[super::hit_test::HitClipStep],
120        current_path: &mut Vec<usize>,
121        negative_z: &mut Vec<(
122            &'a NodeBlueprint,
123            &'a LayoutNode,
124            Vec<usize>,
125            Vec<super::hit_test::HitClipStep>,
126        )>,
127        auto_or_zero_z: &mut Vec<(
128            &'a NodeBlueprint,
129            &'a LayoutNode,
130            Vec<usize>,
131            bool,
132            Vec<super::hit_test::HitClipStep>,
133        )>,
134        positive_z: &mut Vec<(
135            &'a NodeBlueprint,
136            &'a LayoutNode,
137            Vec<usize>,
138            Vec<super::hit_test::HitClipStep>,
139        )>,
140    ) {
141        if current_path.len() >= 256 {
142            return;
143        }
144        let parent_display = Some(layout.style.display);
145        for (idx, child_bp, child_layout) in Self::paired_blueprint_children(bp, layout) {
146            if child_layout.is_top_layer
147                || matches!(
148                    child_layout.style.display,
149                    strata_style::types::Display::None
150                )
151                || matches!(
152                    child_layout.style.visibility,
153                    strata_style::types::Visibility::Hidden
154                )
155            {
156                continue;
157            }
158            current_path.push(idx);
159            if Self::establishes_stacking_context_in(child_layout, parent_display, false) {
160                let eff_steps = Self::effective_hit_clip_steps(child_layout, steps).to_vec();
161                let z = child_layout.style.z_index.unwrap_or(0);
162                if z < 0 {
163                    negative_z.push((child_bp, child_layout, current_path.clone(), eff_steps));
164                } else if z > 0 {
165                    positive_z.push((child_bp, child_layout, current_path.clone(), eff_steps));
166                } else {
167                    auto_or_zero_z.push((
168                        child_bp,
169                        child_layout,
170                        current_path.clone(),
171                        true,
172                        eff_steps,
173                    ));
174                }
175            } else {
176                let eff_for_child = Self::effective_hit_clip_steps(child_layout, steps);
177                if child_layout.style.position != strata_style::types::Position::Static {
178                    auto_or_zero_z.push((
179                        child_bp,
180                        child_layout,
181                        current_path.clone(),
182                        false,
183                        eff_for_child.to_vec(),
184                    ));
185                }
186                let skip_recurse = child_layout.children.is_empty()
187                    || ((child_layout.subtree_hit_flags & strata_layout::tree::SUBTREE_META_VALID)
188                        != 0
189                        && (child_layout.subtree_hit_flags
190                            & strata_layout::tree::SUBTREE_HAS_HOISTED)
191                            == 0);
192                if !skip_recurse {
193                    let step = Self::hit_clip_step_for(child_layout);
194                    if step.clip.is_some() || step.is_abs_cb || step.is_fixed_cb {
195                        let mut child_steps = Vec::with_capacity(eff_for_child.len() + 1);
196                        child_steps.extend_from_slice(eff_for_child);
197                        child_steps.push(step);
198                        Self::collect_hoisted_hover_participants(
199                            child_bp,
200                            child_layout,
201                            &child_steps,
202                            current_path,
203                            negative_z,
204                            auto_or_zero_z,
205                            positive_z,
206                        );
207                    } else {
208                        Self::collect_hoisted_hover_participants(
209                            child_bp,
210                            child_layout,
211                            eff_for_child,
212                            current_path,
213                            negative_z,
214                            auto_or_zero_z,
215                            positive_z,
216                        );
217                    }
218                }
219            }
220            current_path.pop();
221        }
222    }
223
224    fn hit_test_node_path_in_flow(
225        blueprint: &NodeBlueprint,
226        layout: &LayoutNode,
227        px: f32,
228        py: f32,
229        inherited_steps: &[super::hit_test::HitClipStep],
230        current_path: &mut Vec<usize>,
231    ) -> Option<Vec<usize>> {
232        if current_path.len() >= 256
233            || matches!(layout.style.display, strata_style::types::Display::None)
234            || matches!(
235                layout.style.visibility,
236                strata_style::types::Visibility::Hidden
237            )
238        {
239            return None;
240        }
241
242        let eff_inherited = Self::effective_hit_clip_steps(layout, inherited_steps);
243        if !Self::hit_clip_steps_allow(eff_inherited, px, py) {
244            return None;
245        }
246        if (layout.style.overflow_x != strata_style::types::Overflow::Visible
247            || layout.style.overflow_y != strata_style::types::Overflow::Visible)
248            && !layout.geometry.border_box.contains_point(px, py)
249        {
250            return None;
251        }
252        if (layout.subtree_hit_flags
253            & (strata_layout::tree::SUBTREE_META_VALID
254                | strata_layout::tree::SUBTREE_HAS_TRANSFORM))
255            == strata_layout::tree::SUBTREE_META_VALID
256            && !layout.subtree_bounds.contains_point(px, py)
257        {
258            return None;
259        }
260
261        let parent_display = Some(layout.style.display);
262        let paired = Self::paired_blueprint_children(blueprint, layout);
263        for &(idx, child_bp, child_layout) in paired.iter().rev() {
264            if child_layout.is_top_layer
265                || matches!(
266                    child_layout.style.display,
267                    strata_style::types::Display::None
268                )
269                || Self::establishes_stacking_context_in(child_layout, parent_display, false)
270                || child_layout.style.position != strata_style::types::Position::Static
271            {
272                continue;
273            }
274            if (child_layout.subtree_hit_flags
275                & (strata_layout::tree::SUBTREE_META_VALID
276                    | strata_layout::tree::SUBTREE_HAS_TRANSFORM))
277                == strata_layout::tree::SUBTREE_META_VALID
278                && !child_layout.subtree_bounds.contains_point(px, py)
279            {
280                continue;
281            }
282            current_path.push(idx);
283            if let Some(res) =
284                Self::hit_test_node_path_in_flow(child_bp, child_layout, px, py, &[], current_path)
285            {
286                return Some(res);
287            }
288            current_path.pop();
289        }
290
291        if !matches!(
292            layout.style.pointer_events,
293            strata_style::types::PointerEvents::None
294        ) {
295            match blueprint {
296                NodeBlueprint::Element { .. }
297                | NodeBlueprint::Text(_)
298                | NodeBlueprint::DynamicText(_) => {
299                    if layout.geometry.border_box.contains_point(px, py) {
300                        return Some(current_path.clone());
301                    }
302                }
303                _ => {}
304            }
305        }
306        None
307    }
308
309    fn hit_test_node_path_sc(
310        blueprint: &NodeBlueprint,
311        layout: &LayoutNode,
312        px: f32,
313        py: f32,
314        inherited_steps: &[super::hit_test::HitClipStep],
315        current_path: &mut Vec<usize>,
316    ) -> Option<Vec<usize>> {
317        if current_path.len() >= 256
318            || matches!(layout.style.display, strata_style::types::Display::None)
319            || matches!(
320                layout.style.visibility,
321                strata_style::types::Visibility::Hidden
322            )
323        {
324            return None;
325        }
326
327        let eff_inherited = Self::effective_hit_clip_steps(layout, inherited_steps);
328        let inherited_allows = Self::hit_clip_steps_allow(eff_inherited, px, py);
329
330        let (px, py) = Self::unproject_point(layout, px, py);
331
332        let own_clips = layout.style.overflow_x != strata_style::types::Overflow::Visible
333            || layout.style.overflow_y != strata_style::types::Overflow::Visible;
334        let own_allows = !own_clips || layout.geometry.border_box.contains_point(px, py);
335
336        let need_hoisted = (layout.subtree_hit_flags & strata_layout::tree::SUBTREE_META_VALID) == 0
337            || layout.children.iter().any(|c| {
338                (c.subtree_hit_flags & strata_layout::tree::SUBTREE_HAS_HOISTED) != 0
339            });
340        let mut negative_z = Vec::new();
341        if need_hoisted {
342            let mut base_steps = Vec::with_capacity(eff_inherited.len() + 1);
343            base_steps.extend_from_slice(eff_inherited);
344            let own_step = Self::hit_clip_step_for(layout);
345            if own_step.clip.is_some() || own_step.is_abs_cb || own_step.is_fixed_cb {
346                base_steps.push(own_step);
347            }
348
349            let mut auto_or_zero_z = Vec::new();
350            let mut positive_z = Vec::new();
351            Self::collect_hoisted_hover_participants(
352                blueprint,
353                layout,
354                &base_steps,
355                current_path,
356                &mut negative_z,
357                &mut auto_or_zero_z,
358                &mut positive_z,
359            );
360
361            negative_z.sort_by_key(|(_, l, _, _)| l.style.z_index.unwrap_or(0));
362            positive_z.sort_by_key(|(_, l, _, _)| l.style.z_index.unwrap_or(0));
363
364            // Layer 7: positive z-index child stacking contexts
365            for (c_bp, c_layout, c_path, c_steps) in positive_z.into_iter().rev() {
366                let mut path_buf = c_path;
367                if let Some(res) =
368                    Self::hit_test_node_path_sc(c_bp, c_layout, px, py, &c_steps, &mut path_buf)
369                {
370                    return Some(res);
371                }
372            }
373
374            // Layer 6: positioned auto/0 z-index descendants
375            for (c_bp, c_layout, c_path, is_sc, c_steps) in auto_or_zero_z.into_iter().rev() {
376                let mut path_buf = c_path;
377                let hit = if is_sc {
378                    Self::hit_test_node_path_sc(c_bp, c_layout, px, py, &c_steps, &mut path_buf)
379                } else {
380                    Self::hit_test_node_path_in_flow(c_bp, c_layout, px, py, &c_steps, &mut path_buf)
381                };
382                if hit.is_some() {
383                    return hit;
384                }
385            }
386        }
387
388        // Layers 5, 4, 3: direct static non-stacking-context children
389        if inherited_allows && own_allows {
390            let parent_display = Some(layout.style.display);
391            let paired = Self::paired_blueprint_children(blueprint, layout);
392            for &(idx, child_bp, child_layout) in paired.iter().rev() {
393                if child_layout.is_top_layer
394                    || matches!(
395                        child_layout.style.display,
396                        strata_style::types::Display::None
397                    )
398                    || Self::establishes_stacking_context_in(child_layout, parent_display, false)
399                    || child_layout.style.position != strata_style::types::Position::Static
400                    || ((child_layout.subtree_hit_flags
401                        & (strata_layout::tree::SUBTREE_META_VALID
402                            | strata_layout::tree::SUBTREE_HAS_TRANSFORM))
403                        == strata_layout::tree::SUBTREE_META_VALID
404                        && !child_layout.subtree_bounds.contains_point(px, py))
405                {
406                    continue;
407                }
408                current_path.push(idx);
409                if let Some(res) = Self::hit_test_node_path_in_flow(
410                    child_bp,
411                    child_layout,
412                    px,
413                    py,
414                    &[],
415                    current_path,
416                ) {
417                    return Some(res);
418                }
419                current_path.pop();
420            }
421        }
422
423        // Layer 2: negative z-index child stacking contexts
424        for (c_bp, c_layout, c_path, c_steps) in negative_z.into_iter().rev() {
425            let mut path_buf = c_path;
426            if let Some(res) =
427                Self::hit_test_node_path_sc(c_bp, c_layout, px, py, &c_steps, &mut path_buf)
428            {
429                return Some(res);
430            }
431        }
432
433        // Layer 1: stacking context root itself
434        if inherited_allows
435            && !matches!(
436                layout.style.pointer_events,
437                strata_style::types::PointerEvents::None
438            )
439        {
440            match blueprint {
441                NodeBlueprint::Element { .. }
442                | NodeBlueprint::Text(_)
443                | NodeBlueprint::DynamicText(_) => {
444                    if layout.geometry.border_box.contains_point(px, py) {
445                        Some(current_path.clone())
446                    } else {
447                        None
448                    }
449                }
450                _ => None,
451            }
452        } else {
453            None
454        }
455    }
456
457    /// Dispatches W3C boundary events (`mouseout`, `mouseleave`, `mouseover`, `mouseenter`)
458    /// between the previous hover path and the newly active hover path.
459    pub fn dispatch_boundary_events(
460        &self,
461        old_path: Option<&[usize]>,
462        new_path: Option<&[usize]>,
463        px: f32,
464        py: f32,
465    ) {
466        let old_slice = old_path.unwrap_or(&[]);
467        let new_slice = new_path.unwrap_or(&[]);
468
469        let mut common_len = 0;
470        if old_path.is_some() && new_path.is_some() {
471            while common_len < old_slice.len()
472                && common_len < new_slice.len()
473                && old_slice[common_len] == new_slice[common_len]
474            {
475                common_len += 1;
476            }
477        }
478
479        // Dispatches exit events for nodes no longer hovered (from deepest child up)
480        if old_path.is_some() {
481            let min_len = if new_path.is_some() {
482                common_len + 1
483            } else {
484                0
485            };
486            for len in (min_len..=old_slice.len()).rev() {
487                let subpath = &old_slice[..len];
488                if let Some((bp, layout)) =
489                    Self::find_node_by_path(&self.root_blueprint, &self.layout_root, subpath)
490                {
491                    self.dispatch_node_events(
492                        bp,
493                        layout,
494                        &[
495                            strata_dom::EventType::MouseOut,
496                            strata_dom::EventType::MouseLeave,
497                        ],
498                        px,
499                        py,
500                    );
501                }
502            }
503        }
504
505        // Dispatches enter events for newly hovered nodes (from shallowest ancestor down)
506        if new_path.is_some() {
507            let start_len = if old_path.is_some() {
508                common_len + 1
509            } else {
510                0
511            };
512            for len in start_len..=new_slice.len() {
513                let subpath = &new_slice[..len];
514                if let Some((bp, layout)) =
515                    Self::find_node_by_path(&self.root_blueprint, &self.layout_root, subpath)
516                {
517                    self.dispatch_node_events(
518                        bp,
519                        layout,
520                        &[
521                            strata_dom::EventType::MouseOver,
522                            strata_dom::EventType::MouseEnter,
523                        ],
524                        px,
525                        py,
526                    );
527                }
528            }
529        }
530    }
531
532    /// Helper to invoke registered event listeners of specified types on a single blueprint node.
533    pub(crate) fn dispatch_node_events(
534        &self,
535        bp: &NodeBlueprint,
536        layout: &LayoutNode,
537        event_types: &[strata_dom::EventType],
538        px: f32,
539        py: f32,
540    ) {
541        if let NodeBlueprint::Element { attributes, .. } = bp {
542            for attr in attributes {
543                if let strata_dom::Attribute::EventListener { event, handler } = attr {
544                    if event_types.contains(event) {
545                        let ev = self.create_mouse_event(
546                            *event,
547                            px,
548                            py,
549                            0,
550                            0,
551                            Some(&layout.geometry.border_box),
552                        );
553                        handler(ev);
554                    }
555                }
556            }
557        }
558    }
559
560    /// Checks whether any element along the index path has active hover styles (Tailwind or `<style>`) or boundary handlers.
561    pub fn node_path_has_hover_effects(blueprint: &NodeBlueprint, path: &[usize]) -> bool {
562        let stylesheets = Self::collect_stylesheets_from_blueprint(blueprint);
563        Self::node_path_has_hover_effects_with_sheets(blueprint, path, &stylesheets)
564    }
565
566    pub(crate) fn node_path_has_hover_effects_with_sheets(
567        blueprint: &NodeBlueprint,
568        path: &[usize],
569        stylesheets: &[std::sync::Arc<strata_style::StyleSheet>],
570    ) -> bool {
571        let mut path_nodes: Vec<&NodeBlueprint> = Vec::with_capacity(path.len() + 1);
572        let mut cur_bp = blueprint;
573        if Self::node_has_hover_effects(cur_bp) {
574            return true;
575        }
576        path_nodes.push(cur_bp);
577
578        for &idx in path {
579            match cur_bp {
580                NodeBlueprint::Element { children, .. } => {
581                    let mut flat = Vec::new();
582                    for c in children {
583                        Self::flatten_blueprints(c, &mut flat);
584                    }
585                    if idx >= flat.len() {
586                        break;
587                    }
588                    cur_bp = flat[idx];
589                }
590                NodeBlueprint::Fragment(children) => {
591                    let mut flat = Vec::new();
592                    for c in children {
593                        Self::flatten_blueprints(c, &mut flat);
594                    }
595                    if idx >= flat.len() {
596                        break;
597                    }
598                    cur_bp = flat[idx];
599                }
600                _ => break,
601            }
602            if Self::node_has_hover_effects(cur_bp) {
603                return true;
604            }
605            path_nodes.push(cur_bp);
606        }
607
608        if stylesheets.is_empty() {
609            return false;
610        }
611
612        Self::path_nodes_match_stylesheet_hover(&path_nodes, stylesheets)
613    }
614
615    /// Returns true if any element in `path_nodes` matches a `:hover`-bearing compound selector in `stylesheets`.
616    pub(crate) fn path_nodes_match_stylesheet_hover(
617        path_nodes: &[&NodeBlueprint],
618        stylesheets: &[std::sync::Arc<strata_style::StyleSheet>],
619    ) -> bool {
620        let compound_has_hover = |comp: &strata_style::selector::CompoundSelector| {
621            comp.parts.iter().any(|p| match p {
622                strata_style::selector::SelectorPart::PseudoClass(name) => {
623                    let n = name.trim().to_ascii_lowercase();
624                    n == "hover" || n.contains(":hover")
625                }
626                _ => false,
627            })
628        };
629
630        let probe_state = strata_style::selector::PseudoState {
631            is_hovered: true,
632            ..Default::default()
633        };
634        let probe_state_dark = strata_style::selector::PseudoState {
635            is_hovered: true,
636            is_dark: true,
637            ..Default::default()
638        };
639
640        for bp in path_nodes {
641            if let NodeBlueprint::Element {
642                tag,
643                classes,
644                attributes,
645                ..
646            } = bp
647            {
648                if Self::is_style_tag(tag) {
649                    continue;
650                }
651                let tag_str = Self::tag_as_str(tag);
652                let (class_vec, id_val, attr_vec) =
653                    Self::extract_element_selector_meta(classes, attributes);
654                for sheet in stylesheets {
655                    for rule in &sheet.rules {
656                        for sel in &rule.selectors {
657                            if !sel.has_any_hover_pseudo() {
658                                continue;
659                            }
660                            if compound_has_hover(&sel.target)
661                                && (sel.target.matches_with_context(
662                                    tag_str,
663                                    &class_vec,
664                                    id_val.as_deref(),
665                                    &attr_vec,
666                                    &probe_state,
667                                    &[],
668                                    Some(true),
669                                    Some(true),
670                                    &[],
671                                ) || sel.target.matches_with_context(
672                                    tag_str,
673                                    &class_vec,
674                                    id_val.as_deref(),
675                                    &attr_vec,
676                                    &probe_state_dark,
677                                    &[],
678                                    Some(true),
679                                    Some(true),
680                                    &[],
681                                ))
682                            {
683                                return true;
684                            }
685                            for (_, step_comp) in &sel.steps {
686                                if compound_has_hover(step_comp)
687                                    && (step_comp.matches_with_context(
688                                        tag_str,
689                                        &class_vec,
690                                        id_val.as_deref(),
691                                        &attr_vec,
692                                        &probe_state,
693                                        &[],
694                                        Some(true),
695                                        Some(true),
696                                        &[],
697                                    ) || step_comp.matches_with_context(
698                                        tag_str,
699                                        &class_vec,
700                                        id_val.as_deref(),
701                                        &attr_vec,
702                                        &probe_state_dark,
703                                        &[],
704                                        Some(true),
705                                        Some(true),
706                                        &[],
707                                    ))
708                                {
709                                    return true;
710                                }
711                            }
712                        }
713                    }
714                }
715            }
716        }
717        false
718    }
719
720    /// Returns true when `node` carries the Tailwind `"group"` class and any descendant uses `group-hover:`.
721    pub(crate) fn subtree_has_group_hover_effects(node: &NodeBlueprint) -> bool {
722        fn check(bp: &NodeBlueprint) -> bool {
723            match bp {
724                NodeBlueprint::Element {
725                    classes, children, ..
726                } => {
727                    let has_gh = classes.iter().any(|c| {
728                        strata_style::tailwind::tokenize_classes(c)
729                            .into_iter()
730                            .any(|tok| {
731                                let mut cur = tok;
732                                while let (Some(m), rest) =
733                                    strata_style::tailwind::split_modifier(cur)
734                                {
735                                    if m == "group-hover" {
736                                        return true;
737                                    }
738                                    cur = rest;
739                                }
740                                false
741                            })
742                    });
743                    has_gh || children.iter().any(check)
744                }
745                NodeBlueprint::Fragment(children) => children.iter().any(check),
746                _ => false,
747            }
748        }
749        match node {
750            NodeBlueprint::Element {
751                classes, children, ..
752            } if Self::classes_have_group_marker(classes) => children.iter().any(check),
753            _ => false,
754        }
755    }
756
757    /// Checks if a single blueprint node has hover utility classes (including chained modifiers like `dark:hover:*`),
758    /// `.group` descendants with `group-hover:*`, or boundary event listeners.
759    pub fn node_has_hover_effects(node: &NodeBlueprint) -> bool {
760        match node {
761            NodeBlueprint::Element {
762                classes,
763                attributes,
764                ..
765            } => {
766                let has_hover_class = classes.iter().any(|c| {
767                    strata_style::tailwind::tokenize_classes(c)
768                        .into_iter()
769                        .any(|tok| {
770                            let mut cur = tok;
771                            while let (Some(m), rest) = strata_style::tailwind::split_modifier(cur)
772                            {
773                                if m == "hover" {
774                                    return true;
775                                }
776                                cur = rest;
777                            }
778                            false
779                        })
780                });
781                if has_hover_class {
782                    return true;
783                }
784                if Self::subtree_has_group_hover_effects(node) {
785                    return true;
786                }
787                attributes.iter().any(|attr| match attr {
788                    strata_dom::Attribute::EventListener { event, .. } => matches!(
789                        event,
790                        strata_dom::EventType::MouseEnter
791                            | strata_dom::EventType::MouseLeave
792                            | strata_dom::EventType::MouseOver
793                            | strata_dom::EventType::MouseOut
794                    ),
795                    _ => false,
796                })
797            }
798            _ => false,
799        }
800    }
801
802    /// Continuously updates hover state from pointer coordinates.
803    /// Dispatches boundary events and rebuilds layout tree if the hovered element changed and has hover effects.
804    /// Returns true if the hover target changed and an interactive frame rebuild is required.
805    pub fn update_hover(&mut self, px: f32, py: f32) -> bool {
806        self.last_mouse_pos = (px, py);
807        let new_path = Self::hit_test_node_path(&self.root_blueprint, &self.layout_root, px, py);
808        if new_path == self.current_hover_path {
809            if self.hover_tooltip_since.is_some() && !self.hover_tooltip_visible {
810                self.hover_tooltip_anchor = (px, py);
811            }
812            return false;
813        }
814
815        let old_path = self.current_hover_path.take();
816        self.current_hover_path = new_path.clone();
817
818        self.dispatch_boundary_events(old_path.as_deref(), new_path.as_deref(), px, py);
819        let tooltip_changed = self.sync_hover_tooltip(px, py);
820
821        let old_has_effects = old_path.as_deref().is_some_and(|p| {
822            Self::node_path_has_hover_effects_with_index(
823                &self.root_blueprint,
824                p,
825                &self.cached_stylesheets,
826                &self.stylesheet_index,
827            )
828        });
829        let new_has_effects = new_path.as_deref().is_some_and(|p| {
830            Self::node_path_has_hover_effects_with_index(
831                &self.root_blueprint,
832                p,
833                &self.cached_stylesheets,
834                &self.stylesheet_index,
835            )
836        });
837
838        if old_has_effects || new_has_effects {
839            let has_listeners = old_path
840                .as_deref()
841                .is_some_and(|p| Self::path_has_hover_listeners(&self.root_blueprint, p))
842                || new_path
843                    .as_deref()
844                    .is_some_and(|p| Self::path_has_hover_listeners(&self.root_blueprint, p));
845            let layout_required = old_path.as_deref().is_some_and(|p| {
846                Self::path_hover_affects_layout_with_sheets(
847                    &self.root_blueprint,
848                    p,
849                    &self.cached_stylesheets,
850                    &self.stylesheet_index,
851                )
852            }) || new_path.as_deref().is_some_and(|p| {
853                Self::path_hover_affects_layout_with_sheets(
854                    &self.root_blueprint,
855                    p,
856                    &self.cached_stylesheets,
857                    &self.stylesheet_index,
858                )
859            });
860            if layout_required || has_listeners {
861                self.hover_paint_only = false;
862                self.last_hover_fast_path_used = false;
863                let reason = if layout_required {
864                    "HoverAffectsLayout"
865                } else {
866                    "HoverListenersPresent"
867                };
868                self.last_hover_fast_path_bailout = Some(reason.to_string());
869                self.last_rebuild_reason = RebuildReason::HoverFastPathFailed(reason.to_string());
870                self.rebuild_layout_tree();
871            } else {
872                self.hover_paint_only = true;
873                let hover_start = std::time::Instant::now();
874                let fast_ok = self.restyle_hover_subtrees_fast(
875                    if old_has_effects {
876                        old_path.as_deref()
877                    } else {
878                        None
879                    },
880                    if new_has_effects {
881                        new_path.as_deref()
882                    } else {
883                        None
884                    },
885                );
886                self.last_hover_fast_path_used = fast_ok;
887                if fast_ok {
888                    self.last_hover_fast_path_bailout = None;
889                    self.last_rebuild_reason = RebuildReason::HoverFastPath;
890                    self.frame_profile.style_cascade += hover_start.elapsed();
891                } else {
892                    if let Some(ref reason) = self.last_hover_fast_path_bailout {
893                        self.last_rebuild_reason =
894                            RebuildReason::HoverFastPathFailed(reason.clone());
895                    }
896                    self.restyle_for_hover_paint();
897                    self.frame_profile.style_cascade += hover_start.elapsed();
898                }
899                if perf_logging_enabled() {
900                    perf_log_ms(
901                        "hover_repaint",
902                        hover_start,
903                        if fast_ok {
904                            "paint-only hover (fast)"
905                        } else {
906                            "paint-only hover (full)"
907                        },
908                    );
909                }
910            }
911            true
912        } else if tooltip_changed {
913            self.hover_paint_only = true;
914            self.compile_display_list();
915            true
916        } else {
917            self.hover_paint_only = false;
918            false
919        }
920    }
921
922    /// Re-applies hover/active styles, synchronizes CSS transitions, and recompiles paint commands without re-running layout when paint-only.
923    ///
924    /// Paint-only hover variants (`hover:bg-*`, `hover:text-*`, `hover:underline`,
925    /// shadows, opacity, `<style>` `:hover` color/background rules) do not change box geometry.
926    /// Rebuilding the tree carries the new styles; the previous geometry, line boxes, and inline item streams
927    /// are transplanted so the display list can be recompiled immediately.
928    pub fn restyle_for_hover_paint(&mut self) {
929        self.capture_previous_node_sizes();
930        let ctx = self.interaction_context();
931        let new_tree = Self::build_layout_tree_with_interaction(&self.root_blueprint, &ctx);
932        let mut previous = std::mem::replace(&mut self.layout_root, new_tree);
933        let transplanted = Self::transplant_layout_state(&mut previous, &mut self.layout_root);
934        let now_ms = self.runtime_start_epoch.elapsed().as_secs_f64() * 1000.0;
935        self.sync_tree_animations(now_ms);
936        let mut layout_node_ids = self.transition_manager.layout_affecting_node_ids();
937        layout_node_ids.extend(self.animation_manager.layout_affecting_node_ids());
938        let has_layout_transition = self.transition_manager.has_layout_affecting_transitions()
939            || self.animation_manager.has_layout_affecting_animations();
940        if transplanted && !has_layout_transition {
941            strata_layout::box_model::refresh_inline_fragment_styles(&mut self.layout_root);
942        } else {
943            self.applied_scroll_offsets.clear();
944            self.applied_portal_offsets.clear();
945            if has_layout_transition {
946                self.invalidate_layout_for_node_ids(&layout_node_ids);
947            }
948            let localized_layout = if let Some(ref path) = self.current_hover_path {
949                self.layout_root.compute_subgrid_or_boundary_layout(path)
950            } else {
951                false
952            };
953            if !localized_layout {
954                self.layout_root
955                    .compute_layout(self.viewport_width, self.viewport_height);
956            }
957            Self::sync_layout_to_ir(&self.layout_root, &mut self.ir_graph);
958            self.layout_computations += 1;
959            self.apply_viewport_clamps();
960            self.apply_scroll_offsets();
961        }
962        self.sync_active_input_layout();
963        self.compile_display_list();
964    }
965
966    /// Returns true if a single blueprint element matches any `:hover` rule in `stylesheets`
967    /// (fast-rejected in O(1) via `index`'s Bloom filter).
968    pub(crate) fn single_node_matches_stylesheet_hover(
969        bp: &NodeBlueprint,
970        stylesheets: &[std::sync::Arc<strata_style::StyleSheet>],
971        index: &StylesheetSelectorIndex,
972    ) -> bool {
973        if stylesheets.is_empty() || !index.has_any_hover_rule {
974            return false;
975        }
976        let NodeBlueprint::Element {
977            tag,
978            classes,
979            attributes,
980            ..
981        } = bp
982        else {
983            return false;
984        };
985        if Self::is_style_tag(tag) {
986            return false;
987        }
988        let tag_str = Self::tag_as_str(tag);
989        let (class_vec, id_val, _) = Self::extract_element_selector_meta(classes, attributes);
990        if !index.node_may_match_hover(tag_str, id_val.as_deref(), &class_vec) {
991            return false;
992        }
993        Self::path_nodes_match_stylesheet_hover(&[bp], stylesheets)
994    }
995
996    /// Bloom-filter-accelerated variant of [`Self::node_path_has_hover_effects_with_sheets`].
997    pub(crate) fn node_path_has_hover_effects_with_index(
998        blueprint: &NodeBlueprint,
999        path: &[usize],
1000        stylesheets: &[std::sync::Arc<strata_style::StyleSheet>],
1001        index: &StylesheetSelectorIndex,
1002    ) -> bool {
1003        let mut path_nodes: Vec<&NodeBlueprint> = Vec::with_capacity(path.len() + 1);
1004        let mut cur_bp = blueprint;
1005        if Self::node_has_hover_effects(cur_bp) {
1006            return true;
1007        }
1008        path_nodes.push(cur_bp);
1009
1010        for &idx in path {
1011            match cur_bp {
1012                NodeBlueprint::Element { children, .. } | NodeBlueprint::Fragment(children) => {
1013                    let mut flat = Vec::new();
1014                    for c in children {
1015                        Self::flatten_blueprints(c, &mut flat);
1016                    }
1017                    if idx >= flat.len() {
1018                        break;
1019                    }
1020                    cur_bp = flat[idx];
1021                }
1022                _ => break,
1023            }
1024            if Self::node_has_hover_effects(cur_bp) {
1025                return true;
1026            }
1027            path_nodes.push(cur_bp);
1028        }
1029
1030        if stylesheets.is_empty() || !index.has_any_hover_rule {
1031            return false;
1032        }
1033
1034        for bp in &path_nodes {
1035            if Self::single_node_matches_stylesheet_hover(bp, stylesheets, index) {
1036                return true;
1037            }
1038        }
1039        false
1040    }
1041
1042    /// Fast paint-only hover restyle that updates only the diverging subtrees along
1043    /// `old_path` and `new_path`, supporting static `<style>` sheets (`:root` variables,
1044    /// `.class:hover`, `.parent:hover .child`), `group-hover:`, and unrelated active transitions.
1045    pub(crate) fn restyle_hover_subtrees_fast(
1046        &mut self,
1047        old_path: Option<&[usize]>,
1048        new_path: Option<&[usize]>,
1049    ) -> bool {
1050        if Self::node_has_hover_effects(&self.root_blueprint)
1051            || Self::single_node_matches_stylesheet_hover(
1052                &self.root_blueprint,
1053                &self.cached_stylesheets,
1054                &self.stylesheet_index,
1055            )
1056        {
1057            self.last_hover_fast_path_bailout = Some("RootHasHoverEffects".to_string());
1058            return false;
1059        }
1060        if self.stylesheet_index.has_sibling_hover_rule {
1061            self.last_hover_fast_path_bailout =
1062                Some("StylesheetSiblingHoverCombinator".to_string());
1063            return false;
1064        }
1065
1066        fn subtree_has_animations(node: &LayoutNode) -> bool {
1067            if !node.style.animations.is_empty() {
1068                return true;
1069            }
1070            node.children.iter().any(subtree_has_animations)
1071        }
1072
1073        fn subtree_has_transitions(node: &LayoutNode) -> bool {
1074            if !node.style.transitions.is_empty() || node.active_transitions {
1075                return true;
1076            }
1077            node.children.iter().any(subtree_has_transitions)
1078        }
1079
1080        #[allow(clippy::too_many_arguments)]
1081        fn restyle_one_path(
1082            bp_root: &NodeBlueprint,
1083            layout_root: &mut LayoutNode,
1084            target_path: &[usize],
1085            ctx: &InteractionContext,
1086            stylesheets: &[std::sync::Arc<strata_style::StyleSheet>],
1087            sheet_index: &StylesheetSelectorIndex,
1088            path_node_ids: &std::collections::HashMap<Vec<usize>, u64>,
1089            base_node_styles: &std::collections::HashMap<u64, ComputedStyle>,
1090            restyled_paths: &mut Vec<(Vec<usize>, bool)>,
1091            bailout: &mut Option<String>,
1092        ) -> bool {
1093            let mut cur_bp = bp_root;
1094            let mut cur_layout = layout_root;
1095            let mut prefix = Vec::with_capacity(target_path.len());
1096            let mut ancestor_stack: Vec<(&NodeBlueprint, (bool, bool, bool))> =
1097                Vec::with_capacity(target_path.len() + 1);
1098            let mut group_state = (false, false, false);
1099
1100            for &idx in target_path {
1101                // Push current node onto ancestor stack before descending to its child.
1102                let next_group_state = if let NodeBlueprint::Element { classes, .. } = cur_bp {
1103                    if AppRuntime::classes_have_group_marker(classes) {
1104                        let self_hovered =
1105                            ctx.hovered_path.is_some_and(|h| h.starts_with(&prefix));
1106                        let self_focused =
1107                            ctx.focused_path.is_some_and(|f| f.starts_with(&prefix));
1108                        let self_active = self_hovered && ctx.is_mouse_down;
1109                        (
1110                            group_state.0 || self_hovered,
1111                            group_state.1 || self_focused,
1112                            group_state.2 || self_active,
1113                        )
1114                    } else {
1115                        group_state
1116                    }
1117                } else {
1118                    group_state
1119                };
1120                ancestor_stack.push((cur_bp, group_state));
1121
1122                let mut flat = Vec::new();
1123                match cur_bp {
1124                    NodeBlueprint::Element { children, .. } | NodeBlueprint::Fragment(children) => {
1125                        for c in children {
1126                            AppRuntime::flatten_blueprints(c, &mut flat);
1127                        }
1128                    }
1129                    _ => {
1130                        *bailout = Some("PathNotElement".to_string());
1131                        return false;
1132                    }
1133                }
1134                if idx >= flat.len() || idx >= cur_layout.children.len() {
1135                    *bailout = Some("PathIndexOutOfBounds".to_string());
1136                    return false;
1137                }
1138                let child_bp = flat[idx];
1139                let parent_base_style = path_node_ids
1140                    .get(&prefix)
1141                    .and_then(|id| base_node_styles.get(id))
1142                    .cloned();
1143                prefix.push(idx);
1144
1145                // If an ancestor of this path was already restyled in this pass (e.g. shared
1146                // hover ancestor between old_path and new_path), we are already up to date.
1147                if restyled_paths
1148                    .iter()
1149                    .any(|(rp, _)| prefix.starts_with(rp.as_slice()))
1150                {
1151                    return true;
1152                }
1153
1154                let node_has_hover = AppRuntime::node_has_hover_effects(child_bp)
1155                    || AppRuntime::single_node_matches_stylesheet_hover(
1156                        child_bp,
1157                        stylesheets,
1158                        sheet_index,
1159                    );
1160                if node_has_hover {
1161                    let parent_style =
1162                        parent_base_style.unwrap_or_else(|| cur_layout.style.clone());
1163                    let child_layout = &mut cur_layout.children[idx];
1164                    if subtree_has_animations(child_layout) {
1165                        *bailout = Some("SubtreeHasKeyframeAnimation".to_string());
1166                        return false;
1167                    }
1168                    let has_trans = subtree_has_transitions(child_layout);
1169                    let mut ancestors_meta = AppRuntime::materialize_ancestor_metas(
1170                        &ancestor_stack,
1171                        &prefix,
1172                        ctx,
1173                        stylesheets,
1174                        sheet_index,
1175                    );
1176                    let preceding_sibs = if !stylesheets.is_empty()
1177                        && sheet_index.has_sibling_combinator_or_positional_rules
1178                        && idx > 0
1179                    {
1180                        let parent_path = &prefix[..prefix.len() - 1];
1181                        let mut sib_path = Vec::with_capacity(prefix.len());
1182                        sib_path.extend_from_slice(parent_path);
1183                        sib_path.push(0);
1184                        let mut sibs = Vec::with_capacity(idx);
1185                        for (j, sib_bp) in flat[..idx].iter().enumerate() {
1186                            if let Some(last) = sib_path.last_mut() {
1187                                *last = j;
1188                            }
1189                            if let Some(meta) = AppRuntime::materialize_cascade_meta(
1190                                sib_bp,
1191                                &sib_path,
1192                                ctx,
1193                                next_group_state,
1194                            ) {
1195                                sibs.push(meta);
1196                            }
1197                        }
1198                        sibs
1199                    } else {
1200                        Vec::new()
1201                    };
1202                    let is_last_elem = flat.iter().rposition(|bp| {
1203                        matches!(bp, NodeBlueprint::Element { tag, .. } if !AppRuntime::is_style_tag(tag))
1204                    }) == Some(idx);
1205
1206                    let mut rebuilt = AppRuntime::build_layout_tree_full(
1207                        child_bp,
1208                        Some(&parent_style),
1209                        &mut prefix,
1210                        ctx,
1211                        stylesheets,
1212                        &mut ancestors_meta,
1213                        &preceding_sibs,
1214                        is_last_elem,
1215                        next_group_state,
1216                    );
1217                    if !AppRuntime::transplant_layout_state(child_layout, &mut rebuilt) {
1218                        *bailout = Some("TransplantMismatch".to_string());
1219                        return false;
1220                    }
1221                    strata_layout::box_model::refresh_inline_fragment_styles(&mut rebuilt);
1222                    *child_layout = rebuilt;
1223                    restyled_paths.push((prefix.clone(), has_trans));
1224                    return true;
1225                }
1226                cur_bp = child_bp;
1227                cur_layout = &mut cur_layout.children[idx];
1228                group_state = next_group_state;
1229            }
1230            true
1231        }
1232
1233        let hovered_owned = self.current_hover_path.clone();
1234        let focused_owned = self.current_focus_path.clone();
1235        let ctx = InteractionContext {
1236            hovered_path: hovered_owned.as_deref(),
1237            focused_path: focused_owned.as_deref(),
1238            is_mouse_down: self.is_mouse_down,
1239            is_dark_mode: self.is_dark_mode,
1240        };
1241        let mut restyled_paths: Vec<(Vec<usize>, bool)> = Vec::new();
1242        let mut bailout: Option<String> = None;
1243
1244        if let Some(p) = old_path {
1245            if !restyle_one_path(
1246                &self.root_blueprint,
1247                &mut self.layout_root,
1248                p,
1249                &ctx,
1250                &self.cached_stylesheets,
1251                &self.stylesheet_index,
1252                &self.path_node_ids,
1253                &self.base_node_styles,
1254                &mut restyled_paths,
1255                &mut bailout,
1256            ) {
1257                self.last_hover_fast_path_bailout = bailout;
1258                return false;
1259            }
1260        }
1261        if let Some(p) = new_path {
1262            if !restyle_one_path(
1263                &self.root_blueprint,
1264                &mut self.layout_root,
1265                p,
1266                &ctx,
1267                &self.cached_stylesheets,
1268                &self.stylesheet_index,
1269                &self.path_node_ids,
1270                &self.base_node_styles,
1271                &mut restyled_paths,
1272                &mut bailout,
1273            ) {
1274                self.last_hover_fast_path_bailout = bailout;
1275                return false;
1276            }
1277        }
1278
1279        // Sync paint-only transitions strictly on restyled subtrees so hover transitions
1280        // animate smoothly without full-tree rebuilds or disturbing unrelated active transitions.
1281        let now_ms = self.runtime_start_epoch.elapsed().as_secs_f64() * 1000.0;
1282        let anims_active = self.had_active_animations || self.has_active_animations();
1283        for (path, has_trans) in &restyled_paths {
1284            if *has_trans {
1285                self.sync_subtree_paint_transitions(path, now_ms);
1286            } else if anims_active {
1287                self.sync_subtree_base_styles(path);
1288            }
1289        }
1290
1291        self.last_hover_fast_path_bailout = None;
1292        self.sync_active_input_layout();
1293        self.compile_display_list();
1294        true
1295    }
1296
1297    /// Returns `true` when the currently hovered path (or any stylesheet rule)
1298    /// can visually respond to `:active` state changes on `MouseDown` / `MouseUp`.
1299    pub(crate) fn path_has_active_styles(&self) -> bool {
1300        let Some(ref path) = self.current_hover_path else {
1301            return false;
1302        };
1303        let mut cur_bp = &self.root_blueprint;
1304        let has_active_class = |bp: &NodeBlueprint| -> bool {
1305            if let NodeBlueprint::Element { classes, .. } = bp {
1306                classes
1307                    .iter()
1308                    .any(|c| c.split_whitespace().any(|tok| tok.contains("active:")))
1309            } else {
1310                false
1311            }
1312        };
1313        if has_active_class(cur_bp) {
1314            return true;
1315        }
1316        for &idx in path {
1317            let mut flat = Vec::new();
1318            match cur_bp {
1319                NodeBlueprint::Element { children, .. } | NodeBlueprint::Fragment(children) => {
1320                    for c in children {
1321                        Self::flatten_blueprints(c, &mut flat);
1322                    }
1323                }
1324                _ => break,
1325            }
1326            if idx >= flat.len() {
1327                break;
1328            }
1329            cur_bp = flat[idx];
1330            if has_active_class(cur_bp) {
1331                return true;
1332            }
1333        }
1334        for sheet in &self.cached_stylesheets {
1335            for rule in &sheet.rules {
1336                for sel in &rule.selectors {
1337                    let has_active_pseudo = sel.target.parts.iter().any(|p| {
1338                        matches!(
1339                            p,
1340                            strata_style::selector::SelectorPart::PseudoClass(name)
1341                                if name.eq_ignore_ascii_case("active")
1342                        )
1343                    });
1344                    if has_active_pseudo {
1345                        return true;
1346                    }
1347                }
1348            }
1349        }
1350        false
1351    }
1352
1353    /// Re-applies `:active` styles only when the hovered path can visually react
1354    /// to pointer press/release, returning `true` if a repaint is needed.
1355    pub fn restyle_for_active_change(&mut self) -> bool {
1356        if !self.path_has_active_styles() {
1357            return false;
1358        }
1359        self.restyle_for_hover_paint();
1360        true
1361    }
1362
1363    /// Copies resolved geometry and text state from a previous tree into a newly styled tree.
1364    pub(crate) fn transplant_layout_state(
1365        previous: &mut LayoutNode,
1366        next: &mut LayoutNode,
1367    ) -> bool {
1368        if previous.children.len() != next.children.len() {
1369            return false;
1370        }
1371        next.geometry = previous.geometry;
1372        next.line_boxes = std::mem::take(&mut previous.line_boxes);
1373        next.inline_items = std::mem::take(&mut previous.inline_items);
1374        next.layout_cache = previous.layout_cache;
1375        next.measure_cache = previous.measure_cache;
1376        next.intrinsic_cache = previous.intrinsic_cache.clone();
1377        next.last_child_layout_content = previous.last_child_layout_content;
1378        next.children_layout_clean = previous.children_layout_clean;
1379        next.last_preserved_box = previous.last_preserved_box;
1380        next.subtree_hit_flags = previous.subtree_hit_flags;
1381        next.subtree_bounds = previous.subtree_bounds;
1382        for (prev_child, next_child) in previous.children.iter_mut().zip(next.children.iter_mut()) {
1383            if !Self::transplant_layout_state(prev_child, next_child) {
1384                return false;
1385            }
1386        }
1387        true
1388    }
1389
1390    /// Returns true when any element on the path has mouse boundary listeners.
1391    pub(crate) fn path_has_hover_listeners(blueprint: &NodeBlueprint, path: &[usize]) -> bool {
1392        let mut current = blueprint;
1393        if Self::node_has_hover_listeners(current) {
1394            return true;
1395        }
1396        for &idx in path {
1397            let mut flat = Vec::new();
1398            match current {
1399                NodeBlueprint::Element { children, .. } | NodeBlueprint::Fragment(children) => {
1400                    for child in children {
1401                        Self::flatten_blueprints(child, &mut flat);
1402                    }
1403                }
1404                _ => return false,
1405            }
1406            if idx >= flat.len() {
1407                return false;
1408            }
1409            current = flat[idx];
1410            if Self::node_has_hover_listeners(current) {
1411                return true;
1412            }
1413        }
1414        false
1415    }
1416
1417    pub(crate) fn node_has_hover_listeners(node: &NodeBlueprint) -> bool {
1418        match node {
1419            NodeBlueprint::Element { attributes, .. } => attributes.iter().any(|attr| match attr {
1420                strata_dom::Attribute::EventListener { event, .. } => matches!(
1421                    event,
1422                    strata_dom::EventType::MouseEnter
1423                        | strata_dom::EventType::MouseLeave
1424                        | strata_dom::EventType::MouseOver
1425                        | strata_dom::EventType::MouseOut
1426                ),
1427                _ => false,
1428            }),
1429            _ => false,
1430        }
1431    }
1432
1433    /// Clears any active hover state when the pointer departs the window surface.
1434    pub fn clear_hover(&mut self) -> bool {
1435        if self.current_hover_path.is_none() {
1436            if self.dismiss_hover_tooltip() {
1437                self.hover_paint_only = true;
1438                self.compile_display_list();
1439                return true;
1440            }
1441            return false;
1442        }
1443        let old_path = self.current_hover_path.take();
1444        self.dispatch_boundary_events(
1445            old_path.as_deref(),
1446            None,
1447            self.last_mouse_pos.0,
1448            self.last_mouse_pos.1,
1449        );
1450        let tooltip_dismissed = self.dismiss_hover_tooltip();
1451        let old_has_effects = old_path.as_deref().is_some_and(|p| {
1452            Self::node_path_has_hover_effects_with_index(
1453                &self.root_blueprint,
1454                p,
1455                &self.cached_stylesheets,
1456                &self.stylesheet_index,
1457            )
1458        });
1459        if old_has_effects {
1460            let has_listeners = old_path
1461                .as_deref()
1462                .is_some_and(|p| Self::path_has_hover_listeners(&self.root_blueprint, p));
1463            let layout_required = old_path.as_deref().is_some_and(|p| {
1464                Self::path_hover_affects_layout_with_sheets(
1465                    &self.root_blueprint,
1466                    p,
1467                    &self.cached_stylesheets,
1468                    &self.stylesheet_index,
1469                )
1470            });
1471            if layout_required || has_listeners {
1472                self.hover_paint_only = false;
1473                self.last_hover_fast_path_used = false;
1474                self.rebuild_layout_tree();
1475            } else {
1476                self.hover_paint_only = true;
1477                let hover_start = std::time::Instant::now();
1478                let fast_ok = self.restyle_hover_subtrees_fast(old_path.as_deref(), None);
1479                self.last_hover_fast_path_used = fast_ok;
1480                if !fast_ok {
1481                    self.restyle_for_hover_paint();
1482                }
1483                self.frame_profile.style_cascade += hover_start.elapsed();
1484                if perf_logging_enabled() {
1485                    perf_log_ms(
1486                        "hover_repaint",
1487                        hover_start,
1488                        if fast_ok {
1489                            "paint-only clear_hover (fast)"
1490                        } else {
1491                            "paint-only clear_hover (full)"
1492                        },
1493                    );
1494                }
1495            }
1496            true
1497        } else if tooltip_dismissed {
1498            self.hover_paint_only = true;
1499            self.compile_display_list();
1500            true
1501        } else {
1502            self.hover_paint_only = false;
1503            false
1504        }
1505    }
1506
1507    /// Resolves the nearest native tooltip text along `path` (deepest hovered element up to root).
1508    /// Prefers non-empty `title` attributes, falling back to non-empty `alt` attributes on
1509    /// `<button>` and `<img>` elements when no `title` is present along the hovered chain.
1510    pub(crate) fn resolve_hover_tooltip(
1511        blueprint: &NodeBlueprint,
1512        path: &[usize],
1513    ) -> Option<(Vec<usize>, String)> {
1514        let mut chain: Vec<(Vec<usize>, &NodeBlueprint)> = Vec::with_capacity(path.len() + 1);
1515        let mut current = blueprint;
1516        let mut prefix = Vec::with_capacity(path.len());
1517        chain.push((prefix.clone(), current));
1518        for &idx in path {
1519            let mut flat = Vec::new();
1520            match current {
1521                NodeBlueprint::Element { children, .. } | NodeBlueprint::Fragment(children) => {
1522                    for child in children {
1523                        Self::flatten_blueprints(child, &mut flat);
1524                    }
1525                }
1526                _ => break,
1527            }
1528            if idx >= flat.len() {
1529                break;
1530            }
1531            current = flat[idx];
1532            prefix.push(idx);
1533            chain.push((prefix.clone(), current));
1534        }
1535
1536        // Pass 1: explicit non-empty `title` attribute (deepest wins).
1537        for (node_path, node) in chain.iter().rev() {
1538            if let NodeBlueprint::Element { attributes, .. } = node {
1539                for attr in attributes {
1540                    if let strata_dom::Attribute::Property { key, value } = attr {
1541                        if key.eq_ignore_ascii_case("title") {
1542                            let trimmed = value.trim();
1543                            if !trimmed.is_empty() {
1544                                return Some((node_path.clone(), trimmed.to_string()));
1545                            }
1546                        }
1547                    }
1548                }
1549            }
1550        }
1551
1552        // Pass 2: fallback to non-empty `alt` attribute on `<button>` or `<img>`.
1553        for (node_path, node) in chain.iter().rev() {
1554            if let NodeBlueprint::Element {
1555                tag, attributes, ..
1556            } = node
1557            {
1558                let supports_alt_tooltip = match tag {
1559                    strata_dom::Tag::Img | strata_dom::Tag::Button => true,
1560                    strata_dom::Tag::Custom(name) => {
1561                        name.eq_ignore_ascii_case("img") || name.eq_ignore_ascii_case("button")
1562                    }
1563                    _ => false,
1564                };
1565                if !supports_alt_tooltip {
1566                    continue;
1567                }
1568                for attr in attributes {
1569                    if let strata_dom::Attribute::Property { key, value } = attr {
1570                        if key.eq_ignore_ascii_case("alt") {
1571                            let trimmed = value.trim();
1572                            if !trimmed.is_empty() {
1573                                return Some((node_path.clone(), trimmed.to_string()));
1574                            }
1575                        }
1576                    }
1577                }
1578            }
1579        }
1580
1581        None
1582    }
1583
1584    /// Synchronizes hover tooltip state with `self.current_hover_path`.
1585    /// Returns `true` when an active visible tooltip was hidden or changed and requires repainting.
1586    pub(crate) fn sync_hover_tooltip(&mut self, px: f32, py: f32) -> bool {
1587        let resolved = self
1588            .current_hover_path
1589            .as_deref()
1590            .and_then(|p| Self::resolve_hover_tooltip(&self.root_blueprint, p));
1591
1592        match resolved {
1593            Some((owner_path, text)) => {
1594                if self.hover_tooltip_path.as_ref() == Some(&owner_path)
1595                    && self.hover_tooltip_text.as_deref() == Some(text.as_str())
1596                {
1597                    if self.hover_tooltip_since.is_some() && !self.hover_tooltip_visible {
1598                        self.hover_tooltip_anchor = (px, py);
1599                    }
1600                    false
1601                } else {
1602                    let was_visible = self.hover_tooltip_visible;
1603                    self.hover_tooltip_path = Some(owner_path);
1604                    self.hover_tooltip_text = Some(text);
1605                    self.hover_tooltip_anchor = (px, py);
1606                    self.hover_tooltip_since = if self.is_mouse_down {
1607                        None
1608                    } else {
1609                        Some(std::time::Instant::now())
1610                    };
1611                    self.hover_tooltip_visible = false;
1612                    was_visible
1613                }
1614            }
1615            None => self.dismiss_hover_tooltip(),
1616        }
1617    }
1618
1619    /// Re-validates the active hover tooltip after `root_blueprint` is replaced by `update_view`.
1620    pub(crate) fn refresh_hover_tooltip_after_view_update(&mut self) {
1621        let Some(ref path) = self.current_hover_path else {
1622            self.dismiss_hover_tooltip();
1623            return;
1624        };
1625        match Self::resolve_hover_tooltip(&self.root_blueprint, path) {
1626            Some((owner_path, text)) => {
1627                if self.hover_tooltip_path.as_ref() == Some(&owner_path) {
1628                    self.hover_tooltip_text = Some(text);
1629                } else {
1630                    self.hover_tooltip_path = Some(owner_path);
1631                    self.hover_tooltip_text = Some(text);
1632                    self.hover_tooltip_anchor = self.last_mouse_pos;
1633                    self.hover_tooltip_since = if self.is_mouse_down {
1634                        None
1635                    } else {
1636                        Some(std::time::Instant::now())
1637                    };
1638                    self.hover_tooltip_visible = false;
1639                }
1640            }
1641            None => {
1642                self.dismiss_hover_tooltip();
1643            }
1644        }
1645    }
1646
1647    /// Clears all pending/visible native hover tooltip state.
1648    /// Returns `true` if a visible tooltip was dismissed.
1649    pub fn dismiss_hover_tooltip(&mut self) -> bool {
1650        let was_visible = self.hover_tooltip_visible;
1651        self.hover_tooltip_text = None;
1652        self.hover_tooltip_path = None;
1653        self.hover_tooltip_since = None;
1654        self.hover_tooltip_visible = false;
1655        was_visible
1656    }
1657
1658    /// Dismisses any visible or pending native hover tooltip and recompiles the display list if
1659    /// the tooltip was visible on screen.
1660    pub fn dismiss_hover_tooltip_and_repaint(&mut self) -> bool {
1661        let was_visible = self.hover_tooltip_visible;
1662        self.hover_tooltip_since = None;
1663        self.hover_tooltip_visible = false;
1664        if was_visible {
1665            self.paint_dirty = true;
1666            self.compile_display_list();
1667        }
1668        was_visible
1669    }
1670
1671    /// Returns the remaining duration until a pending native hover tooltip should appear.
1672    pub fn next_hover_tooltip_due_in(&self) -> Option<std::time::Duration> {
1673        if self.hover_tooltip_visible || self.is_mouse_down {
1674            return None;
1675        }
1676        let (_, Some(since)) = (&self.hover_tooltip_text, self.hover_tooltip_since) else {
1677            return None;
1678        };
1679        Some(self.hover_tooltip_delay.saturating_sub(since.elapsed()))
1680    }
1681
1682    /// Advances the native hover tooltip dwell timer. Returns `true` when the tooltip transitions
1683    /// to visible and updates the display list.
1684    pub fn poll_hover_tooltip(&mut self) -> bool {
1685        if self.hover_tooltip_visible || self.is_mouse_down {
1686            return false;
1687        }
1688        let (Some(_), Some(since)) = (&self.hover_tooltip_text, self.hover_tooltip_since) else {
1689            return false;
1690        };
1691        if since.elapsed() < self.hover_tooltip_delay {
1692            return false;
1693        }
1694        self.hover_tooltip_visible = true;
1695        self.paint_dirty = true;
1696        self.compile_display_list();
1697        true
1698    }
1699
1700    /// Appends native hover tooltip draw commands on top of the compiled display list when active.
1701    pub fn render_hover_tooltip(&mut self) {
1702        if !self.hover_tooltip_visible {
1703            return;
1704        }
1705        let Some(ref text) = self.hover_tooltip_text else {
1706            return;
1707        };
1708        if text.is_empty() || self.viewport_width <= 0.0 || self.viewport_height <= 0.0 {
1709            return;
1710        }
1711
1712        let style = self.hover_tooltip_style;
1713        let font_size = style.font_size.max(6.0);
1714        let line_height = style.line_height.max(1.0);
1715        let font_family = strata_primitives::AtomId::FONT_SANS;
1716        let font_weight = strata_style::types::FontWeight::Normal;
1717        let pad_x = style.padding_x.max(0.0);
1718        let pad_y = style.padding_y.max(0.0);
1719        let margin = 6.0_f32;
1720        let max_allowed_w = style.max_width.max(24.0);
1721        let max_text_w = (self.viewport_width - pad_x * 2.0 - margin * 2.0)
1722            .clamp(24.0_f32.min(max_allowed_w), max_allowed_w);
1723
1724        let (tw, th) = strata_layout::measure_text_bounds_styled_with_family(
1725            text,
1726            font_size,
1727            line_height,
1728            Some(max_text_w),
1729            false,
1730            font_family,
1731            font_weight,
1732            strata_style::types::FontStyle::Normal,
1733        );
1734        let text_w = tw.max(12.0).min(max_text_w);
1735        let text_h = th.max(font_size * line_height);
1736        let box_w = (text_w + pad_x * 2.0)
1737            .ceil()
1738            .min((self.viewport_width - margin * 2.0).max(24.0));
1739        let box_h = (text_h + pad_y * 2.0)
1740            .ceil()
1741            .min((self.viewport_height - margin * 2.0).max(22.0));
1742
1743        let (ax, ay) = self.hover_tooltip_anchor;
1744        let mut x = ax + style.cursor_offset_x;
1745        let mut y = ay + style.cursor_offset_y;
1746        if x + box_w > self.viewport_width - margin {
1747            x = (self.viewport_width - margin - box_w).max(margin);
1748        }
1749        if y + box_h > self.viewport_height - margin {
1750            y = (ay - box_h - 10.0).max(margin);
1751        }
1752        x = x.max(margin);
1753        y = y.max(margin);
1754
1755        let bounds = strata_layout::Rect::new(x, y, box_w, box_h);
1756        let radius = strata_style::types::BorderRadius::all(style.corner_radius.max(0.0));
1757
1758        if style.shadow_color.a > 0 {
1759            self.display_list
1760                .push(strata_render::compositor::DrawCommand::DrawShadow {
1761                    bounds,
1762                    shadow: strata_style::types::BoxShadow {
1763                        offset_x: 0.0,
1764                        offset_y: 4.0,
1765                        blur_radius: 12.0,
1766                        spread_radius: 0.0,
1767                        color: style.shadow_color,
1768                        inset: false,
1769                    },
1770                    border_radius: radius,
1771                });
1772        }
1773        let border_w = style.border_width.max(0.0);
1774        self.display_list
1775            .push(strata_render::compositor::DrawCommand::DrawRoundedRect {
1776                bounds,
1777                color: style.background_color,
1778                border_radius: radius,
1779                border_width: strata_primitives::geom::EdgeInsets::all(border_w),
1780                border_color: if border_w > 0.0 {
1781                    Some(style.border_color)
1782                } else {
1783                    None
1784                },
1785            });
1786        self.display_list
1787            .push(strata_render::compositor::DrawCommand::DrawText {
1788                origin: (x + pad_x, y + pad_y),
1789                bounds_width: Some((box_w - pad_x * 2.0).max(1.0)),
1790                bounds_height: Some((box_h - pad_y * 2.0).max(1.0)),
1791                text_align: strata_style::TextAlign::Left,
1792                text: text.clone(),
1793                font_size,
1794                line_height,
1795                font_weight,
1796                color: style.text_color,
1797                is_monospace: false,
1798                font_family,
1799            });
1800    }
1801}