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