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 Self::collect_top_layer_hover_portals(child_bp, child_layout, current_path, out);
80 }
81 current_path.pop();
82 }
83 }
84
85 pub(crate) fn hit_test_node_path_rec(
86 blueprint: &NodeBlueprint,
87 layout: &LayoutNode,
88 px: f32,
89 py: f32,
90 current_path: &mut Vec<usize>,
91 ) -> Option<Vec<usize>> {
92 if current_path.is_empty() {
93 let mut portals = Vec::new();
94 let mut scan_path = Vec::new();
95 Self::collect_top_layer_hover_portals(blueprint, layout, &mut scan_path, &mut portals);
96 for (p_bp, p_layout, mut p_path) in portals.into_iter().rev() {
97 if let Some(hit) =
98 Self::hit_test_node_path_sc(p_bp, p_layout, px, py, &[], &mut p_path)
99 {
100 return Some(hit);
101 }
102 }
103 }
104 Self::hit_test_node_path_sc(blueprint, layout, px, py, &[], current_path)
105 }
106
107 #[allow(clippy::too_many_arguments, clippy::type_complexity)]
108 fn collect_hoisted_hover_participants<'a>(
109 bp: &'a NodeBlueprint,
110 layout: &'a LayoutNode,
111 steps: &[super::hit_test::HitClipStep],
112 current_path: &mut Vec<usize>,
113 negative_z: &mut Vec<(
114 &'a NodeBlueprint,
115 &'a LayoutNode,
116 Vec<usize>,
117 Vec<super::hit_test::HitClipStep>,
118 )>,
119 auto_or_zero_z: &mut Vec<(
120 &'a NodeBlueprint,
121 &'a LayoutNode,
122 Vec<usize>,
123 bool,
124 Vec<super::hit_test::HitClipStep>,
125 )>,
126 positive_z: &mut Vec<(
127 &'a NodeBlueprint,
128 &'a LayoutNode,
129 Vec<usize>,
130 Vec<super::hit_test::HitClipStep>,
131 )>,
132 ) {
133 if current_path.len() >= 256 {
134 return;
135 }
136 let parent_display = Some(layout.style.display);
137 for (idx, child_bp, child_layout) in Self::paired_blueprint_children(bp, layout) {
138 if child_layout.is_top_layer
139 || matches!(
140 child_layout.style.display,
141 strata_style::types::Display::None
142 )
143 || matches!(
144 child_layout.style.visibility,
145 strata_style::types::Visibility::Hidden
146 )
147 {
148 continue;
149 }
150 current_path.push(idx);
151 if Self::establishes_stacking_context_in(child_layout, parent_display, false) {
152 let eff_steps = Self::effective_hit_clip_steps(child_layout, steps).to_vec();
153 let z = child_layout.style.z_index.unwrap_or(0);
154 if z < 0 {
155 negative_z.push((child_bp, child_layout, current_path.clone(), eff_steps));
156 } else if z > 0 {
157 positive_z.push((child_bp, child_layout, current_path.clone(), eff_steps));
158 } else {
159 auto_or_zero_z.push((
160 child_bp,
161 child_layout,
162 current_path.clone(),
163 true,
164 eff_steps,
165 ));
166 }
167 } else {
168 let eff_for_child = Self::effective_hit_clip_steps(child_layout, steps);
169 if child_layout.style.position != strata_style::types::Position::Static {
170 auto_or_zero_z.push((
171 child_bp,
172 child_layout,
173 current_path.clone(),
174 false,
175 eff_for_child.to_vec(),
176 ));
177 }
178 let mut child_steps = Vec::with_capacity(eff_for_child.len() + 1);
179 child_steps.extend_from_slice(eff_for_child);
180 let step = Self::hit_clip_step_for(child_layout);
181 if step.clip.is_some() || step.is_abs_cb || step.is_fixed_cb {
182 child_steps.push(step);
183 }
184 Self::collect_hoisted_hover_participants(
185 child_bp,
186 child_layout,
187 &child_steps,
188 current_path,
189 negative_z,
190 auto_or_zero_z,
191 positive_z,
192 );
193 }
194 current_path.pop();
195 }
196 }
197
198 fn hit_test_node_path_in_flow(
199 blueprint: &NodeBlueprint,
200 layout: &LayoutNode,
201 px: f32,
202 py: f32,
203 inherited_steps: &[super::hit_test::HitClipStep],
204 current_path: &mut Vec<usize>,
205 ) -> Option<Vec<usize>> {
206 if current_path.len() >= 256
207 || matches!(layout.style.display, strata_style::types::Display::None)
208 || matches!(
209 layout.style.visibility,
210 strata_style::types::Visibility::Hidden
211 )
212 {
213 return None;
214 }
215
216 let eff_inherited = Self::effective_hit_clip_steps(layout, inherited_steps);
217 if !Self::hit_clip_steps_allow(eff_inherited, px, py) {
218 return None;
219 }
220 if (layout.style.overflow_x != strata_style::types::Overflow::Visible
221 || layout.style.overflow_y != strata_style::types::Overflow::Visible)
222 && !layout.geometry.border_box.contains_point(px, py)
223 {
224 return None;
225 }
226
227 let parent_display = Some(layout.style.display);
228 let paired = Self::paired_blueprint_children(blueprint, layout);
229 for &(idx, child_bp, child_layout) in paired.iter().rev() {
230 if child_layout.is_top_layer
231 || matches!(
232 child_layout.style.display,
233 strata_style::types::Display::None
234 )
235 || Self::establishes_stacking_context_in(child_layout, parent_display, false)
236 || child_layout.style.position != strata_style::types::Position::Static
237 {
238 continue;
239 }
240 current_path.push(idx);
241 if let Some(res) =
242 Self::hit_test_node_path_in_flow(child_bp, child_layout, px, py, &[], current_path)
243 {
244 return Some(res);
245 }
246 current_path.pop();
247 }
248
249 if !matches!(
250 layout.style.pointer_events,
251 strata_style::types::PointerEvents::None
252 ) {
253 match blueprint {
254 NodeBlueprint::Element { .. }
255 | NodeBlueprint::Text(_)
256 | NodeBlueprint::DynamicText(_) => {
257 if layout.geometry.border_box.contains_point(px, py) {
258 return Some(current_path.clone());
259 }
260 }
261 _ => {}
262 }
263 }
264 None
265 }
266
267 fn hit_test_node_path_sc(
268 blueprint: &NodeBlueprint,
269 layout: &LayoutNode,
270 px: f32,
271 py: f32,
272 inherited_steps: &[super::hit_test::HitClipStep],
273 current_path: &mut Vec<usize>,
274 ) -> Option<Vec<usize>> {
275 if current_path.len() >= 256
276 || matches!(layout.style.display, strata_style::types::Display::None)
277 || matches!(
278 layout.style.visibility,
279 strata_style::types::Visibility::Hidden
280 )
281 {
282 return None;
283 }
284
285 let eff_inherited = Self::effective_hit_clip_steps(layout, inherited_steps);
286 let inherited_allows = Self::hit_clip_steps_allow(eff_inherited, px, py);
287
288 let (px, py) = Self::unproject_point(layout, px, py);
289
290 let own_clips = layout.style.overflow_x != strata_style::types::Overflow::Visible
291 || layout.style.overflow_y != strata_style::types::Overflow::Visible;
292 let own_allows = !own_clips || layout.geometry.border_box.contains_point(px, py);
293
294 let mut base_steps = Vec::with_capacity(eff_inherited.len() + 1);
295 base_steps.extend_from_slice(eff_inherited);
296 let own_step = Self::hit_clip_step_for(layout);
297 if own_step.clip.is_some() || own_step.is_abs_cb || own_step.is_fixed_cb {
298 base_steps.push(own_step);
299 }
300
301 let mut negative_z = Vec::new();
302 let mut auto_or_zero_z = Vec::new();
303 let mut positive_z = Vec::new();
304 Self::collect_hoisted_hover_participants(
305 blueprint,
306 layout,
307 &base_steps,
308 current_path,
309 &mut negative_z,
310 &mut auto_or_zero_z,
311 &mut positive_z,
312 );
313
314 negative_z.sort_by_key(|(_, l, _, _)| l.style.z_index.unwrap_or(0));
315 positive_z.sort_by_key(|(_, l, _, _)| l.style.z_index.unwrap_or(0));
316
317 for (c_bp, c_layout, c_path, c_steps) in positive_z.into_iter().rev() {
319 let mut path_buf = c_path;
320 if let Some(res) =
321 Self::hit_test_node_path_sc(c_bp, c_layout, px, py, &c_steps, &mut path_buf)
322 {
323 return Some(res);
324 }
325 }
326
327 for (c_bp, c_layout, c_path, is_sc, c_steps) in auto_or_zero_z.into_iter().rev() {
329 let mut path_buf = c_path;
330 let hit = if is_sc {
331 Self::hit_test_node_path_sc(c_bp, c_layout, px, py, &c_steps, &mut path_buf)
332 } else {
333 Self::hit_test_node_path_in_flow(c_bp, c_layout, px, py, &c_steps, &mut path_buf)
334 };
335 if hit.is_some() {
336 return hit;
337 }
338 }
339
340 if inherited_allows && own_allows {
342 let parent_display = Some(layout.style.display);
343 let paired = Self::paired_blueprint_children(blueprint, layout);
344 for &(idx, child_bp, child_layout) in paired.iter().rev() {
345 if child_layout.is_top_layer
346 || matches!(
347 child_layout.style.display,
348 strata_style::types::Display::None
349 )
350 || Self::establishes_stacking_context_in(child_layout, parent_display, false)
351 || child_layout.style.position != strata_style::types::Position::Static
352 {
353 continue;
354 }
355 current_path.push(idx);
356 if let Some(res) = Self::hit_test_node_path_in_flow(
357 child_bp,
358 child_layout,
359 px,
360 py,
361 &[],
362 current_path,
363 ) {
364 return Some(res);
365 }
366 current_path.pop();
367 }
368 }
369
370 for (c_bp, c_layout, c_path, c_steps) in negative_z.into_iter().rev() {
372 let mut path_buf = c_path;
373 if let Some(res) =
374 Self::hit_test_node_path_sc(c_bp, c_layout, px, py, &c_steps, &mut path_buf)
375 {
376 return Some(res);
377 }
378 }
379
380 if inherited_allows
382 && !matches!(
383 layout.style.pointer_events,
384 strata_style::types::PointerEvents::None
385 )
386 {
387 match blueprint {
388 NodeBlueprint::Element { .. }
389 | NodeBlueprint::Text(_)
390 | NodeBlueprint::DynamicText(_) => {
391 if layout.geometry.border_box.contains_point(px, py) {
392 Some(current_path.clone())
393 } else {
394 None
395 }
396 }
397 _ => None,
398 }
399 } else {
400 None
401 }
402 }
403
404 pub fn dispatch_boundary_events(
407 &self,
408 old_path: Option<&[usize]>,
409 new_path: Option<&[usize]>,
410 px: f32,
411 py: f32,
412 ) {
413 let old_slice = old_path.unwrap_or(&[]);
414 let new_slice = new_path.unwrap_or(&[]);
415
416 let mut common_len = 0;
417 if old_path.is_some() && new_path.is_some() {
418 while common_len < old_slice.len()
419 && common_len < new_slice.len()
420 && old_slice[common_len] == new_slice[common_len]
421 {
422 common_len += 1;
423 }
424 }
425
426 if old_path.is_some() {
428 let min_len = if new_path.is_some() {
429 common_len + 1
430 } else {
431 0
432 };
433 for len in (min_len..=old_slice.len()).rev() {
434 let subpath = &old_slice[..len];
435 if let Some((bp, layout)) =
436 Self::find_node_by_path(&self.root_blueprint, &self.layout_root, subpath)
437 {
438 self.dispatch_node_events(
439 bp,
440 layout,
441 &[
442 strata_dom::EventType::MouseOut,
443 strata_dom::EventType::MouseLeave,
444 ],
445 px,
446 py,
447 );
448 }
449 }
450 }
451
452 if new_path.is_some() {
454 let start_len = if old_path.is_some() {
455 common_len + 1
456 } else {
457 0
458 };
459 for len in start_len..=new_slice.len() {
460 let subpath = &new_slice[..len];
461 if let Some((bp, layout)) =
462 Self::find_node_by_path(&self.root_blueprint, &self.layout_root, subpath)
463 {
464 self.dispatch_node_events(
465 bp,
466 layout,
467 &[
468 strata_dom::EventType::MouseOver,
469 strata_dom::EventType::MouseEnter,
470 ],
471 px,
472 py,
473 );
474 }
475 }
476 }
477 }
478
479 pub(crate) fn dispatch_node_events(
481 &self,
482 bp: &NodeBlueprint,
483 layout: &LayoutNode,
484 event_types: &[strata_dom::EventType],
485 px: f32,
486 py: f32,
487 ) {
488 if let NodeBlueprint::Element { attributes, .. } = bp {
489 for attr in attributes {
490 if let strata_dom::Attribute::EventListener { event, handler } = attr {
491 if event_types.contains(event) {
492 let ev = self.create_mouse_event(
493 *event,
494 px,
495 py,
496 0,
497 0,
498 Some(&layout.geometry.border_box),
499 );
500 handler(ev);
501 }
502 }
503 }
504 }
505 }
506
507 pub fn node_path_has_hover_effects(blueprint: &NodeBlueprint, path: &[usize]) -> bool {
509 let stylesheets = Self::collect_stylesheets_from_blueprint(blueprint);
510 Self::node_path_has_hover_effects_with_sheets(blueprint, path, &stylesheets)
511 }
512
513 pub(crate) fn node_path_has_hover_effects_with_sheets(
514 blueprint: &NodeBlueprint,
515 path: &[usize],
516 stylesheets: &[std::sync::Arc<strata_style::StyleSheet>],
517 ) -> bool {
518 let mut path_nodes: Vec<&NodeBlueprint> = Vec::with_capacity(path.len() + 1);
519 let mut cur_bp = blueprint;
520 if Self::node_has_hover_effects(cur_bp) {
521 return true;
522 }
523 path_nodes.push(cur_bp);
524
525 for &idx in path {
526 match cur_bp {
527 NodeBlueprint::Element { children, .. } => {
528 let mut flat = Vec::new();
529 for c in children {
530 Self::flatten_blueprints(c, &mut flat);
531 }
532 if idx >= flat.len() {
533 break;
534 }
535 cur_bp = flat[idx];
536 }
537 NodeBlueprint::Fragment(children) => {
538 let mut flat = Vec::new();
539 for c in children {
540 Self::flatten_blueprints(c, &mut flat);
541 }
542 if idx >= flat.len() {
543 break;
544 }
545 cur_bp = flat[idx];
546 }
547 _ => break,
548 }
549 if Self::node_has_hover_effects(cur_bp) {
550 return true;
551 }
552 path_nodes.push(cur_bp);
553 }
554
555 if stylesheets.is_empty() {
556 return false;
557 }
558
559 Self::path_nodes_match_stylesheet_hover(&path_nodes, stylesheets)
560 }
561
562 pub(crate) fn path_nodes_match_stylesheet_hover(
564 path_nodes: &[&NodeBlueprint],
565 stylesheets: &[std::sync::Arc<strata_style::StyleSheet>],
566 ) -> bool {
567 let compound_has_hover = |comp: &strata_style::selector::CompoundSelector| {
568 comp.parts.iter().any(|p| match p {
569 strata_style::selector::SelectorPart::PseudoClass(name) => {
570 let n = name.trim().to_ascii_lowercase();
571 n == "hover" || n.contains(":hover")
572 }
573 _ => false,
574 })
575 };
576
577 let probe_state = strata_style::selector::PseudoState {
578 is_hovered: true,
579 ..Default::default()
580 };
581 let probe_state_dark = strata_style::selector::PseudoState {
582 is_hovered: true,
583 is_dark: true,
584 ..Default::default()
585 };
586
587 for bp in path_nodes {
588 if let NodeBlueprint::Element {
589 tag,
590 classes,
591 attributes,
592 ..
593 } = bp
594 {
595 if Self::is_style_tag(tag) {
596 continue;
597 }
598 let tag_str = Self::tag_as_str(tag);
599 let (class_vec, id_val, attr_vec) =
600 Self::extract_element_selector_meta(classes, attributes);
601 for sheet in stylesheets {
602 for rule in &sheet.rules {
603 for sel in &rule.selectors {
604 if !sel.has_any_hover_pseudo() {
605 continue;
606 }
607 if compound_has_hover(&sel.target)
608 && (sel.target.matches_with_context(
609 tag_str,
610 &class_vec,
611 id_val.as_deref(),
612 &attr_vec,
613 &probe_state,
614 &[],
615 Some(true),
616 Some(true),
617 &[],
618 ) || sel.target.matches_with_context(
619 tag_str,
620 &class_vec,
621 id_val.as_deref(),
622 &attr_vec,
623 &probe_state_dark,
624 &[],
625 Some(true),
626 Some(true),
627 &[],
628 ))
629 {
630 return true;
631 }
632 for (_, step_comp) in &sel.steps {
633 if compound_has_hover(step_comp)
634 && (step_comp.matches_with_context(
635 tag_str,
636 &class_vec,
637 id_val.as_deref(),
638 &attr_vec,
639 &probe_state,
640 &[],
641 Some(true),
642 Some(true),
643 &[],
644 ) || step_comp.matches_with_context(
645 tag_str,
646 &class_vec,
647 id_val.as_deref(),
648 &attr_vec,
649 &probe_state_dark,
650 &[],
651 Some(true),
652 Some(true),
653 &[],
654 ))
655 {
656 return true;
657 }
658 }
659 }
660 }
661 }
662 }
663 }
664 false
665 }
666
667 pub(crate) fn subtree_has_group_hover_effects(node: &NodeBlueprint) -> bool {
669 fn check(bp: &NodeBlueprint) -> bool {
670 match bp {
671 NodeBlueprint::Element {
672 classes, children, ..
673 } => {
674 let has_gh = classes.iter().any(|c| {
675 strata_style::tailwind::tokenize_classes(c)
676 .into_iter()
677 .any(|tok| {
678 let mut cur = tok;
679 while let (Some(m), rest) =
680 strata_style::tailwind::split_modifier(cur)
681 {
682 if m == "group-hover" {
683 return true;
684 }
685 cur = rest;
686 }
687 false
688 })
689 });
690 has_gh || children.iter().any(check)
691 }
692 NodeBlueprint::Fragment(children) => children.iter().any(check),
693 _ => false,
694 }
695 }
696 match node {
697 NodeBlueprint::Element {
698 classes, children, ..
699 } if Self::classes_have_group_marker(classes) => children.iter().any(check),
700 _ => false,
701 }
702 }
703
704 pub fn node_has_hover_effects(node: &NodeBlueprint) -> bool {
707 match node {
708 NodeBlueprint::Element {
709 classes,
710 attributes,
711 ..
712 } => {
713 let has_hover_class = classes.iter().any(|c| {
714 strata_style::tailwind::tokenize_classes(c)
715 .into_iter()
716 .any(|tok| {
717 let mut cur = tok;
718 while let (Some(m), rest) = strata_style::tailwind::split_modifier(cur)
719 {
720 if m == "hover" {
721 return true;
722 }
723 cur = rest;
724 }
725 false
726 })
727 });
728 if has_hover_class {
729 return true;
730 }
731 if Self::subtree_has_group_hover_effects(node) {
732 return true;
733 }
734 attributes.iter().any(|attr| match attr {
735 strata_dom::Attribute::EventListener { event, .. } => matches!(
736 event,
737 strata_dom::EventType::MouseEnter
738 | strata_dom::EventType::MouseLeave
739 | strata_dom::EventType::MouseOver
740 | strata_dom::EventType::MouseOut
741 ),
742 _ => false,
743 })
744 }
745 _ => false,
746 }
747 }
748
749 pub fn update_hover(&mut self, px: f32, py: f32) -> bool {
753 self.last_mouse_pos = (px, py);
754 let new_path = Self::hit_test_node_path(&self.root_blueprint, &self.layout_root, px, py);
755 if new_path == self.current_hover_path {
756 if self.hover_tooltip_since.is_some() && !self.hover_tooltip_visible {
757 self.hover_tooltip_anchor = (px, py);
758 }
759 return false;
760 }
761
762 let old_path = self.current_hover_path.take();
763 self.current_hover_path = new_path.clone();
764
765 self.dispatch_boundary_events(old_path.as_deref(), new_path.as_deref(), px, py);
766 let tooltip_changed = self.sync_hover_tooltip(px, py);
767
768 let old_has_effects = old_path.as_deref().is_some_and(|p| {
769 Self::node_path_has_hover_effects_with_sheets(
770 &self.root_blueprint,
771 p,
772 &self.cached_stylesheets,
773 )
774 });
775 let new_has_effects = new_path.as_deref().is_some_and(|p| {
776 Self::node_path_has_hover_effects_with_sheets(
777 &self.root_blueprint,
778 p,
779 &self.cached_stylesheets,
780 )
781 });
782
783 if old_has_effects || new_has_effects {
784 let has_listeners = old_path
785 .as_deref()
786 .is_some_and(|p| Self::path_has_hover_listeners(&self.root_blueprint, p))
787 || new_path
788 .as_deref()
789 .is_some_and(|p| Self::path_has_hover_listeners(&self.root_blueprint, p));
790 let layout_required = old_path
791 .as_deref()
792 .is_some_and(|p| Self::path_hover_affects_layout(&self.root_blueprint, p))
793 || new_path
794 .as_deref()
795 .is_some_and(|p| Self::path_hover_affects_layout(&self.root_blueprint, p));
796 if layout_required || has_listeners {
797 self.hover_paint_only = false;
798 self.rebuild_layout_tree();
799 } else {
800 self.hover_paint_only = true;
801 let hover_start = std::time::Instant::now();
802 let fast_ok = self.restyle_hover_subtrees_fast(
803 if old_has_effects {
804 old_path.as_deref()
805 } else {
806 None
807 },
808 if new_has_effects {
809 new_path.as_deref()
810 } else {
811 None
812 },
813 );
814 if !fast_ok {
815 self.restyle_for_hover_paint();
816 }
817 if perf_logging_enabled() {
818 perf_log_ms("hover_repaint", hover_start, "paint-only hover");
819 }
820 }
821 true
822 } else if tooltip_changed {
823 self.hover_paint_only = true;
824 self.compile_display_list();
825 true
826 } else {
827 self.hover_paint_only = false;
828 false
829 }
830 }
831
832 pub fn restyle_for_hover_paint(&mut self) {
839 let stylesheets = Self::collect_stylesheets_from_blueprint(&self.root_blueprint);
840 for sheet in &stylesheets {
841 self.register_keyframes_stylesheet(sheet);
842 }
843 let ctx = self.interaction_context();
844 let new_tree = Self::build_layout_tree_with_interaction(&self.root_blueprint, &ctx);
845 let mut previous = std::mem::replace(&mut self.layout_root, new_tree);
846 let transplanted = Self::transplant_layout_state(&mut previous, &mut self.layout_root);
847 let now_ms = self.runtime_start_epoch.elapsed().as_secs_f64() * 1000.0;
848 self.sync_tree_animations(now_ms);
849 if transplanted && !self.transition_manager.has_layout_affecting_transitions() {
850 strata_layout::box_model::refresh_inline_fragment_styles(&mut self.layout_root);
851 } else {
852 self.applied_scroll_offsets.clear();
853 self.applied_portal_offsets.clear();
854 let localized_layout = if let Some(ref path) = self.current_hover_path {
855 self.layout_root.compute_subgrid_or_boundary_layout(path)
856 } else {
857 false
858 };
859 if !localized_layout {
860 self.layout_root
861 .compute_layout(self.viewport_width, self.viewport_height);
862 }
863 Self::sync_layout_to_ir(&self.layout_root, &mut self.ir_graph);
864 self.layout_computations += 1;
865 self.apply_viewport_clamps();
866 self.apply_scroll_offsets();
867 }
868 self.sync_active_input_layout();
869 self.compile_display_list();
870 }
871
872 pub(crate) fn restyle_hover_subtrees_fast(
875 &mut self,
876 old_path: Option<&[usize]>,
877 new_path: Option<&[usize]>,
878 ) -> bool {
879 if !self.cached_stylesheets.is_empty()
880 || self.transition_manager.has_active_transitions()
881 || Self::node_has_hover_effects(&self.root_blueprint)
882 {
883 return false;
884 }
885
886 fn subtree_has_transitions_or_anims(node: &LayoutNode) -> bool {
887 if !node.style.transitions.is_empty() || !node.style.animations.is_empty() {
888 return true;
889 }
890 node.children.iter().any(subtree_has_transitions_or_anims)
891 }
892
893 fn restyle_one_path(
894 bp_root: &NodeBlueprint,
895 layout_root: &mut LayoutNode,
896 target_path: &[usize],
897 ctx: &InteractionContext,
898 ) -> bool {
899 let mut cur_bp = bp_root;
900 let mut cur_layout = layout_root;
901 let mut prefix = Vec::with_capacity(target_path.len());
902 for &idx in target_path {
903 let mut flat = Vec::new();
904 match cur_bp {
905 NodeBlueprint::Element { children, .. } | NodeBlueprint::Fragment(children) => {
906 for c in children {
907 AppRuntime::flatten_blueprints(c, &mut flat);
908 }
909 }
910 _ => return false,
911 }
912 if idx >= flat.len() || idx >= cur_layout.children.len() {
913 return false;
914 }
915 let child_bp = flat[idx];
916 prefix.push(idx);
917 if AppRuntime::subtree_has_group_hover_effects(child_bp) {
918 return false;
919 }
920 if AppRuntime::node_has_hover_effects(child_bp) {
921 let parent_style = cur_layout.style.clone();
922 let child_layout = &mut cur_layout.children[idx];
923 if subtree_has_transitions_or_anims(child_layout) {
924 return false;
925 }
926 let mut rebuilt = AppRuntime::build_layout_tree_with_interaction_context(
927 child_bp,
928 Some(&parent_style),
929 &mut prefix,
930 ctx,
931 );
932 if !AppRuntime::transplant_layout_state(child_layout, &mut rebuilt) {
933 return false;
934 }
935 strata_layout::box_model::refresh_inline_fragment_styles(&mut rebuilt);
936 *child_layout = rebuilt;
937 return true;
938 }
939 cur_bp = child_bp;
940 cur_layout = &mut cur_layout.children[idx];
941 }
942 true
943 }
944
945 let hovered_owned = self.current_hover_path.clone();
946 let focused_owned = self.current_focus_path.clone();
947 let ctx = InteractionContext {
948 hovered_path: hovered_owned.as_deref(),
949 focused_path: focused_owned.as_deref(),
950 is_mouse_down: self.is_mouse_down,
951 is_dark_mode: self.is_dark_mode,
952 };
953 if let Some(p) = old_path {
954 if !restyle_one_path(&self.root_blueprint, &mut self.layout_root, p, &ctx) {
955 return false;
956 }
957 }
958 if let Some(p) = new_path {
959 if !restyle_one_path(&self.root_blueprint, &mut self.layout_root, p, &ctx) {
960 return false;
961 }
962 }
963 self.sync_active_input_layout();
964 self.compile_display_list();
965 true
966 }
967
968 pub(crate) fn path_has_active_styles(&self) -> bool {
971 let Some(ref path) = self.current_hover_path else {
972 return false;
973 };
974 let mut cur_bp = &self.root_blueprint;
975 let has_active_class = |bp: &NodeBlueprint| -> bool {
976 if let NodeBlueprint::Element { classes, .. } = bp {
977 classes
978 .iter()
979 .any(|c| c.split_whitespace().any(|tok| tok.contains("active:")))
980 } else {
981 false
982 }
983 };
984 if has_active_class(cur_bp) {
985 return true;
986 }
987 for &idx in path {
988 let mut flat = Vec::new();
989 match cur_bp {
990 NodeBlueprint::Element { children, .. } | NodeBlueprint::Fragment(children) => {
991 for c in children {
992 Self::flatten_blueprints(c, &mut flat);
993 }
994 }
995 _ => break,
996 }
997 if idx >= flat.len() {
998 break;
999 }
1000 cur_bp = flat[idx];
1001 if has_active_class(cur_bp) {
1002 return true;
1003 }
1004 }
1005 for sheet in &self.cached_stylesheets {
1006 for rule in &sheet.rules {
1007 for sel in &rule.selectors {
1008 let has_active_pseudo = sel.target.parts.iter().any(|p| {
1009 matches!(
1010 p,
1011 strata_style::selector::SelectorPart::PseudoClass(name)
1012 if name.eq_ignore_ascii_case("active")
1013 )
1014 });
1015 if has_active_pseudo {
1016 return true;
1017 }
1018 }
1019 }
1020 }
1021 false
1022 }
1023
1024 pub fn restyle_for_active_change(&mut self) -> bool {
1027 if !self.path_has_active_styles() {
1028 return false;
1029 }
1030 self.restyle_for_hover_paint();
1031 true
1032 }
1033
1034 pub(crate) fn transplant_layout_state(
1036 previous: &mut LayoutNode,
1037 next: &mut LayoutNode,
1038 ) -> bool {
1039 if previous.children.len() != next.children.len() {
1040 return false;
1041 }
1042 next.geometry = previous.geometry;
1043 next.line_boxes = std::mem::take(&mut previous.line_boxes);
1044 next.inline_items = std::mem::take(&mut previous.inline_items);
1045 next.layout_cache = previous.layout_cache;
1046 for (prev_child, next_child) in previous.children.iter_mut().zip(next.children.iter_mut()) {
1047 if !Self::transplant_layout_state(prev_child, next_child) {
1048 return false;
1049 }
1050 }
1051 true
1052 }
1053
1054 pub(crate) fn path_has_hover_listeners(blueprint: &NodeBlueprint, path: &[usize]) -> bool {
1056 let mut current = blueprint;
1057 if Self::node_has_hover_listeners(current) {
1058 return true;
1059 }
1060 for &idx in path {
1061 let mut flat = Vec::new();
1062 match current {
1063 NodeBlueprint::Element { children, .. } | NodeBlueprint::Fragment(children) => {
1064 for child in children {
1065 Self::flatten_blueprints(child, &mut flat);
1066 }
1067 }
1068 _ => return false,
1069 }
1070 if idx >= flat.len() {
1071 return false;
1072 }
1073 current = flat[idx];
1074 if Self::node_has_hover_listeners(current) {
1075 return true;
1076 }
1077 }
1078 false
1079 }
1080
1081 pub(crate) fn node_has_hover_listeners(node: &NodeBlueprint) -> bool {
1082 match node {
1083 NodeBlueprint::Element { attributes, .. } => attributes.iter().any(|attr| match attr {
1084 strata_dom::Attribute::EventListener { event, .. } => matches!(
1085 event,
1086 strata_dom::EventType::MouseEnter
1087 | strata_dom::EventType::MouseLeave
1088 | strata_dom::EventType::MouseOver
1089 | strata_dom::EventType::MouseOut
1090 ),
1091 _ => false,
1092 }),
1093 _ => false,
1094 }
1095 }
1096
1097 pub fn clear_hover(&mut self) -> bool {
1099 if self.current_hover_path.is_none() {
1100 if self.dismiss_hover_tooltip() {
1101 self.hover_paint_only = true;
1102 self.compile_display_list();
1103 return true;
1104 }
1105 return false;
1106 }
1107 let old_path = self.current_hover_path.take();
1108 self.dispatch_boundary_events(
1109 old_path.as_deref(),
1110 None,
1111 self.last_mouse_pos.0,
1112 self.last_mouse_pos.1,
1113 );
1114 let tooltip_dismissed = self.dismiss_hover_tooltip();
1115 let old_has_effects = old_path
1116 .as_deref()
1117 .is_some_and(|p| Self::node_path_has_hover_effects(&self.root_blueprint, p));
1118 if old_has_effects {
1119 let has_listeners = old_path
1120 .as_deref()
1121 .is_some_and(|p| Self::path_has_hover_listeners(&self.root_blueprint, p));
1122 let layout_required = old_path
1123 .as_deref()
1124 .is_some_and(|p| Self::path_hover_affects_layout(&self.root_blueprint, p));
1125 if layout_required || has_listeners {
1126 self.hover_paint_only = false;
1127 self.rebuild_layout_tree();
1128 } else {
1129 self.hover_paint_only = true;
1130 let hover_start = std::time::Instant::now();
1131 self.restyle_for_hover_paint();
1132 if perf_logging_enabled() {
1133 perf_log_ms("hover_repaint", hover_start, "paint-only hover");
1134 }
1135 }
1136 true
1137 } else if tooltip_dismissed {
1138 self.hover_paint_only = true;
1139 self.compile_display_list();
1140 true
1141 } else {
1142 self.hover_paint_only = false;
1143 false
1144 }
1145 }
1146
1147 pub(crate) fn resolve_hover_tooltip(
1151 blueprint: &NodeBlueprint,
1152 path: &[usize],
1153 ) -> Option<(Vec<usize>, String)> {
1154 let mut chain: Vec<(Vec<usize>, &NodeBlueprint)> = Vec::with_capacity(path.len() + 1);
1155 let mut current = blueprint;
1156 let mut prefix = Vec::with_capacity(path.len());
1157 chain.push((prefix.clone(), current));
1158 for &idx in path {
1159 let mut flat = Vec::new();
1160 match current {
1161 NodeBlueprint::Element { children, .. } | NodeBlueprint::Fragment(children) => {
1162 for child in children {
1163 Self::flatten_blueprints(child, &mut flat);
1164 }
1165 }
1166 _ => break,
1167 }
1168 if idx >= flat.len() {
1169 break;
1170 }
1171 current = flat[idx];
1172 prefix.push(idx);
1173 chain.push((prefix.clone(), current));
1174 }
1175
1176 for (node_path, node) in chain.iter().rev() {
1178 if let NodeBlueprint::Element { attributes, .. } = node {
1179 for attr in attributes {
1180 if let strata_dom::Attribute::Property { key, value } = attr {
1181 if key.eq_ignore_ascii_case("title") {
1182 let trimmed = value.trim();
1183 if !trimmed.is_empty() {
1184 return Some((node_path.clone(), trimmed.to_string()));
1185 }
1186 }
1187 }
1188 }
1189 }
1190 }
1191
1192 for (node_path, node) in chain.iter().rev() {
1194 if let NodeBlueprint::Element {
1195 tag, attributes, ..
1196 } = node
1197 {
1198 let supports_alt_tooltip = match tag {
1199 strata_dom::Tag::Img | strata_dom::Tag::Button => true,
1200 strata_dom::Tag::Custom(name) => {
1201 name.eq_ignore_ascii_case("img") || name.eq_ignore_ascii_case("button")
1202 }
1203 _ => false,
1204 };
1205 if !supports_alt_tooltip {
1206 continue;
1207 }
1208 for attr in attributes {
1209 if let strata_dom::Attribute::Property { key, value } = attr {
1210 if key.eq_ignore_ascii_case("alt") {
1211 let trimmed = value.trim();
1212 if !trimmed.is_empty() {
1213 return Some((node_path.clone(), trimmed.to_string()));
1214 }
1215 }
1216 }
1217 }
1218 }
1219 }
1220
1221 None
1222 }
1223
1224 pub(crate) fn sync_hover_tooltip(&mut self, px: f32, py: f32) -> bool {
1227 let resolved = self
1228 .current_hover_path
1229 .as_deref()
1230 .and_then(|p| Self::resolve_hover_tooltip(&self.root_blueprint, p));
1231
1232 match resolved {
1233 Some((owner_path, text)) => {
1234 if self.hover_tooltip_path.as_ref() == Some(&owner_path)
1235 && self.hover_tooltip_text.as_deref() == Some(text.as_str())
1236 {
1237 if self.hover_tooltip_since.is_some() && !self.hover_tooltip_visible {
1238 self.hover_tooltip_anchor = (px, py);
1239 }
1240 false
1241 } else {
1242 let was_visible = self.hover_tooltip_visible;
1243 self.hover_tooltip_path = Some(owner_path);
1244 self.hover_tooltip_text = Some(text);
1245 self.hover_tooltip_anchor = (px, py);
1246 self.hover_tooltip_since = if self.is_mouse_down {
1247 None
1248 } else {
1249 Some(std::time::Instant::now())
1250 };
1251 self.hover_tooltip_visible = false;
1252 was_visible
1253 }
1254 }
1255 None => self.dismiss_hover_tooltip(),
1256 }
1257 }
1258
1259 pub(crate) fn refresh_hover_tooltip_after_view_update(&mut self) {
1261 let Some(ref path) = self.current_hover_path else {
1262 self.dismiss_hover_tooltip();
1263 return;
1264 };
1265 match Self::resolve_hover_tooltip(&self.root_blueprint, path) {
1266 Some((owner_path, text)) => {
1267 if self.hover_tooltip_path.as_ref() == Some(&owner_path) {
1268 self.hover_tooltip_text = Some(text);
1269 } else {
1270 self.hover_tooltip_path = Some(owner_path);
1271 self.hover_tooltip_text = Some(text);
1272 self.hover_tooltip_anchor = self.last_mouse_pos;
1273 self.hover_tooltip_since = if self.is_mouse_down {
1274 None
1275 } else {
1276 Some(std::time::Instant::now())
1277 };
1278 self.hover_tooltip_visible = false;
1279 }
1280 }
1281 None => {
1282 self.dismiss_hover_tooltip();
1283 }
1284 }
1285 }
1286
1287 pub fn dismiss_hover_tooltip(&mut self) -> bool {
1290 let was_visible = self.hover_tooltip_visible;
1291 self.hover_tooltip_text = None;
1292 self.hover_tooltip_path = None;
1293 self.hover_tooltip_since = None;
1294 self.hover_tooltip_visible = false;
1295 was_visible
1296 }
1297
1298 pub fn dismiss_hover_tooltip_and_repaint(&mut self) -> bool {
1301 let was_visible = self.hover_tooltip_visible;
1302 self.hover_tooltip_since = None;
1303 self.hover_tooltip_visible = false;
1304 if was_visible {
1305 self.paint_dirty = true;
1306 self.compile_display_list();
1307 }
1308 was_visible
1309 }
1310
1311 pub fn next_hover_tooltip_due_in(&self) -> Option<std::time::Duration> {
1313 if self.hover_tooltip_visible || self.is_mouse_down {
1314 return None;
1315 }
1316 let (_, Some(since)) = (&self.hover_tooltip_text, self.hover_tooltip_since) else {
1317 return None;
1318 };
1319 Some(self.hover_tooltip_delay.saturating_sub(since.elapsed()))
1320 }
1321
1322 pub fn poll_hover_tooltip(&mut self) -> bool {
1325 if self.hover_tooltip_visible || self.is_mouse_down {
1326 return false;
1327 }
1328 let (Some(_), Some(since)) = (&self.hover_tooltip_text, self.hover_tooltip_since) else {
1329 return false;
1330 };
1331 if since.elapsed() < self.hover_tooltip_delay {
1332 return false;
1333 }
1334 self.hover_tooltip_visible = true;
1335 self.paint_dirty = true;
1336 self.compile_display_list();
1337 true
1338 }
1339
1340 pub fn render_hover_tooltip(&mut self) {
1342 if !self.hover_tooltip_visible {
1343 return;
1344 }
1345 let Some(ref text) = self.hover_tooltip_text else {
1346 return;
1347 };
1348 if text.is_empty() || self.viewport_width <= 0.0 || self.viewport_height <= 0.0 {
1349 return;
1350 }
1351
1352 let style = self.hover_tooltip_style;
1353 let font_size = style.font_size.max(6.0);
1354 let line_height = style.line_height.max(1.0);
1355 let font_family = strata_primitives::AtomId::FONT_SANS;
1356 let font_weight = strata_style::types::FontWeight::Normal;
1357 let pad_x = style.padding_x.max(0.0);
1358 let pad_y = style.padding_y.max(0.0);
1359 let margin = 6.0_f32;
1360 let max_allowed_w = style.max_width.max(24.0);
1361 let max_text_w = (self.viewport_width - pad_x * 2.0 - margin * 2.0)
1362 .clamp(24.0_f32.min(max_allowed_w), max_allowed_w);
1363
1364 let (tw, th) = strata_layout::measure_text_bounds_styled_with_family(
1365 text,
1366 font_size,
1367 line_height,
1368 Some(max_text_w),
1369 false,
1370 font_family,
1371 font_weight,
1372 strata_style::types::FontStyle::Normal,
1373 );
1374 let text_w = tw.max(12.0).min(max_text_w);
1375 let text_h = th.max(font_size * line_height);
1376 let box_w = (text_w + pad_x * 2.0)
1377 .ceil()
1378 .min((self.viewport_width - margin * 2.0).max(24.0));
1379 let box_h = (text_h + pad_y * 2.0)
1380 .ceil()
1381 .min((self.viewport_height - margin * 2.0).max(22.0));
1382
1383 let (ax, ay) = self.hover_tooltip_anchor;
1384 let mut x = ax + style.cursor_offset_x;
1385 let mut y = ay + style.cursor_offset_y;
1386 if x + box_w > self.viewport_width - margin {
1387 x = (self.viewport_width - margin - box_w).max(margin);
1388 }
1389 if y + box_h > self.viewport_height - margin {
1390 y = (ay - box_h - 10.0).max(margin);
1391 }
1392 x = x.max(margin);
1393 y = y.max(margin);
1394
1395 let bounds = strata_layout::Rect::new(x, y, box_w, box_h);
1396 let radius = strata_style::types::BorderRadius::all(style.corner_radius.max(0.0));
1397
1398 if style.shadow_color.a > 0 {
1399 self.display_list
1400 .push(strata_render::compositor::DrawCommand::DrawShadow {
1401 bounds,
1402 shadow: strata_style::types::BoxShadow {
1403 offset_x: 0.0,
1404 offset_y: 4.0,
1405 blur_radius: 12.0,
1406 spread_radius: 0.0,
1407 color: style.shadow_color,
1408 inset: false,
1409 },
1410 border_radius: radius,
1411 });
1412 }
1413 let border_w = style.border_width.max(0.0);
1414 self.display_list
1415 .push(strata_render::compositor::DrawCommand::DrawRoundedRect {
1416 bounds,
1417 color: style.background_color,
1418 border_radius: radius,
1419 border_width: strata_primitives::geom::EdgeInsets::all(border_w),
1420 border_color: if border_w > 0.0 {
1421 Some(style.border_color)
1422 } else {
1423 None
1424 },
1425 });
1426 self.display_list
1427 .push(strata_render::compositor::DrawCommand::DrawText {
1428 origin: (x + pad_x, y + pad_y),
1429 bounds_width: Some((box_w - pad_x * 2.0).max(1.0)),
1430 bounds_height: Some((box_h - pad_y * 2.0).max(1.0)),
1431 text_align: strata_style::TextAlign::Left,
1432 text: text.clone(),
1433 font_size,
1434 line_height,
1435 font_weight,
1436 color: style.text_color,
1437 is_monospace: false,
1438 font_family,
1439 });
1440 }
1441}