Skip to main content

fission_core/
hit_test.rs

1use crate::env::ScrollStateMap;
2use crate::ui::custom_render::downcast_render_object;
3use fission_diagnostics::prelude as diag;
4use fission_ir::{CoreIR, LayoutOp, NodeId, Op};
5use fission_layout::{LayoutPoint, LayoutSnapshot};
6use glam::{Mat4, Vec4};
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9pub enum FocusDirection {
10    Up,
11    Down,
12    Left,
13    Right,
14}
15
16pub fn hit_test(
17    ir: &CoreIR,
18    layout: &LayoutSnapshot,
19    scroll_map: &ScrollStateMap,
20    point: LayoutPoint,
21) -> Option<NodeId> {
22    hit_test_internal(ir, layout, Some(scroll_map), point)
23}
24
25pub fn hit_test_with_scroll(
26    ir: &CoreIR,
27    layout: &LayoutSnapshot,
28    scroll_map: &ScrollStateMap,
29    point: LayoutPoint,
30) -> Option<NodeId> {
31    hit_test_internal(ir, layout, Some(scroll_map), point)
32}
33
34fn hit_test_internal(
35    ir: &CoreIR,
36    layout: &LayoutSnapshot,
37    scroll_map: Option<&ScrollStateMap>,
38    point: LayoutPoint,
39) -> Option<NodeId> {
40    let result = ir
41        .root
42        .and_then(|root| hit_test_recursive(root, ir, layout, scroll_map, point));
43
44    if let Some(id) = result {
45        diag::emit(
46            diag::DiagCategory::Input,
47            diag::DiagLevel::Debug,
48            diag::DiagEventKind::InputEvent {
49                kind: "hit_test_result".into(),
50                target: Some(id.as_u128()),
51                position: Some((point.x, point.y)),
52            },
53        );
54    }
55    result
56}
57
58fn hit_test_recursive(
59    node_id: NodeId,
60    ir: &CoreIR,
61    layout: &LayoutSnapshot,
62    scroll_map: Option<&ScrollStateMap>,
63    point: LayoutPoint,
64) -> Option<NodeId> {
65    let node = ir.nodes.get(&node_id)?;
66    let geom = layout.get_node_geometry(node_id)?;
67
68    let is_clip_container = matches!(
69        node.op,
70        Op::Layout(LayoutOp::Clip { .. }) | Op::Layout(LayoutOp::Scroll { .. })
71    );
72
73    if is_clip_container && !geom.rect.contains(point) {
74        return None;
75    }
76
77    let mut child_point = point;
78
79    if let (Some(map), Op::Layout(LayoutOp::Scroll { direction, .. })) = (scroll_map, &node.op) {
80        let offset = map.get_offset(node_id);
81        match direction {
82            fission_ir::FlexDirection::Column => {
83                child_point.y += offset;
84            }
85            fission_ir::FlexDirection::Row => {
86                child_point.x += offset;
87            }
88        }
89    }
90
91    if let Op::Layout(LayoutOp::Transform { transform }) = &node.op {
92        let mat = Mat4::from_cols_array(transform);
93        let inv = mat.inverse();
94        let local_x = point.x - geom.rect.origin.x;
95        let local_y = point.y - geom.rect.origin.y;
96        let p = Vec4::new(local_x, local_y, 0.0, 1.0);
97        let transformed = inv * p;
98        child_point = LayoutPoint::new(
99            transformed.x + geom.rect.origin.x,
100            transformed.y + geom.rect.origin.y,
101        );
102    }
103
104    for child_id in node.children.iter().rev() {
105        if let Some(hit) = hit_test_recursive(*child_id, ir, layout, scroll_map, child_point) {
106            return Some(hit);
107        }
108    }
109
110    // --- Custom render object hit-test ----------------------------------
111    // If this node has a custom render object, delegate to it before
112    // falling through to the standard semantics-based check.
113    if geom.rect.contains(point) {
114        if let Some(any_ro) = ir.custom_render_objects.get(&node_id) {
115            if let Some(render_obj) = downcast_render_object(any_ro) {
116                let local_point =
117                    LayoutPoint::new(point.x - geom.rect.origin.x, point.y - geom.rect.origin.y);
118                let result = render_obj.hit_test(local_point, geom.rect);
119                if result.hit {
120                    return Some(node_id);
121                }
122            }
123        }
124    }
125
126    let mut current_is_hit = false;
127    if geom.rect.contains(point) {
128        match &node.op {
129            Op::Layout(LayoutOp::Scroll { .. }) | Op::Layout(LayoutOp::Embed { .. }) => {
130                current_is_hit = true;
131            }
132            Op::Semantics(semantics) => {
133                if !semantics.actions.entries.is_empty()
134                    || semantics.focusable
135                    || semantics.draggable
136                    || semantics.scrollable_x
137                    || semantics.scrollable_y
138                {
139                    current_is_hit = true;
140                }
141            }
142            _ => {}
143        }
144    }
145
146    if current_is_hit {
147        Some(node_id)
148    } else {
149        None
150    }
151}
152
153pub fn find_next_focus_node(ir: &CoreIR, current: Option<NodeId>, reverse: bool) -> Option<NodeId> {
154    // Identify current scope if focused node is provided
155    let (current_scope_id, current_is_barrier) = if let Some(id) = current {
156        let scope = find_parent_scope(id, ir);
157        let mut is_barrier = false;
158        if let Some(sid) = scope {
159            if let Some(node) = ir.nodes.get(&sid) {
160                if let Op::Semantics(s) = &node.op {
161                    is_barrier = s.is_focus_barrier;
162                }
163            }
164        }
165        (scope, is_barrier)
166    } else {
167        (None, false)
168    };
169
170    let nodes_in_scope = if current_is_barrier {
171        let scope_id = current_scope_id.unwrap();
172        let mut list = Vec::new();
173        // Start recursion on CHILDREN of the barrier root to avoid skipping it
174        if let Some(node) = ir.nodes.get(&scope_id) {
175            for child in &node.children {
176                collect_focusable_nodes(*child, ir, &mut list, true, 0);
177            }
178        }
179        sort_focusable_nodes(ir, list)
180    } else {
181        get_all_focusable_nodes(ir)
182    };
183
184    if nodes_in_scope.is_empty() {
185        return None;
186    }
187
188    let idx = if let Some(curr_id) = current {
189        nodes_in_scope.iter().position(|id| *id == curr_id)
190    } else {
191        None
192    };
193
194    match idx {
195        Some(i) => {
196            if reverse {
197                if i == 0 {
198                    Some(nodes_in_scope[nodes_in_scope.len() - 1])
199                } else {
200                    Some(nodes_in_scope[i - 1])
201                }
202            } else if i == nodes_in_scope.len() - 1 {
203                Some(nodes_in_scope[0])
204            } else {
205                Some(nodes_in_scope[i + 1])
206            }
207        }
208        None => {
209            if reverse {
210                Some(nodes_in_scope[nodes_in_scope.len() - 1])
211            } else {
212                Some(nodes_in_scope[0])
213            }
214        }
215    }
216}
217
218pub fn get_all_focusable_nodes(ir: &CoreIR) -> Vec<NodeId> {
219    let mut list = Vec::new();
220    if let Some(root) = ir.root {
221        collect_focusable_nodes(root, ir, &mut list, false, 0);
222    }
223    sort_focusable_nodes(ir, list)
224}
225
226fn sort_focusable_nodes(ir: &CoreIR, mut list: Vec<(NodeId, usize)>) -> Vec<NodeId> {
227    list.sort_by(|(id_a, order_a), (id_b, order_b)| {
228        let idx_a = ir.nodes.get(id_a).and_then(|n| {
229            if let Op::Semantics(s) = &n.op {
230                s.focus_index
231            } else {
232                None
233            }
234        });
235        let idx_b = ir.nodes.get(id_b).and_then(|n| {
236            if let Op::Semantics(s) = &n.op {
237                s.focus_index
238            } else {
239                None
240            }
241        });
242
243        match (idx_a, idx_b) {
244            (Some(a), Some(b)) => a.cmp(&b).then(order_a.cmp(order_b)),
245            (Some(_), None) => std::cmp::Ordering::Less,
246            (None, Some(_)) => std::cmp::Ordering::Greater,
247            (None, None) => order_a.cmp(order_b),
248        }
249    });
250    list.into_iter().map(|(id, _)| id).collect()
251}
252
253fn collect_focusable_nodes(
254    node_id: NodeId,
255    ir: &CoreIR,
256    list: &mut Vec<(NodeId, usize)>,
257    stop_at_barriers: bool,
258    mut order: usize,
259) {
260    if let Some(node) = ir.nodes.get(&node_id) {
261        let mut is_barrier = false;
262        if let Op::Semantics(s) = &node.op {
263            if s.focusable && !s.disabled {
264                list.push((node_id, order));
265                order += 1;
266            }
267            is_barrier = s.is_focus_barrier;
268        }
269
270        if stop_at_barriers && is_barrier {
271            return;
272        }
273
274        let mut children = node.children.clone();
275        // Internal sort within branches still useful for tree-order
276        children.sort_by_key(|cid| {
277            ir.nodes
278                .get(cid)
279                .and_then(|n| {
280                    if let Op::Semantics(s) = &n.op {
281                        s.focus_index
282                    } else {
283                        None
284                    }
285                })
286                .unwrap_or(i32::MAX)
287        });
288
289        for child in children {
290            collect_focusable_nodes(child, ir, list, stop_at_barriers, order);
291            order = list.last().map(|(_, o)| *o + 1).unwrap_or(order);
292        }
293    }
294}
295
296fn find_parent_scope(node_id: NodeId, ir: &CoreIR) -> Option<NodeId> {
297    let mut curr = ir.nodes.get(&node_id)?.parent;
298    while let Some(pid) = curr {
299        if let Some(node) = ir.nodes.get(&pid) {
300            if let Op::Semantics(s) = &node.op {
301                if s.is_focus_scope {
302                    return Some(pid);
303                }
304            }
305            curr = node.parent;
306        } else {
307            break;
308        }
309    }
310    None
311}
312
313pub fn find_neighbor_focus_node(
314    ir: &CoreIR,
315    layout: &LayoutSnapshot,
316    current: NodeId,
317    direction: FocusDirection,
318) -> Option<NodeId> {
319    let current_rect = layout.get_node_rect(current)?;
320    let focusable_nodes = get_all_focusable_nodes(ir);
321
322    let mut best_candidate = None;
323    let mut best_dist = f32::INFINITY;
324
325    let (cx, cy) = (
326        current_rect.x() + current_rect.width() / 2.0,
327        current_rect.y() + current_rect.height() / 2.0,
328    );
329
330    for node_id in focusable_nodes {
331        if node_id == current {
332            continue;
333        }
334        let rect = match layout.get_node_rect(node_id) {
335            Some(r) => r,
336            None => continue,
337        };
338
339        let (nx, ny) = (
340            rect.x() + rect.width() / 2.0,
341            rect.y() + rect.height() / 2.0,
342        );
343
344        let is_in_dir = match direction {
345            FocusDirection::Up => ny < cy && (nx - cx).abs() < (ny - cy).abs(),
346            FocusDirection::Down => ny > cy && (nx - cx).abs() < (ny - cy).abs(),
347            FocusDirection::Left => nx < cx && (ny - cy).abs() < (nx - cx).abs(),
348            FocusDirection::Right => nx > cx && (ny - cy).abs() < (nx - cx).abs(),
349        };
350
351        if is_in_dir {
352            let dist = (nx - cx).powi(2) + (ny - cy).powi(2);
353            if dist < best_dist {
354                best_dist = dist;
355                best_candidate = Some(node_id);
356            }
357        }
358    }
359
360    best_candidate
361}