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 fn collect_top_layer_portals<'a>(
113 bp: &'a NodeBlueprint,
114 layout: &'a LayoutNode,
115 fallback_bp: &'a NodeBlueprint,
116 current_path: &mut Vec<usize>,
117 out: &mut Vec<(&'a NodeBlueprint, &'a LayoutNode, Vec<usize>)>,
118 depth: usize,
119 ) {
120 if depth >= 256 {
121 return;
122 }
123 for (idx, child_bp, child_layout) in
124 Self::paired_children_with_fallback(bp, layout, fallback_bp)
125 {
126 if child_layout.style.display == Display::None {
127 continue;
128 }
129 current_path.push(idx);
130 if child_layout.is_top_layer {
131 out.push((child_bp, child_layout, current_path.clone()));
132 }
133 if !child_layout.children.is_empty() {
134 Self::collect_top_layer_portals(
135 child_bp,
136 child_layout,
137 fallback_bp,
138 current_path,
139 out,
140 depth + 1,
141 );
142 }
143 current_path.pop();
144 }
145 }
146
147 pub fn rebuild(&mut self, blueprint: &NodeBlueprint, layout: &LayoutNode) {
149 self.entries.clear();
150 self.entity_to_index.clear();
151
152 let mut order = 0;
153 let mut path = Vec::new();
154 let root_z = layout.style.z_index.unwrap_or(0);
155 Self::collect_stacking_context(
156 blueprint,
157 layout,
158 &mut path,
159 &mut self.entries,
160 &mut order,
161 root_z,
162 i64::MIN,
163 true,
164 &[],
165 0,
166 );
167
168 let fallback_bp = NodeBlueprint::Empty;
169 let mut portals = Vec::new();
170 path.clear();
171 Self::collect_top_layer_portals(
172 blueprint,
173 layout,
174 &fallback_bp,
175 &mut path,
176 &mut portals,
177 0,
178 );
179 for (p_bp, p_layout, mut p_path) in portals {
180 let p_z = p_layout.style.z_index.unwrap_or(0);
181 Self::collect_stacking_context(
182 p_bp,
183 p_layout,
184 &mut p_path,
185 &mut self.entries,
186 &mut order,
187 p_z,
188 i64::MAX,
189 false,
190 &[],
191 1,
192 );
193 }
194
195 for (idx, entry) in self.entries.iter().enumerate() {
196 if entry.entity_id.is_valid() {
197 self.entity_to_index.insert(entry.entity_id, idx);
198 }
199 }
200 }
201
202 #[inline]
203 fn steps_to_clip(steps: &[super::hit_test::HitClipStep]) -> Option<Rect> {
204 let mut acc: Option<Rect> = None;
205 for s in steps {
206 if let Some(r) = s.clip {
207 acc = intersect_clip(acc, r);
208 }
209 }
210 acc
211 }
212
213 #[allow(clippy::too_many_arguments)]
214 fn emit_node_entry(
215 blueprint: &NodeBlueprint,
216 layout: &LayoutNode,
217 layout_path: &[usize],
218 out: &mut Vec<SpatialEntry>,
219 order: &mut usize,
220 effective_z: i32,
221 root_z_key: i64,
222 active_clip: Option<Rect>,
223 ) {
224 let entity_id = layout.entity_id;
225 let bounds = layout.geometry.border_box;
226 let mut listeners = Vec::new();
227
228 if let NodeBlueprint::Element { attributes, .. } = blueprint {
229 for attr in attributes {
230 if let strata_dom::Attribute::EventListener { event, handler } = attr {
231 listeners.push((*event, Rc::clone(handler)));
232 }
233 }
234 }
235
236 if entity_id.is_valid() || !listeners.is_empty() {
237 let hittable = !matches!(layout.style.visibility, Visibility::Hidden)
238 && !matches!(layout.style.pointer_events, PointerEvents::None);
239 let entry = SpatialEntry {
240 entity_id,
241 bounds,
242 event_listeners: listeners,
243 z_index: effective_z,
244 order: *order,
245 root_z_key,
246 clip_bounds: active_clip,
247 hittable,
248 layout_path: layout_path.to_vec(),
249 };
250 *order += 1;
251 out.push(entry);
252 }
253 }
254
255 fn paired_children_with_fallback<'a>(
256 node_bp: &'a NodeBlueprint,
257 node_layout: &'a LayoutNode,
258 fallback_bp: &'a NodeBlueprint,
259 ) -> Vec<(usize, &'a NodeBlueprint, &'a LayoutNode)> {
260 let mut flat_children = Vec::new();
261 match node_bp {
262 NodeBlueprint::Element { children, .. } | NodeBlueprint::Fragment(children) => {
263 for c in children {
264 AppRuntime::flatten_blueprints(c, &mut flat_children);
265 }
266 }
267 _ => {}
268 }
269
270 let mut out = Vec::with_capacity(node_layout.children.len());
271 for (idx, child_layout) in node_layout.children.iter().enumerate() {
272 let resolved_bp = if child_layout.entity_id.is_valid() {
273 if let Some(&cand) = flat_children.get(idx) {
274 if cand.entity_id() == Some(child_layout.entity_id) {
275 cand
276 } else {
277 node_bp
278 .find_by_entity_id(child_layout.entity_id)
279 .unwrap_or(cand)
280 }
281 } else {
282 node_bp
283 .find_by_entity_id(child_layout.entity_id)
284 .unwrap_or(fallback_bp)
285 }
286 } else {
287 flat_children.get(idx).copied().unwrap_or(fallback_bp)
288 };
289 out.push((idx, resolved_bp, child_layout));
290 }
291 out
292 }
293
294 #[allow(clippy::too_many_arguments, clippy::type_complexity)]
295 fn collect_hoisted_participants<'a>(
296 bp: &'a NodeBlueprint,
297 layout: &'a LayoutNode,
298 fallback_bp: &'a NodeBlueprint,
299 current_path: &mut Vec<usize>,
300 steps: &[super::hit_test::HitClipStep],
301 negative_z: &mut Vec<(
302 &'a NodeBlueprint,
303 &'a LayoutNode,
304 Vec<usize>,
305 Vec<super::hit_test::HitClipStep>,
306 )>,
307 auto_or_zero_z: &mut Vec<(
308 &'a NodeBlueprint,
309 &'a LayoutNode,
310 Vec<usize>,
311 bool,
312 Vec<super::hit_test::HitClipStep>,
313 )>,
314 positive_z: &mut Vec<(
315 &'a NodeBlueprint,
316 &'a LayoutNode,
317 Vec<usize>,
318 Vec<super::hit_test::HitClipStep>,
319 )>,
320 depth: usize,
321 ) {
322 if depth >= 256 {
323 return;
324 }
325 let parent_display = Some(layout.style.display);
326 for (idx, child_bp, child_layout) in
327 Self::paired_children_with_fallback(bp, layout, fallback_bp)
328 {
329 if child_layout.style.display == Display::None || child_layout.is_top_layer {
330 continue;
331 }
332 current_path.push(idx);
333 if AppRuntime::establishes_stacking_context_in(child_layout, parent_display, false) {
334 let eff_steps = AppRuntime::effective_hit_clip_steps(child_layout, steps).to_vec();
335 let z = child_layout.style.z_index.unwrap_or(0);
336 if z < 0 {
337 negative_z.push((child_bp, child_layout, current_path.clone(), eff_steps));
338 } else if z > 0 {
339 positive_z.push((child_bp, child_layout, current_path.clone(), eff_steps));
340 } else {
341 auto_or_zero_z.push((
342 child_bp,
343 child_layout,
344 current_path.clone(),
345 true,
346 eff_steps,
347 ));
348 }
349 } else {
350 let eff_for_child = AppRuntime::effective_hit_clip_steps(child_layout, steps);
351 if child_layout.style.position != Position::Static {
352 auto_or_zero_z.push((
353 child_bp,
354 child_layout,
355 current_path.clone(),
356 false,
357 eff_for_child.to_vec(),
358 ));
359 }
360 let mut child_steps = Vec::with_capacity(eff_for_child.len() + 1);
361 child_steps.extend_from_slice(eff_for_child);
362 let step = AppRuntime::hit_clip_step_for(child_layout);
363 if step.clip.is_some() || step.is_abs_cb || step.is_fixed_cb {
364 child_steps.push(step);
365 }
366 Self::collect_hoisted_participants(
367 child_bp,
368 child_layout,
369 fallback_bp,
370 current_path,
371 &child_steps,
372 negative_z,
373 auto_or_zero_z,
374 positive_z,
375 depth + 1,
376 );
377 }
378 current_path.pop();
379 }
380 }
381
382 #[allow(clippy::too_many_arguments)]
383 fn collect_direct_in_flow_children(
384 bp: &NodeBlueprint,
385 layout: &LayoutNode,
386 current_path: &mut Vec<usize>,
387 out: &mut Vec<SpatialEntry>,
388 order: &mut usize,
389 inherited_z: i32,
390 root_z_key: i64,
391 active_clip: Option<Rect>,
392 depth: usize,
393 ) {
394 let fallback_bp = NodeBlueprint::Empty;
395 let paired = Self::paired_children_with_fallback(bp, layout, &fallback_bp);
396 if paired.is_empty() {
397 return;
398 }
399
400 let parent_display = Some(layout.style.display);
401 let is_in_flow_non_sc = |c: &LayoutNode| {
402 c.style.display != Display::None
403 && !c.is_top_layer
404 && !AppRuntime::establishes_stacking_context_in(c, parent_display, false)
405 && c.style.position == Position::Static
406 };
407 let is_inline_level = |c: &LayoutNode| {
408 matches!(
409 c.style.display,
410 Display::Inline | Display::InlineBlock | Display::InlineFlex | Display::InlineGrid
411 )
412 };
413
414 for &(idx, child_bp, child_layout) in &paired {
416 if is_in_flow_non_sc(child_layout)
417 && child_layout.style.float == Float::None
418 && !is_inline_level(child_layout)
419 {
420 current_path.push(idx);
421 Self::collect_in_flow_non_hoisted(
422 child_bp,
423 child_layout,
424 current_path,
425 out,
426 order,
427 inherited_z,
428 root_z_key,
429 active_clip,
430 depth + 1,
431 );
432 current_path.pop();
433 }
434 }
435
436 for &(idx, child_bp, child_layout) in &paired {
438 if is_in_flow_non_sc(child_layout) && child_layout.style.float != Float::None {
439 current_path.push(idx);
440 Self::collect_in_flow_non_hoisted(
441 child_bp,
442 child_layout,
443 current_path,
444 out,
445 order,
446 inherited_z,
447 root_z_key,
448 active_clip,
449 depth + 1,
450 );
451 current_path.pop();
452 }
453 }
454
455 for &(idx, child_bp, child_layout) in &paired {
457 if is_in_flow_non_sc(child_layout)
458 && child_layout.style.float == Float::None
459 && is_inline_level(child_layout)
460 {
461 current_path.push(idx);
462 Self::collect_in_flow_non_hoisted(
463 child_bp,
464 child_layout,
465 current_path,
466 out,
467 order,
468 inherited_z,
469 root_z_key,
470 active_clip,
471 depth + 1,
472 );
473 current_path.pop();
474 }
475 }
476 }
477
478 #[allow(clippy::too_many_arguments)]
479 fn collect_in_flow_non_hoisted(
480 bp: &NodeBlueprint,
481 layout: &LayoutNode,
482 current_path: &mut Vec<usize>,
483 out: &mut Vec<SpatialEntry>,
484 order: &mut usize,
485 inherited_z: i32,
486 root_z_key: i64,
487 active_clip: Option<Rect>,
488 depth: usize,
489 ) {
490 if depth >= 256 || layout.style.display == Display::None {
491 return;
492 }
493 let effective_z = layout.style.z_index.unwrap_or(inherited_z);
494 Self::emit_node_entry(
495 bp,
496 layout,
497 current_path,
498 out,
499 order,
500 effective_z,
501 root_z_key,
502 active_clip,
503 );
504 let child_clip = if layout.style.overflow_x != Overflow::Visible
505 || layout.style.overflow_y != Overflow::Visible
506 {
507 intersect_clip(active_clip, layout.geometry.border_box)
508 } else {
509 active_clip
510 };
511 Self::collect_direct_in_flow_children(
512 bp,
513 layout,
514 current_path,
515 out,
516 order,
517 effective_z,
518 root_z_key,
519 child_clip,
520 depth,
521 );
522 }
523
524 #[allow(clippy::too_many_arguments)]
525 fn collect_stacking_context(
526 bp: &NodeBlueprint,
527 layout: &LayoutNode,
528 current_path: &mut Vec<usize>,
529 out: &mut Vec<SpatialEntry>,
530 order: &mut usize,
531 effective_z: i32,
532 self_root_z_key: i64,
533 is_root: bool,
534 inherited_steps: &[super::hit_test::HitClipStep],
535 depth: usize,
536 ) {
537 if depth >= 256 || layout.style.display == Display::None {
538 return;
539 }
540
541 let eff_inherited = AppRuntime::effective_hit_clip_steps(layout, inherited_steps);
542 let self_clip = Self::steps_to_clip(eff_inherited);
543
544 Self::emit_node_entry(
546 bp,
547 layout,
548 current_path,
549 out,
550 order,
551 effective_z,
552 self_root_z_key,
553 self_clip,
554 );
555
556 let mut base_steps = Vec::with_capacity(eff_inherited.len() + 1);
557 base_steps.extend_from_slice(eff_inherited);
558 let own_step = AppRuntime::hit_clip_step_for(layout);
559 if own_step.clip.is_some() || own_step.is_abs_cb || own_step.is_fixed_cb {
560 base_steps.push(own_step);
561 }
562 let in_flow_clip = Self::steps_to_clip(&base_steps);
563
564 let fallback_bp = NodeBlueprint::Empty;
565 let mut negative_z = Vec::new();
566 let mut auto_or_zero_z = Vec::new();
567 let mut positive_z = Vec::new();
568 Self::collect_hoisted_participants(
569 bp,
570 layout,
571 &fallback_bp,
572 current_path,
573 &base_steps,
574 &mut negative_z,
575 &mut auto_or_zero_z,
576 &mut positive_z,
577 depth + 1,
578 );
579
580 negative_z.sort_by_key(|(_, l, _, _)| l.style.z_index.unwrap_or(0));
581 positive_z.sort_by_key(|(_, l, _, _)| l.style.z_index.unwrap_or(0));
582
583 for (c_bp, c_layout, mut c_path, c_steps) in negative_z {
585 let cz = c_layout.style.z_index.unwrap_or(0);
586 let child_root_key = if is_root { cz as i64 } else { self_root_z_key };
587 Self::collect_stacking_context(
588 c_bp,
589 c_layout,
590 &mut c_path,
591 out,
592 order,
593 cz,
594 child_root_key,
595 false,
596 &c_steps,
597 depth + 1,
598 );
599 }
600
601 let normal_root_key = if is_root { 0 } else { self_root_z_key };
603 Self::collect_direct_in_flow_children(
604 bp,
605 layout,
606 current_path,
607 out,
608 order,
609 effective_z,
610 normal_root_key,
611 in_flow_clip,
612 depth,
613 );
614
615 for (c_bp, c_layout, mut c_path, is_sc, c_steps) in auto_or_zero_z {
617 if is_sc {
618 let cz = c_layout.style.z_index.unwrap_or(effective_z);
619 Self::collect_stacking_context(
620 c_bp,
621 c_layout,
622 &mut c_path,
623 out,
624 order,
625 cz,
626 normal_root_key,
627 false,
628 &c_steps,
629 depth + 1,
630 );
631 } else {
632 let eff_c = AppRuntime::effective_hit_clip_steps(c_layout, &c_steps);
633 let c_clip = Self::steps_to_clip(eff_c);
634 Self::collect_in_flow_non_hoisted(
635 c_bp,
636 c_layout,
637 &mut c_path,
638 out,
639 order,
640 effective_z,
641 normal_root_key,
642 c_clip,
643 depth + 1,
644 );
645 }
646 }
647
648 for (c_bp, c_layout, mut c_path, c_steps) in positive_z {
650 let cz = c_layout.style.z_index.unwrap_or(0);
651 let child_root_key = if is_root { cz as i64 } else { self_root_z_key };
652 Self::collect_stacking_context(
653 c_bp,
654 c_layout,
655 &mut c_path,
656 out,
657 order,
658 cz,
659 child_root_key,
660 false,
661 &c_steps,
662 depth + 1,
663 );
664 }
665 }
666
667 pub fn query_entity_at_point(&self, px: f32, py: f32) -> Option<EntityId> {
669 let mut best: Option<&SpatialEntry> = None;
670 for entry in self.entries.iter().rev() {
671 if entry.entity_id.is_valid() && entry.contains_clipped_point(px, py) {
672 match best {
673 None => best = Some(entry),
674 Some(cur) => {
675 if (entry.root_z_key, entry.order) > (cur.root_z_key, cur.order) {
676 best = Some(entry);
677 }
678 }
679 }
680 }
681 }
682 best.map(|e| e.entity_id)
683 }
684
685 pub fn query_event_at_point(
688 &self,
689 px: f32,
690 py: f32,
691 event_type: EventType,
692 ) -> Option<(EntityId, Rc<dyn Fn(Event)>, Rect)> {
693 let mut best: Option<(&SpatialEntry, &Rc<dyn Fn(Event)>)> = None;
694 for entry in self.entries.iter().rev() {
695 if entry.contains_clipped_point(px, py) {
696 for (ev, handler) in &entry.event_listeners {
697 if *ev == event_type {
698 match best {
699 None => best = Some((entry, handler)),
700 Some((cur, _)) => {
701 if (entry.root_z_key, entry.order) > (cur.root_z_key, cur.order) {
702 best = Some((entry, handler));
703 }
704 }
705 }
706 break;
707 }
708 }
709 }
710 }
711 best.map(|(entry, handler)| (entry.entity_id, Rc::clone(handler), entry.bounds))
712 }
713
714 pub fn get_bounds(&self, entity_id: EntityId) -> Option<Rect> {
716 let idx = self.entity_to_index.get(&entity_id)?;
717 Some(self.entries[*idx].bounds)
718 }
719
720 pub fn len(&self) -> usize {
722 self.entries.len()
723 }
724
725 pub fn is_empty(&self) -> bool {
727 self.entries.is_empty()
728 }
729}