strata-ui 0.1.6

Universal frontend framework in pure Rust with pixel-perfect CSS emulation and React/TSX ergonomics
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
//! Spatial acceleration index for hit-testing, point queries, and EntityId resolution.

use std::collections::HashMap;
use std::rc::Rc;
use strata_dom::{Event, EventType, NodeBlueprint};
use strata_layout::tree::LayoutNode;
use strata_layout::Rect;
use strata_primitives::EntityId;
use strata_style::types::{Display, Float, Overflow, PointerEvents, Position, Visibility};

use crate::runtime::AppRuntime;

/// An individual spatial entry for an entity in the layout hierarchy.
#[derive(Clone)]
pub struct SpatialEntry {
    pub entity_id: EntityId,
    pub bounds: Rect,
    pub event_listeners: Vec<(EventType, Rc<dyn Fn(Event)>)>,
    pub z_index: i32,
    pub order: usize,
    root_z_key: i64,
    clip_bounds: Option<Rect>,
    hittable: bool,
    layout_path: Vec<usize>,
}

impl SpatialEntry {
    #[inline]
    fn contains_clipped_point(&self, px: f32, py: f32) -> bool {
        if !self.hittable || !self.bounds.contains_point(px, py) {
            return false;
        }
        match self.clip_bounds {
            Some(clip) => clip.width >= 0.0 && clip.height >= 0.0 && clip.contains_point(px, py),
            None => true,
        }
    }
}

impl std::fmt::Debug for SpatialEntry {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SpatialEntry")
            .field("entity_id", &self.entity_id)
            .field("bounds", &self.bounds)
            .field("listeners_count", &self.event_listeners.len())
            .field("z_index", &self.z_index)
            .field("order", &self.order)
            .finish()
    }
}

#[inline]
fn intersect_clip(existing: Option<Rect>, next: Rect) -> Option<Rect> {
    match existing {
        None => Some(next),
        Some(prev) => {
            if prev.width < 0.0 || prev.height < 0.0 {
                return Some(prev);
            }
            let x0 = prev.x.max(next.x);
            let y0 = prev.y.max(next.y);
            let x1 = (prev.x + prev.width).min(next.x + next.width);
            let y1 = (prev.y + prev.height).min(next.y + next.height);
            if x1 < x0 || y1 < y0 {
                Some(Rect::new(0.0, 0.0, -1.0, -1.0))
            } else {
                Some(Rect::new(x0, y0, x1 - x0, y1 - y0))
            }
        }
    }
}

/// Accelerated spatial index maintaining entity bounding boxes and event listeners.
#[derive(Default, Clone, Debug)]
pub struct SpatialIndex {
    entries: Vec<SpatialEntry>,
    entity_to_index: HashMap<EntityId, usize>,
}

impl SpatialIndex {
    /// Creates a new empty spatial index.
    pub fn new() -> Self {
        Self {
            entries: Vec::new(),
            entity_to_index: HashMap::new(),
        }
    }

    /// Synchronizes cached entry bounding boxes from `layout_root` in O(entries) without
    /// walking blueprints or reallocating the index (used on high-frequency scroll ticks).
    pub fn sync_bounds(&mut self, layout_root: &LayoutNode) {
        if self.entries.is_empty() {
            return;
        }
        for entry in &mut self.entries {
            let mut cur = layout_root;
            let mut valid = true;
            for &idx in &entry.layout_path {
                if let Some(child) = cur.children.get(idx) {
                    cur = child;
                } else {
                    valid = false;
                    break;
                }
            }
            if valid {
                entry.bounds = cur.geometry.border_box;
            }
        }
    }

