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;
#[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))
}
}
}
}
#[derive(Default, Clone, Debug)]
pub struct SpatialIndex {
entries: Vec<SpatialEntry>,
entity_to_index: HashMap<EntityId, usize>,
}
impl SpatialIndex {
pub fn new() -> Self {
Self {
entries: Vec::new(),
entity_to_index: HashMap::new(),
}
}
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;
}
}
}
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();
}
}
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)));
}
}
}
if entity_id.is_valid() || !listeners.is_empty() {
let hittable = !matches!(layout.style.visibility, Visibility::Hidden)
&& !matches!(layout.style.pointer_events, PointerEvents::None);
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
)
};
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();
}
}
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();
}
}
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);
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));
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,
);
}
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,
);
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,
);
}
}
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,
);
}
}
pub fn query_entity_at_point(&self, px: f32, py: f32) -> Option<EntityId> {
let mut best: Option<&SpatialEntry> = None;
for entry in self.entries.iter().rev() {
if entry.entity_id.is_valid() && entry.contains_clipped_point(px, py) {
match best {
None => best = Some(entry),
Some(cur) => {
if (entry.root_z_key, entry.order) > (cur.root_z_key, cur.order) {
best = Some(entry);
}
}
}
}
}
best.map(|e| e.entity_id)
}
pub fn query_event_at_point(
&self,
px: f32,
py: f32,
event_type: EventType,
) -> Option<(EntityId, Rc<dyn Fn(Event)>, Rect)> {
let mut best: Option<(&SpatialEntry, &Rc<dyn Fn(Event)>)> = None;
for entry in self.entries.iter().rev() {
if entry.contains_clipped_point(px, py) {
for (ev, handler) in &entry.event_listeners {
if *ev == event_type {
match best {
None => best = Some((entry, handler)),
Some((cur, _)) => {
if (entry.root_z_key, entry.order) > (cur.root_z_key, cur.order) {
best = Some((entry, handler));
}
}
}
break;
}
}
}
}
best.map(|(entry, handler)| (entry.entity_id, Rc::clone(handler), entry.bounds))
}
pub fn get_bounds(&self, entity_id: EntityId) -> Option<Rect> {
let idx = self.entity_to_index.get(&entity_id)?;
Some(self.entries[*idx].bounds)
}
pub fn len(&self) -> usize {
self.entries.len()
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
}