1use std::collections::HashMap;
4use std::rc::Rc;
5use strata_dom::{Event, EventType, NodeBlueprint};
6use strata_layout::tree::LayoutNode;
7use strata_layout::Rect;
8use strata_primitives::EntityId;
9use strata_style::types::{Display, Float, Overflow, PointerEvents, Position, Visibility};
10
11use crate::runtime::AppRuntime;
12
13#[derive(Clone)]
15pub struct SpatialEntry {
16 pub entity_id: EntityId,
17 pub bounds: Rect,
18 pub event_listeners: Vec<(EventType, Rc<dyn Fn(Event)>)>,
19 pub z_index: i32,
20 pub order: usize,
21 root_z_key: i64,
22 clip_bounds: Option<Rect>,
23 hittable: bool,
24 layout_path: Vec<usize>,
25}
26
27impl SpatialEntry {
28 #[inline]
29 fn contains_clipped_point(&self, px: f32, py: f32) -> bool {
30 if !self.hittable || !self.bounds.contains_point(px, py) {
31 return false;
32 }
33 match self.clip_bounds {
34 Some(clip) => clip.width >= 0.0 && clip.height >= 0.0 && clip.contains_point(px, py),
35 None => true,
36 }
37 }
38}
39
40impl std::fmt::Debug for SpatialEntry {
41 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42 f.debug_struct("SpatialEntry")
43 .field("entity_id", &self.entity_id)
44 .field("bounds", &self.bounds)
45 .field("listeners_count", &self.event_listeners.len())
46 .field("z_index", &self.z_index)
47 .field("order", &self.order)
48 .finish()
49 }
50}
51
52#[inline]
53fn intersect_clip(existing: Option<Rect>, next: Rect) -> Option<Rect> {
54 match existing {
55 None => Some(next),
56 Some(prev) => {
57 if prev.width < 0.0 || prev.height < 0.0 {
58 return Some(prev);
59 }
60 let x0 = prev.x.max(next.x);
61 let y0 = prev.y.max(next.y);
62 let x1 = (prev.x + prev.width).min(next.x + next.width);
63 let y1 = (prev.y + prev.height).min(next.y + next.height);
64 if x1 < x0 || y1 < y0 {
65 Some(Rect::new(0.0, 0.0, -1.0, -1.0))
66 } else {
67 Some(Rect::new(x0, y0, x1 - x0, y1 - y0))
68 }
69 }
70 }
71}
72
73#[derive(Default, Clone, Debug)]
75pub struct SpatialIndex {
76 entries: Vec<SpatialEntry>,
77 entity_to_index: HashMap<EntityId, usize>,
78}
79
80impl SpatialIndex {
81 pub fn new() -> Self {
83 Self {
84 entries: Vec::new(),
85 entity_to_index: HashMap::new(),
86 }
87 }
88
89 pub fn sync_bounds(&mut self, layout_root: &LayoutNode) {
92 if self.entries.is_empty() {
93 return;
94 }
95 for entry in &mut self.entries {
96 let mut cur = layout_root;
97 let mut valid = true;
98 for &idx in &entry.layout_path {
99 if let Some(child) = cur.children.get(idx) {
100 cur = child;
101 } else {
102 valid = false;
103 break;
104 }
105 }
106 if valid {
107 entry.bounds = cur.geometry.border_box;
108 }
109 }
110 }
111
112 pub fn sync_bounds_for_prefix(&mut self, layout_root: &LayoutNode, prefix: &[usize]) {
115 if self.entries.is_empty() {
116 return;
117 }
118 if prefix.is_empty() {
119 self.sync_bounds(layout_root);
120 return;
121 }
122 let mut prefix_root = layout_root;
123 for &idx in prefix {
124 if let Some(child) = prefix_root.children.get(idx) {
125 prefix_root = child;
126 } else {
127 return;
128 }
129 }
130 let prefix_len = prefix.len();
131 for entry in &mut self.entries {
132 if entry.layout_path.len() <= prefix_len || !entry.layout_path.starts_with(prefix) {
133 continue;
134 }
135 let mut cur = prefix_root;
136 let mut valid = true;
137 for &idx in &entry.layout_path[prefix_len..] {
138 if let Some(child) = cur.children.get(idx) {
139 cur = child;
140 } else {
141 valid = false;
142 break;
143 }
144 }
145 if valid {
146 entry.bounds = cur.geometry.border_box;
147 }
148 }
149 }
150
151 fn collect_top_layer_portals<'a>(
152 bp: &'a NodeBlueprint,
153 layout: &'a LayoutNode,
154 fallback_bp: &'a NodeBlueprint,
155 current_path: &mut Vec<usize>,
156 out: &mut Vec<(&'a NodeBlueprint, &'a LayoutNode, Vec<usize>)>,
157 depth: usize,
158 ) {
159 if depth >= 256 {
160 return;
161 }
162 for (idx, child_bp, child_layout) in
163 Self::paired_children_with_fallback(bp, layout, fallback_bp)
164 {
165 if child_layout.style.display == Display::None {
166 continue;
167 }
168 current_path.push(idx);
169 if child_layout.is_top_layer {
170 out.push((child_bp, child_layout, current_path.clone()));
171 }
172 if !child_layout.children.is_empty() {
173 Self::collect_top_layer_portals(
174 child_bp,
175 child_layout,
176 fallback_bp,
177 current_path,
178 out,
179 depth + 1,
180 );
181 }
182 current_path.pop();
183 }
184 }
185
186 pub fn rebuild(&mut self, blueprint: &NodeBlueprint, layout: &LayoutNode) {
188 self.entries.clear();
189 self.entity_to_index.clear();
190
191 let mut order = 0;
192 let mut path = Vec::new();
193 let root_z = layout.style.z_index.unwrap_or(0);
194 Self::collect_stacking_context(
195 blueprint,
196 layout,
197 &mut path,
198 &mut self.entries,
199 &mut order,
200 root_z,
201 i64::MIN,
202 true,
203 &[],
204 0,
205 );
206
207 let fallback_bp = NodeBlueprint::Empty;
208 let mut portals = Vec::new();
209 path.clear();
210 Self::collect_top_layer_portals(
211 blueprint,
212 layout,
213 &fallback_bp,
214 &mut path,
215 &mut portals,
216 0,
217 );
218 for (p_bp, p_layout, mut p_path) in portals {
219 let p_z = p_layout.style.z_index.unwrap_or(0);
220 Self::collect_stacking_context(
221 p_bp,
222 p_layout,
223 &mut p_path,
224 &mut self.entries,
225 &mut order,
226 p_z,
227 i64::MAX,
228 false,
229 &[],
230 1,
231 );
232 }
233
234 for (idx, entry) in self.entries.iter().enumerate() {
235 if entry.entity_id.is_valid() {
236 self.entity_to_index.insert(entry.entity_id, idx);
237 }
238 }
239 }
240
241 #[inline]
242 fn steps_to_clip(steps: &[super::hit_test::HitClipStep]) -> Option<Rect> {
243 let mut acc: Option<Rect> = None;
244 for s in steps {
245 if let Some(r) = s.clip {
246 acc = intersect_clip(acc, r);
247 }
248 }
249 acc
250 }
251
252 #[allow(clippy::too_many_arguments)]
253 fn emit_node_entry(
254 blueprint: &NodeBlueprint,
255 layout: &LayoutNode,
256 layout_path: &[usize],
257 out: &mut Vec<SpatialEntry>,
258 order: &mut usize,
259 effective_z: i32,
260 root_z_key: i64,
261 active_clip: Option<Rect>,
262 ) {
263 let entity_id = layout.entity_id;
264 let bounds = layout.geometry.border_box;
265 let mut listeners = Vec::new();
266
267 if let NodeBlueprint::Element { attributes, .. } = blueprint {
268 for attr in attributes {
269 if let strata_dom::Attribute::EventListener { event, handler } = attr {
270 listeners.push((*event, Rc::clone(handler)));
271 }
272 }
273 }
274
275 let hittable = !matches!(layout.style.visibility, Visibility::Hidden)
276 && !matches!(layout.style.pointer_events, PointerEvents::None);
277 let is_visual_element = matches!(blueprint, NodeBlueprint::Element { .. });
278 if entity_id.is_valid() || !listeners.is_empty() || (is_visual_element && hittable) {
279 let entry = SpatialEntry {
280 entity_id,
281 bounds,
282 event_listeners: listeners,
283 z_index: effective_z,
284 order: *order,
285 root_z_key,
286 clip_bounds: active_clip,
287 hittable,
288 layout_path: layout_path.to_vec(),
289 };
290 *order += 1;
291 out.push(entry);
292 }
293 }
294
295 fn paired_children_with_fallback<'a>(
296 node_bp: &'a NodeBlueprint,
297 node_layout: &'a LayoutNode,
298 fallback_bp: &'a NodeBlueprint,
299 ) -> Vec<(usize, &'a NodeBlueprint, &'a LayoutNode)> {
300 let mut flat_children = Vec::new();
301 match node_bp {
302 NodeBlueprint::Element { children, .. } | NodeBlueprint::Fragment(children) => {
303 for c in children {
304 AppRuntime::flatten_blueprints(c, &mut flat_children);
305 }
306 }
307 _ => {}
308 }
309
310 let mut out = Vec::with_capacity(node_layout.children.len());
311 for (idx, child_layout) in node_layout.children.iter().enumerate() {
312 let resolved_bp = if child_layout.entity_id.is_valid() {
313 if let Some(&cand) = flat_children.get(idx) {
314 if cand.entity_id() == Some(child_layout.entity_id) {
315 cand
316 } else {
317 node_bp
318 .find_by_entity_id(child_layout.entity_id)
319 .unwrap_or(cand)
320 }
321 } else {
322 node_bp
323 .find_by_entity_id(child_layout.entity_id)
324 .unwrap_or(fallback_bp)
325 }
326 } else {
327 flat_children.get(idx).copied().unwrap_or(fallback_bp)
328 };
329 out.push((idx, resolved_bp, child_layout));
330 }
331 out
332 }
333
334 #[allow(clippy::too_many_arguments, clippy::type_complexity)]
335 fn collect_hoisted_participants<'a>(
336 bp: &'a NodeBlueprint,
337 layout: &'a LayoutNode,
338 fallback_bp: &'a NodeBlueprint,
339 current_path: &mut Vec<usize>,
340 steps: &[super::hit_test::HitClipStep],
341 negative_z: &mut Vec<(
342 &'a NodeBlueprint,
343 &'a LayoutNode,
344 Vec<usize>,
345 Vec<super::hit_test::HitClipStep>,
346 )>,
347 auto_or_zero_z: &mut Vec<(
348 &'a NodeBlueprint,
349 &'a LayoutNode,
350 Vec<usize>,
351 bool,
352 Vec<super::hit_test::HitClipStep>,
353 )>,
354 positive_z: &mut Vec<(
355 &'a NodeBlueprint,
356 &'a LayoutNode,
357 Vec<usize>,
358 Vec<super::hit_test::HitClipStep>,
359 )>,
360 depth: usize,
361 ) {
362 if depth >= 256 {
363 return;
364 }
365 let parent_display = Some(layout.style.display);
366 for (idx, child_bp, child_layout) in
367 Self::paired_children_with_fallback(bp, layout, fallback_bp)
368 {
369 if child_layout.style.display == Display::None || child_layout.is_top_layer {
370 continue;
371 }
372 current_path.push(idx);
373 if AppRuntime::establishes_stacking_context_in(child_layout, parent_display, false) {
374 let eff_steps = AppRuntime::effective_hit_clip_steps(child_layout, steps).to_vec();
375 let z = child_layout.style.z_index.unwrap_or(0);
376 if z < 0 {
377 negative_z.push((child_bp, child_layout, current_path.clone(), eff_steps));
378 } else if z > 0 {
379 positive_z.push((child_bp, child_layout, current_path.clone(), eff_steps));
380 } else {
381 auto_or_zero_z.push((
382 child_bp,
383 child_layout,
384 current_path.clone(),
385 true,
386 eff_steps,
387 ));
388 }
389 } else {
390 let eff_for_child = AppRuntime::effective_hit_clip_steps(child_layout, steps);
391 if child_layout.style.position != Position::Static {
392 auto_or_zero_z.push((
393 child_bp,
394 child_layout,
395 current_path.clone(),
396 false,
397 eff_for_child.to_vec(),
398 ));
399 }
400 let mut child_steps = Vec::with_capacity(eff_for_child.len() + 1);
401 child_steps.extend_from_slice(eff_for_child);
402 let step = AppRuntime::hit_clip_step_for(child_layout);
403 if step.clip.is_some() || step.is_abs_cb || step.is_fixed_cb {
404 child_steps.push(step);
405 }
406 Self::collect_hoisted_participants(
407 child_bp,
408 child_layout,
409 fallback_bp,
410 current_path,
411 &child_steps,
412 negative_z,
413 auto_or_zero_z,
414 positive_z,
415 depth + 1,
416 );
417 }
418 current_path.pop();
419 }
420 }
421
422 #[allow(clippy::too_many_arguments)]
423 fn collect_direct_in_flow_children(
424 bp: &NodeBlueprint,
425 layout: &LayoutNode,
426 current_path: &mut Vec<usize>,
427 out: &mut Vec<SpatialEntry>,
428 order: &mut usize,
429 inherited_z: i32,
430 root_z_key: i64,
431 active_clip: Option<Rect>,
432 depth: usize,
433 ) {
434 let fallback_bp = NodeBlueprint::Empty;
435 let paired = Self::paired_children_with_fallback(bp, layout, &fallback_bp);
436 if paired.is_empty() {
437 return;
438 }
439
440 let parent_display = Some(layout.style.display);
441 let is_in_flow_non_sc = |c: &LayoutNode| {
442 c.style.display != Display::None
443 && !c.is_top_layer
444 && !AppRuntime::establishes_stacking_context_in(c, parent_display, false)
445 && c.style.position == Position::Static
446 };
447 let is_inline_level = |c: &LayoutNode| {
448 matches!(
449 c.style.display,
450 Display::Inline | Display::InlineBlock | Display::InlineFlex | Display::InlineGrid
451 )
452 };
453
454 for &(idx, child_bp, child_layout) in &paired {
456 if is_in_flow_non_sc(child_layout)
457 && child_layout.style.float == Float::None
458 && !is_inline_level(child_layout)
459 {
460 current_path.push(idx);
461 Self::collect_in_flow_non_hoisted(
462 child_bp,
463 child_layout,
464 current_path,
465 out,
466 order,
467 inherited_z,
468 root_z_key,
469 active_clip,
470 depth + 1,
471 );
472 current_path.pop();
473 }
474 }
475
476 for &(idx, child_bp, child_layout) in &paired {
478 if is_in_flow_non_sc(child_layout) && child_layout.style.float != Float::None {
479 current_path.push(idx);
480 Self::collect_in_flow_non_hoisted(
481 child_bp,
482 child_layout,
483 current_path,
484 out,
485 order,
486 inherited_z,
487 root_z_key,
488 active_clip,
489 depth + 1,
490 );
491 current_path.pop();
492 }
493 }
494
495 for &(idx, child_bp, child_layout) in &paired {
497 if is_in_flow_non_sc(child_layout)
498 && child_layout.style.float == Float::None
499 && is_inline_level(child_layout)
500 {
501 current_path.push(idx);
502 Self::collect_in_flow_non_hoisted(
503 child_bp,
504 child_layout,
505 current_path,
506 out,
507 order,
508 inherited_z,
509 root_z_key,
510 active_clip,
511 depth + 1,
512 );
513 current_path.pop();
514 }
515 }
516 }
517
518 #[allow(clippy::too_many_arguments)]
519 fn collect_in_flow_non_hoisted(
520 bp: &NodeBlueprint,
521 layout: &LayoutNode,
522 current_path: &mut Vec<usize>,
523 out: &mut Vec<SpatialEntry>,
524 order: &mut usize,
525 inherited_z: i32,
526 root_z_key: i64,
527 active_clip: Option<Rect>,
528 depth: usize,
529 ) {
530 if depth >= 256 || layout.style.display == Display::None {
531 return;
532 }
533 let effective_z = layout.style.z_index.unwrap_or(inherited_z);
534 Self::emit_node_entry(
535 bp,
536 layout,
537 current_path,
538 out,
539 order,
540 effective_z,
541 root_z_key,
542 active_clip,
543 );
544 let child_clip = if layout.style.overflow_x != Overflow::Visible
545 || layout.style.overflow_y != Overflow::Visible
546 {
547 intersect_clip(active_clip, layout.geometry.border_box)
548 } else {
549 active_clip
550 };
551 Self::collect_direct_in_flow_children(
552 bp,
553 layout,
554 current_path,
555 out,
556 order,
557 effective_z,
558 root_z_key,
559 child_clip,
560 depth,
561 );
562 }
563
564 #[allow(clippy::too_many_arguments)]
565 fn collect_stacking_context(
566 bp: &NodeBlueprint,
567 layout: &LayoutNode,
568 current_path: &mut Vec<usize>,
569 out: &mut Vec<SpatialEntry>,
570 order: &mut usize,
571 effective_z: i32,
572 self_root_z_key: i64,
573 is_root: bool,
574 inherited_steps: &[super::hit_test::HitClipStep],
575 depth: usize,
576 ) {
577 if depth >= 256 || layout.style.display == Display::None {
578 return;
579 }
580
581 let eff_inherited = AppRuntime::effective_hit_clip_steps(layout, inherited_steps);
582 let self_clip = Self::steps_to_clip(eff_inherited);
583
584 Self::emit_node_entry(
586 bp,
587 layout,
588 current_path,
589 out,
590 order,
591 effective_z,
592 self_root_z_key,
593 self_clip,
594 );
595
596 let mut base_steps = Vec::with_capacity(eff_inherited.len() + 1);
597 base_steps.extend_from_slice(eff_inherited);
598 let own_step = AppRuntime::hit_clip_step_for(layout);
599 if own_step.clip.is_some() || own_step.is_abs_cb || own_step.is_fixed_cb {
600 base_steps.push(own_step);
601 }
602 let in_flow_clip = Self::steps_to_clip(&base_steps);
603
604 let fallback_bp = NodeBlueprint::Empty;
605 let mut negative_z = Vec::new();
606 let mut auto_or_zero_z = Vec::new();
607 let mut positive_z = Vec::new();
608 Self::collect_hoisted_participants(
609 bp,
610 layout,
611 &fallback_bp,
612 current_path,
613 &base_steps,
614 &mut negative_z,
615 &mut auto_or_zero_z,
616 &mut positive_z,
617 depth + 1,
618 );
619
620 negative_z.sort_by_key(|(_, l, _, _)| l.style.z_index.unwrap_or(0));
621 positive_z.sort_by_key(|(_, l, _, _)| l.style.z_index.unwrap_or(0));
622
623 for (c_bp, c_layout, mut c_path, c_steps) in negative_z {
625 let cz = c_layout.style.z_index.unwrap_or(0);
626 let child_root_key = if is_root { cz as i64 } else { self_root_z_key };
627 Self::collect_stacking_context(
628 c_bp,
629 c_layout,
630 &mut c_path,
631 out,
632 order,
633 cz,
634 child_root_key,
635 false,
636 &c_steps,
637 depth + 1,
638 );
639 }
640
641 let normal_root_key = if is_root { 0 } else { self_root_z_key };
643 Self::collect_direct_in_flow_children(
644 bp,
645 layout,
646 current_path,
647 out,
648 order,
649 effective_z,
650 normal_root_key,
651 in_flow_clip,
652 depth,
653 );
654
655 for (c_bp, c_layout, mut c_path, is_sc, c_steps) in auto_or_zero_z {
657 if is_sc {
658 let cz = c_layout.style.z_index.unwrap_or(effective_z);
659 Self::collect_stacking_context(
660 c_bp,
661 c_layout,
662 &mut c_path,
663 out,
664 order,
665 cz,
666 normal_root_key,
667 false,
668 &c_steps,
669 depth + 1,
670 );
671 } else {
672 let eff_c = AppRuntime::effective_hit_clip_steps(c_layout, &c_steps);
673 let c_clip = Self::steps_to_clip(eff_c);
674 Self::collect_in_flow_non_hoisted(
675 c_bp,
676 c_layout,
677 &mut c_path,
678 out,
679 order,
680 effective_z,
681 normal_root_key,
682 c_clip,
683 depth + 1,
684 );
685 }
686 }
687
688 for (c_bp, c_layout, mut c_path, c_steps) in positive_z {
690 let cz = c_layout.style.z_index.unwrap_or(0);
691 let child_root_key = if is_root { cz as i64 } else { self_root_z_key };
692 Self::collect_stacking_context(
693 c_bp,
694 c_layout,
695 &mut c_path,
696 out,
697 order,
698 cz,
699 child_root_key,
700 false,
701 &c_steps,
702 depth + 1,
703 );
704 }
705 }
706
707 fn frontmost_hittable_entry(&self, px: f32, py: f32) -> Option<&SpatialEntry> {
709 let mut top: Option<&SpatialEntry> = None;
710 for entry in self.entries.iter().rev() {
711 if entry.contains_clipped_point(px, py) {
712 match top {
713 None => top = Some(entry),
714 Some(cur) => {
715 if (entry.root_z_key, entry.order) > (cur.root_z_key, cur.order) {
716 top = Some(entry);
717 }
718 }
719 }
720 }
721 }
722 top
723 }
724
725 pub fn query_entity_at_point(&self, px: f32, py: f32) -> Option<EntityId> {
728 let top = self.frontmost_hittable_entry(px, py)?;
729 if top.entity_id.is_valid() {
730 return Some(top.entity_id);
731 }
732 let mut best: Option<&SpatialEntry> = None;
733 for entry in &self.entries {
734 if entry.entity_id.is_valid()
735 && entry.layout_path.len() <= top.layout_path.len()
736 && top.layout_path.starts_with(&entry.layout_path)
737 && best.is_none_or(|cur| entry.layout_path.len() >= cur.layout_path.len())
738 {
739 best = Some(entry);
740 }
741 }
742 best.map(|e| e.entity_id)
743 }
744
745 pub fn query_event_at_point(
749 &self,
750 px: f32,
751 py: f32,
752 event_type: EventType,
753 ) -> Option<(EntityId, Rc<dyn Fn(Event)>, Rect)> {
754 let top = self.frontmost_hittable_entry(px, py)?;
755 let mut best: Option<(&SpatialEntry, &Rc<dyn Fn(Event)>)> = None;
756 for entry in &self.entries {
757 if entry.layout_path.len() <= top.layout_path.len()
758 && top.layout_path.starts_with(&entry.layout_path)
759 {
760 for (ev, handler) in &entry.event_listeners {
761 if *ev == event_type {
762 if best.is_none_or(|(cur, _)| {
763 entry.layout_path.len() >= cur.layout_path.len()
764 }) {
765 best = Some((entry, handler));
766 }
767 break;
768 }
769 }
770 }
771 }
772 best.map(|(entry, handler)| (entry.entity_id, Rc::clone(handler), entry.bounds))
773 }
774
775 pub fn get_bounds(&self, entity_id: EntityId) -> Option<Rect> {
777 let idx = self.entity_to_index.get(&entity_id)?;
778 Some(self.entries[*idx].bounds)
779 }
780
781 pub fn len(&self) -> usize {
783 self.entries.len()
784 }
785
786 pub fn is_empty(&self) -> bool {
788 self.entries.is_empty()
789 }
790}