    /// Synchronizes cached entry bounding boxes only for descendants of `prefix`, avoiding
    /// unrelated root-to-node layout walks on high-frequency smooth scroll ticks.
    pub fn sync_bounds_for_prefix(&mut self, layout_root: &LayoutNode, prefix: &[usize]) {
        if self.entries.is_empty() {
            return;
        }
        if prefix.is_empty() {
            self.sync_bounds(layout_root);
            return;
        }
        let mut prefix_root = layout_root;
        for &idx in prefix {
            if let Some(child) = prefix_root.children.get(idx) {
                prefix_root = child;
            } else {
                return;
            }
        }
        let prefix_len = prefix.len();
        for entry in &mut self.entries {
            if entry.layout_path.len() <= prefix_len || !entry.layout_path.starts_with(prefix) {
                continue;
            }
            let mut cur = prefix_root;
            let mut valid = true;
            for &idx in &entry.layout_path[prefix_len..] {
                if let Some(child) = cur.children.get(idx) {
                    cur = child;
                } else {
                    valid = false;
                    break;
                }
            }
            if valid {
                entry.bounds = cur.geometry.border_box;
            }
        }
    }

    fn collect_top_layer_portals<'a>(
        bp: &'a NodeBlueprint,
        layout: &'a LayoutNode,
        fallback_bp: &'a NodeBlueprint,
        current_path: &mut Vec<usize>,
        out: &mut Vec<(&'a NodeBlueprint, &'a LayoutNode, Vec<usize>)>,
        depth: usize,
    ) {
        if depth >= 256 {
            return;
        }
        for (idx, child_bp, child_layout) in
            Self::paired_children_with_fallback(bp, layout, fallback_bp)
        {
            if child_layout.style.display == Display::None {
                continue;
            }
            current_path.push(idx);
            if child_layout.is_top_layer {
                out.push((child_bp, child_layout, current_path.clone()));
            }
            if !child_layout.children.is_empty() {
                Self::collect_top_layer_portals(
                    child_bp,
                    child_layout,
                    fallback_bp,
                    current_path,
                    out,
                    depth + 1,
                );
            }
            current_path.pop();
        }
    }

    /// Clears and rebuilds the spatial index from the active blueprint and computed layout hierarchy.
    pub fn rebuild(&mut self, blueprint: &NodeBlueprint, layout: &LayoutNode) {
        self.entries.clear();
        self.entity_to_index.clear();

        let mut order = 0;
        let mut path = Vec::new();
        let root_z = layout.style.z_index.unwrap_or(0);
        Self::collect_stacking_context(
            blueprint,
            layout,
            &mut path,
            &mut self.entries,
            &mut order,
            root_z,
            i64::MIN,
            true,
            &[],
            0,
        );

        let fallback_bp = NodeBlueprint::Empty;
        let mut portals = Vec::new();
        path.clear();
        Self::collect_top_layer_portals(
            blueprint,
            layout,
            &fallback_bp,
            &mut path,
            &mut portals,
            0,
        );
        for (p_bp, p_layout, mut p_path) in portals {
            let p_z = p_layout.style.z_index.unwrap_or(0);
            Self::collect_stacking_context(
                p_bp,
                p_layout,
                &mut p_path,
                &mut self.entries,
                &mut order,
                p_z,
                i64::MAX,
                false,
                &[],
                1,
            );
        }

        for (idx, entry) in self.entries.iter().enumerate() {
            if entry.entity_id.is_valid() {
                self.entity_to_index.insert(entry.entity_id, idx);
            }
        }
    }

    #[inline]
    fn steps_to_clip(steps: &[super::hit_test::HitClipStep]) -> Option<Rect> {
        let mut acc: Option<Rect> = None;
        for s in steps {
            if let Some(r) = s.clip {
                acc = intersect_clip(acc, r);
            }
        }
        acc
    }

    #[allow(clippy::too_many_arguments)]
    fn emit_node_entry(
        blueprint: &NodeBlueprint,
        layout: &LayoutNode,
        layout_path: &[usize],
        out: &mut Vec<SpatialEntry>,
        order: &mut usize,
        effective_z: i32,
        root_z_key: i64,
        active_clip: Option<Rect>,
    ) {
        let entity_id = layout.entity_id;
        let bounds = layout.geometry.border_box;
        let mut listeners = Vec::new();

        if let NodeBlueprint::Element { attributes, .. } = blueprint {
            for attr in attributes {
                if let strata_dom::Attribute::EventListener { event, handler } = attr {
                    listeners.push((*event, Rc::clone(handler)));
                }
            }
        }

        let hittable = !matches!(layout.style.visibility, Visibility::Hidden)
            && !matches!(layout.style.pointer_events, PointerEvents::None);
        let is_visual_element = matches!(blueprint, NodeBlueprint::Element { .. });
        if entity_id.is_valid() || !listeners.is_empty() || (is_visual_element && hittable) {
            let entry = SpatialEntry {
                entity_id,
                bounds,
                event_listeners: listeners,
                z_index: effective_z,
                order: *order,
                root_z_key,
                clip_bounds: active_clip,
                hittable,
                layout_path: layout_path.to_vec(),
            };
            *order += 1;
            out.push(entry);
        }
    }

    fn paired_children_with_fallback<'a>(
        node_bp: &'a NodeBlueprint,
        node_layout: &'a LayoutNode,
        fallback_bp: &'a NodeBlueprint,
    ) -> Vec<(usize, &'a NodeBlueprint, &'a LayoutNode)> {
        let mut flat_children = Vec::new();
        match node_bp {
            NodeBlueprint::Element { children, .. } | NodeBlueprint::Fragment(children) => {
                for c in children {
                    AppRuntime::flatten_blueprints(c, &mut flat_children);
                }
            }
            _ => {}
        }

        let mut out = Vec::with_capacity(node_layout.children.len());
        for (idx, child_layout) in node_layout.children.iter().enumerate() {
            let resolved_bp = if child_layout.entity_id.is_valid() {
                if let Some(&cand) = flat_children.get(idx) {
                    if cand.entity_id() == Some(child_layout.entity_id) {
                        cand
                    } else {
                        node_bp
                            .find_by_entity_id(child_layout.entity_id)
                            .unwrap_or(cand)
                    }
                } else {
                    node_bp
                        .find_by_entity_id(child_layout.entity_id)
                        .unwrap_or(fallback_bp)
                }
            } else {
                flat_children.get(idx).copied().unwrap_or(fallback_bp)
            };
            out.push((idx, resolved_bp, child_layout));
        }
        out
    }

    #[allow(clippy::too_many_arguments, clippy::type_complexity)]
    fn collect_hoisted_participants<'a>(
        bp: &'a NodeBlueprint,
        layout: &'a LayoutNode,
        fallback_bp: &'a NodeBlueprint,
        current_path: &mut Vec<usize>,
        steps: &[super::hit_test::HitClipStep],
        negative_z: &mut Vec<(
            &'a NodeBlueprint,
            &'a LayoutNode,
            Vec<usize>,
            Vec<super::hit_test::HitClipStep>,
        )>,
        auto_or_zero_z: &mut Vec<(
            &'a NodeBlueprint,
            &'a LayoutNode,
            Vec<usize>,
            bool,
            Vec<super::hit_test::HitClipStep>,
        )>,
        positive_z: &mut Vec<(
            &'a NodeBlueprint,
            &'a LayoutNode,
            Vec<usize>,
            Vec<super::hit_test::HitClipStep>,
        )>,
        depth: usize,
    ) {
        if depth >= 256 {
            return;
        }
        let parent_display = Some(layout.style.display);
        for (idx, child_bp, child_layout) in
            Self::paired_children_with_fallback(bp, layout, fallback_bp)
        {
            if child_layout.style.display == Display::None || child_layout.is_top_layer {
                continue;
            }
            current_path.push(idx);
            if AppRuntime::establishes_stacking_context_in(child_layout, parent_display, false) {
                let eff_steps = AppRuntime::effective_hit_clip_steps(child_layout, steps).to_vec();
                let z = child_layout.style.z_index.unwrap_or(0);
                if z < 0 {
                    negative_z.push((child_bp, child_layout, current_path.clone(), eff_steps));
                } else if z > 0 {
                    positive_z.push((child_bp, child_layout, current_path.clone(), eff_steps));
                } else {
                    auto_or_zero_z.push((
                        child_bp,
                        child_layout,
                        current_path.clone(),
                        true,
                        eff_steps,
                    ));
                }
            } else {
                let eff_for_child = AppRuntime::effective_hit_clip_steps(child_layout, steps);
                if child_layout.style.position != Position::Static {
                    auto_or_zero_z.push((
                        child_bp,
                        child_layout,
                        current_path.clone(),
                        false,
                        eff_for_child.to_vec(),
                    ));
                }
                let mut child_steps = Vec::with_capacity(eff_for_child.len() + 1);
                child_steps.extend_from_slice(eff_for_child);
                let step = AppRuntime::hit_clip_step_for(child_layout);
                if step.clip.is_some() || step.is_abs_cb || step.is_fixed_cb {
                    child_steps.push(step);
                }
                Self::collect_hoisted_participants(
                    child_bp,
                    child_layout,
                    fallback_bp,
                    current_path,
                    &child_steps,
                    negative_z,
                    auto_or_zero_z,
                    positive_z,
                    depth + 1,
                );
            }
            current_path.pop();
        }
    }

    #[allow(clippy::too_many_arguments)]
    fn collect_direct_in_flow_children(
        bp: &NodeBlueprint,
        layout: &LayoutNode,
        current_path: &mut Vec<usize>,
        out: &mut Vec<SpatialEntry>,
        order: &mut usize,
        inherited_z: i32,
        root_z_key: i64,
        active_clip: Option<Rect>,
        depth: usize,
    ) {
        let fallback_bp = NodeBlueprint::Empty;
        let paired = Self::paired_children_with_fallback(bp, layout, &fallback_bp);
        if paired.is_empty() {
            return;
        }

        let parent_display = Some(layout.style.display);
        let is_in_flow_non_sc = |c: &LayoutNode| {
            c.style.display != Display::None
                && !c.is_top_layer
                && !AppRuntime::establishes_stacking_context_in(c, parent_display, false)
                && c.style.position == Position::Static
        };
        let is_inline_level = |c: &LayoutNode| {
            matches!(
                c.style.display,
                Display::Inline | Display::InlineBlock | Display::InlineFlex | Display::InlineGrid
            )
        };

        // Layer 3: In-flow blocks
        for &(idx, child_bp, child_layout) in &paired {
            if is_in_flow_non_sc(child_layout)
                && child_layout.style.float == Float::None
                && !is_inline_level(child_layout)
            {
                current_path.push(idx);
                Self::collect_in_flow_non_hoisted(
                    child_bp,
                    child_layout,
                    current_path,
                    out,
                    order,
                    inherited_z,
                    root_z_key,
                    active_clip,
                    depth + 1,
                );
                current_path.pop();
            }
        }

        // Layer 4: Floats
        for &(idx, child_bp, child_layout) in &paired {
            if is_in_flow_non_sc(child_layout) && child_layout.style.float != Float::None {
                current_path.push(idx);
                Self::collect_in_flow_non_hoisted(
                    child_bp,
                    child_layout,
                    current_path,
                    out,
                    order,
                    inherited_z,
                    root_z_key,
                    active_clip,
                    depth + 1,
                );
                current_path.pop();
            }
        }

        // Layer 5: In-flow inlines
        for &(idx, child_bp, child_layout) in &paired {
            if is_in_flow_non_sc(child_layout)
                && child_layout.style.float == Float::None
                && is_inline_level(child_layout)
            {
                current_path.push(idx);
                Self::collect_in_flow_non_hoisted(
                    child_bp,
                    child_layout,
                    current_path,
                    out,
                    order,
                    inherited_z,
                    root_z_key,
                    active_clip,
                    depth + 1,
                );
                current_path.pop();
            }
        }
    }

    #[allow(clippy::too_many_arguments)]
    fn collect_in_flow_non_hoisted(
        bp: &NodeBlueprint,
        layout: &LayoutNode,
        current_path: &mut Vec<usize>,
        out: &mut Vec<SpatialEntry>,
        order: &mut usize,
        inherited_z: i32,
        root_z_key: i64,
        active_clip: Option<Rect>,
        depth: usize,
    ) {
        if depth >= 256 || layout.style.display == Display::None {
            return;
        }
        let effective_z = layout.style.z_index.unwrap_or(inherited_z);
        Self::emit_node_entry(
            bp,
            layout,
            current_path,
            out,
            order,
            effective_z,
            root_z_key,
            active_clip,
        );
        let child_clip = if layout.style.overflow_x != Overflow::Visible
            || layout.style.overflow_y != Overflow::Visible
        {
            intersect_clip(active_clip, layout.geometry.border_box)
        } else {
            active_clip
        };
        Self::collect_direct_in_flow_children(
            bp,
            layout,
            current_path,
            out,
            order,
            effective_z,
            root_z_key,
            child_clip,
            depth,
        );
    }

    #[allow(clippy::too_many_arguments)]
    fn collect_stacking_context(
        bp: &NodeBlueprint,
        layout: &LayoutNode,
        current_path: &mut Vec<usize>,
        out: &mut Vec<SpatialEntry>,
        order: &mut usize,
        effective_z: i32,
        self_root_z_key: i64,
        is_root: bool,
        inherited_steps: &[super::hit_test::HitClipStep],
        depth: usize,
    ) {
        if depth >= 256 || layout.style.display == Display::None {
            return;
        }

        let eff_inherited = AppRuntime::effective_hit_clip_steps(layout, inherited_steps);
        let self_clip = Self::steps_to_clip(eff_inherited);

        // Layer 1: Stacking context root element itself
        Self::emit_node_entry(
            bp,
            layout,
            current_path,
            out,
            order,
            effective_z,
            self_root_z_key,
            self_clip,
        );

        let mut base_steps = Vec::with_capacity(eff_inherited.len() + 1);
        base_steps.extend_from_slice(eff_inherited);
        let own_step = AppRuntime::hit_clip_step_for(layout);
        if own_step.clip.is_some() || own_step.is_abs_cb || own_step.is_fixed_cb {
            base_steps.push(own_step);
        }
        let in_flow_clip = Self::steps_to_clip(&base_steps);

        let fallback_bp = NodeBlueprint::Empty;
        let mut negative_z = Vec::new();
        let mut auto_or_zero_z = Vec::new();
        let mut positive_z = Vec::new();
        Self::collect_hoisted_participants(
            bp,
            layout,
            &fallback_bp,
            current_path,
            &base_steps,
            &mut negative_z,
            &mut auto_or_zero_z,
            &mut positive_z,
            depth + 1,
        );

        negative_z.sort_by_key(|(_, l, _, _)| l.style.z_index.unwrap_or(0));
        positive_z.sort_by_key(|(_, l, _, _)| l.style.z_index.unwrap_or(0));

        // Layer 2: Child stacking contexts with negative z-index (ascending)
        for (c_bp, c_layout, mut c_path, c_steps) in negative_z {
            let cz = c_layout.style.z_index.unwrap_or(0);
            let child_root_key = if is_root { cz as i64 } else { self_root_z_key };
            Self::collect_stacking_context(
                c_bp,
                c_layout,
                &mut c_path,
                out,
                order,
                cz,
                child_root_key,
                false,
                &c_steps,
                depth + 1,
            );
        }

        // Layers 3, 4, 5: In-flow blocks, floats, and inlines
        let normal_root_key = if is_root { 0 } else { self_root_z_key };
        Self::collect_direct_in_flow_children(
            bp,
            layout,
            current_path,
            out,
            order,
            effective_z,
            normal_root_key,
            in_flow_clip,
            depth,
        );

        // Layer 6: Positioned descendants with z-index: auto and child stacking contexts with z-index: 0
        for (c_bp, c_layout, mut c_path, is_sc, c_steps) in auto_or_zero_z {
            if is_sc {
                let cz = c_layout.style.z_index.unwrap_or(effective_z);
                Self::collect_stacking_context(
                    c_bp,
                    c_layout,
                    &mut c_path,
                    out,
                    order,
                    cz,
                    normal_root_key,
                    false,
                    &c_steps,
                    depth + 1,
                );
            } else {
                let eff_c = AppRuntime::effective_hit_clip_steps(c_layout, &c_steps);
                let c_clip = Self::steps_to_clip(eff_c);
                Self::collect_in_flow_non_hoisted(
                    c_bp,
                    c_layout,
                    &mut c_path,
                    out,
                    order,
                    effective_z,
                    normal_root_key,
                    c_clip,
                    depth + 1,
                );
            }
        }

        // Layer 7: Child stacking contexts with positive z-index (ascending)
        for (c_bp, c_layout, mut c_path, c_steps) in positive_z {
            let cz = c_layout.style.z_index.unwrap_or(0);
            let child_root_key = if is_root { cz as i64 } else { self_root_z_key };
            Self::collect_stacking_context(
                c_bp,
                c_layout,
                &mut c_path,
                out,
                order,
                cz,
                child_root_key,
                false,
                &c_steps,
                depth + 1,
            );
        }
    }

    /// Resolves the single front-most hittable entry containing `(px, py)`.
    fn frontmost_hittable_entry(&self, px: f32, py: f32) -> Option<&SpatialEntry> {
        let mut top: Option<&SpatialEntry> = None;
        for entry in self.entries.iter().rev() {
            if entry.contains_clipped_point(px, py) {
                match top {
                    None => top = Some(entry),
                    Some(cur) => {
                        if (entry.root_z_key, entry.order) > (cur.root_z_key, cur.order) {
                            top = Some(entry);
                        }
                    }
                }
            }
        }
        top
    }

    /// Queries the front-most / deepest EntityId at point (px, py), honoring stacking `z_index`
    /// and paint order without piercing through opaque higher-z overlays.
    pub fn query_entity_at_point(&self, px: f32, py: f32) -> Option<EntityId> {
        let top = self.frontmost_hittable_entry(px, py)?;
        if top.entity_id.is_valid() {
            return Some(top.entity_id);
        }
        let mut best: Option<&SpatialEntry> = None;
        for entry in &self.entries {
            if entry.entity_id.is_valid()
                && entry.layout_path.len() <= top.layout_path.len()
                && top.layout_path.starts_with(&entry.layout_path)
                && best.is_none_or(|cur| entry.layout_path.len() >= cur.layout_path.len())
            {
                best = Some(entry);
            }
        }
        best.map(|e| e.entity_id)
    }

    /// Queries the front-most event listener registered for `event_type` at point (px, py),
    /// matching W3C DOM non-piercing hit-testing: resolves the single front-most visual target
    /// first, then searches strictly along its DOM ancestor `layout_path`.
    pub fn query_event_at_point(
        &self,
        px: f32,
        py: f32,
        event_type: EventType,
    ) -> Option<(EntityId, Rc<dyn Fn(Event)>, Rect)> {
        let top = self.frontmost_hittable_entry(px, py)?;
        let mut best: Option<(&SpatialEntry, &Rc<dyn Fn(Event)>)> = None;
        for entry in &self.entries {
            if entry.layout_path.len() <= top.layout_path.len()
                && top.layout_path.starts_with(&entry.layout_path)
            {
                for (ev, handler) in &entry.event_listeners {
                    if *ev == event_type {
                        if best.is_none_or(|(cur, _)| {
                            entry.layout_path.len() >= cur.layout_path.len()
                        }) {
                            best = Some((entry, handler));
                        }
                        break;
                    }
                }
            }
        }
        best.map(|(entry, handler)| (entry.entity_id, Rc::clone(handler), entry.bounds))
    }

    /// Returns the bounding box of an entity if present in the index.
    pub fn get_bounds(&self, entity_id: EntityId) -> Option<Rect> {
        let idx = self.entity_to_index.get(&entity_id)?;
        Some(self.entries[*idx].bounds)
    }

    /// Returns the total number of indexed spatial entries.
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Returns true if the index has no spatial entries.
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }
}