fission-core 0.9.0

Core runtime, state, actions, effects, resources, input, and UI model for Fission
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
use crate::env::ScrollStateMap;
use crate::ui::custom_render::downcast_render_object;
use fission_diagnostics::prelude as diag;
use fission_ir::{CoreIR, LayoutOp, Op, PaintOp, WidgetId};
use fission_layout::{LayoutPoint, LayoutSnapshot};
use glam::{Mat4, Vec4};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FocusDirection {
    Up,
    Down,
    Left,
    Right,
}

pub fn hit_test(
    ir: &CoreIR,
    layout: &LayoutSnapshot,
    scroll_map: &ScrollStateMap,
    point: LayoutPoint,
) -> Option<WidgetId> {
    hit_test_internal(ir, layout, Some(scroll_map), point)
}

pub fn hit_test_with_scroll(
    ir: &CoreIR,
    layout: &LayoutSnapshot,
    scroll_map: &ScrollStateMap,
    point: LayoutPoint,
) -> Option<WidgetId> {
    hit_test_internal(ir, layout, Some(scroll_map), point)
}

fn hit_test_internal(
    ir: &CoreIR,
    layout: &LayoutSnapshot,
    scroll_map: Option<&ScrollStateMap>,
    point: LayoutPoint,
) -> Option<WidgetId> {
    let result = ir
        .root
        .and_then(|root| hit_test_recursive(root, ir, layout, scroll_map, point));

    if let Some(id) = result {
        diag::emit(
            diag::DiagCategory::Input,
            diag::DiagLevel::Debug,
            diag::DiagEventKind::InputEvent {
                kind: "hit_test_result".into(),
                target: Some(id.as_u128()),
                position: Some((point.x, point.y)),
            },
        );
    }
    result
}

fn hit_test_recursive(
    node_id: WidgetId,
    ir: &CoreIR,
    layout: &LayoutSnapshot,
    scroll_map: Option<&ScrollStateMap>,
    point: LayoutPoint,
) -> Option<WidgetId> {
    let node = ir.nodes.get(&node_id)?;
    let geom = layout.get_node_geometry(node_id)?;

    let is_clip_container = matches!(
        node.op,
        Op::Layout(LayoutOp::Clip { .. }) | Op::Layout(LayoutOp::Scroll { .. })
    );

    if is_clip_container && !geom.rect.contains(point) {
        return None;
    }

    let mut child_point = point;

    if let (Some(map), Op::Layout(LayoutOp::Scroll { direction, .. })) = (scroll_map, &node.op) {
        let offset = map.get_offset(node_id);
        match direction {
            fission_ir::FlexDirection::Column => {
                child_point.y += offset;
            }
            fission_ir::FlexDirection::Row => {
                child_point.x += offset;
            }
        }
    }

    if let Op::Layout(LayoutOp::Transform { transform }) = &node.op {
        let mat = Mat4::from_cols_array(transform);
        let inv = mat.inverse();
        let local_x = point.x - geom.rect.origin.x;
        let local_y = point.y - geom.rect.origin.y;
        let p = Vec4::new(local_x, local_y, 0.0, 1.0);
        let transformed = inv * p;
        child_point = LayoutPoint::new(
            transformed.x + geom.rect.origin.x,
            transformed.y + geom.rect.origin.y,
        );
    }

    for child_id in node.children.iter().rev() {
        if let Some(hit) = hit_test_recursive(*child_id, ir, layout, scroll_map, child_point) {
            return Some(hit);
        }
    }

    // --- Custom render object hit-test ----------------------------------
    // If this node has a custom render object, delegate to it before
    // falling through to the standard semantics-based check.
    if geom.rect.contains(point) {
        if let Some(any_ro) = ir.custom_render_objects.get(&node_id) {
            if let Some(render_obj) = downcast_render_object(any_ro) {
                let local_point =
                    LayoutPoint::new(point.x - geom.rect.origin.x, point.y - geom.rect.origin.y);
                let result = render_obj.hit_test(local_point, geom.rect);
                if result.hit {
                    return Some(node_id);
                }
            }
        }
    }

    if geom.rect.contains(point) && paint_op_blocks_hit_testing(&node.op) {
        return Some(node_id);
    }

    let mut current_is_hit = false;
    if geom.rect.contains(point) {
        match &node.op {
            Op::Layout(LayoutOp::Scroll { .. }) | Op::Layout(LayoutOp::Embed { .. }) => {
                current_is_hit = true;
            }
            Op::Semantics(semantics) => {
                if !semantics.actions.entries.is_empty()
                    || semantics.focusable
                    || semantics.draggable
                    || semantics.scrollable_x
                    || semantics.scrollable_y
                {
                    current_is_hit = true;
                }
            }
            _ => {}
        }
    }

    if current_is_hit {
        Some(node_id)
    } else {
        None
    }
}

fn paint_op_blocks_hit_testing(op: &Op) -> bool {
    match op {
        Op::Paint(PaintOp::DrawRect {
            fill,
            stroke,
            shadow,
            ..
        }) => fill.is_some() || stroke.is_some() || shadow.is_some(),
        Op::Paint(PaintOp::DrawText { text, .. }) => !text.is_empty(),
        Op::Paint(PaintOp::DrawRichText { runs, .. }) => {
            runs.iter().any(|run| !run.text.is_empty())
        }
        Op::Paint(PaintOp::DrawImage { .. }) => true,
        Op::Paint(PaintOp::DrawPath { fill, stroke, .. })
        | Op::Paint(PaintOp::DrawSvg { fill, stroke, .. }) => fill.is_some() || stroke.is_some(),
        _ => false,
    }
}

pub fn find_next_focus_node(
    ir: &CoreIR,
    current: Option<WidgetId>,
    reverse: bool,
) -> Option<WidgetId> {
    let nodes_in_scope = if let Some(barrier_id) = topmost_focus_barrier(ir) {
        focusable_nodes_in_scope(ir, barrier_id)
    } else if let Some(scope_id) = current.and_then(|id| find_containing_focus_scope(id, ir)) {
        if is_focus_barrier(ir, scope_id) {
            focusable_nodes_in_scope(ir, scope_id)
        } else {
            get_all_focusable_nodes(ir)
        }
    } else {
        get_all_focusable_nodes(ir)
    };

    if nodes_in_scope.is_empty() {
        return None;
    }

    let idx = if let Some(curr_id) = current {
        nodes_in_scope.iter().position(|id| *id == curr_id)
    } else {
        None
    };

    match idx {
        Some(i) => {
            if reverse {
                if i == 0 {
                    Some(nodes_in_scope[nodes_in_scope.len() - 1])
                } else {
                    Some(nodes_in_scope[i - 1])
                }
            } else if i == nodes_in_scope.len() - 1 {
                Some(nodes_in_scope[0])
            } else {
                Some(nodes_in_scope[i + 1])
            }
        }
        None => {
            if reverse {
                Some(nodes_in_scope[nodes_in_scope.len() - 1])
            } else {
                Some(nodes_in_scope[0])
            }
        }
    }
}

pub fn get_all_focusable_nodes(ir: &CoreIR) -> Vec<WidgetId> {
    let mut list = Vec::new();
    if let Some(root) = ir.root {
        collect_focusable_nodes(root, ir, &mut list, false, 0);
    }
    sort_focusable_nodes(ir, list)
}

/// Returns focus barriers in tree order. The last barrier is the topmost active
/// barrier because overlays lower after their underlying content.
pub fn focus_barriers_in_tree_order(ir: &CoreIR) -> Vec<WidgetId> {
    let mut barriers = Vec::new();
    if let Some(root) = ir.root {
        collect_focus_barriers(root, ir, &mut barriers);
    }
    barriers
}

/// Returns the topmost active focus barrier in the current semantic tree.
pub fn topmost_focus_barrier(ir: &CoreIR) -> Option<WidgetId> {
    focus_barriers_in_tree_order(ir).last().copied()
}

/// Returns enabled focusable nodes inside `scope_id` in traversal order.
pub fn focusable_nodes_in_scope(ir: &CoreIR, scope_id: WidgetId) -> Vec<WidgetId> {
    let mut list = Vec::new();
    if let Some(scope) = ir.nodes.get(&scope_id) {
        let mut order = 0;
        for child in &scope.children {
            collect_focusable_nodes(*child, ir, &mut list, false, order);
            order = list.last().map(|(_, index)| *index + 1).unwrap_or(order);
        }
    }
    sort_focusable_nodes(ir, list)
}

/// Returns the preferred entry target for a focus scope.
pub fn preferred_focus_node_in_scope(ir: &CoreIR, scope_id: WidgetId) -> Option<WidgetId> {
    let nodes = focusable_nodes_in_scope(ir, scope_id);
    nodes
        .iter()
        .copied()
        .find(|id| semantics(ir, *id).is_some_and(|value| value.autofocus))
        .or_else(|| nodes.first().copied())
}

/// Returns whether `node_id` is an enabled focus target.
pub fn is_enabled_focus_node(ir: &CoreIR, node_id: WidgetId) -> bool {
    semantics(ir, node_id).is_some_and(|value| value.focusable && !value.disabled)
}

/// Returns whether `node_id` is `ancestor_id` or belongs to its subtree.
pub fn is_descendant_or_self(ir: &CoreIR, node_id: WidgetId, ancestor_id: WidgetId) -> bool {
    let mut current = Some(node_id);
    while let Some(id) = current {
        if id == ancestor_id {
            return true;
        }
        current = ir.nodes.get(&id).and_then(|node| node.parent);
    }
    false
}

fn sort_focusable_nodes(ir: &CoreIR, mut list: Vec<(WidgetId, usize)>) -> Vec<WidgetId> {
    list.sort_by(|(id_a, order_a), (id_b, order_b)| {
        let idx_a = ir.nodes.get(id_a).and_then(|n| {
            if let Op::Semantics(s) = &n.op {
                s.focus_index
            } else {
                None
            }
        });
        let idx_b = ir.nodes.get(id_b).and_then(|n| {
            if let Op::Semantics(s) = &n.op {
                s.focus_index
            } else {
                None
            }
        });

        match (idx_a, idx_b) {
            (Some(a), Some(b)) => a.cmp(&b).then(order_a.cmp(order_b)),
            (Some(_), None) => std::cmp::Ordering::Less,
            (None, Some(_)) => std::cmp::Ordering::Greater,
            (None, None) => order_a.cmp(order_b),
        }
    });
    list.into_iter().map(|(id, _)| id).collect()
}

fn collect_focusable_nodes(
    node_id: WidgetId,
    ir: &CoreIR,
    list: &mut Vec<(WidgetId, usize)>,
    stop_at_barriers: bool,
    mut order: usize,
) {
    if let Some(node) = ir.nodes.get(&node_id) {
        let mut is_barrier = false;
        if let Op::Semantics(s) = &node.op {
            if s.focusable && !s.disabled {
                list.push((node_id, order));
                order += 1;
            }
            is_barrier = s.is_focus_barrier;
        }

        if stop_at_barriers && is_barrier {
            return;
        }

        let mut children = node.children.clone();
        // Internal sort within branches still useful for tree-order
        children.sort_by_key(|cid| {
            ir.nodes
                .get(cid)
                .and_then(|n| {
                    if let Op::Semantics(s) = &n.op {
                        s.focus_index
                    } else {
                        None
                    }
                })
                .unwrap_or(i32::MAX)
        });

        for child in children {
            collect_focusable_nodes(child, ir, list, stop_at_barriers, order);
            order = list.last().map(|(_, o)| *o + 1).unwrap_or(order);
        }
    }
}

fn collect_focus_barriers(node_id: WidgetId, ir: &CoreIR, barriers: &mut Vec<WidgetId>) {
    let Some(node) = ir.nodes.get(&node_id) else {
        return;
    };
    if matches!(&node.op, Op::Semantics(value) if value.is_focus_scope && value.is_focus_barrier) {
        barriers.push(node_id);
    }
    for child in &node.children {
        collect_focus_barriers(*child, ir, barriers);
    }
}

fn find_containing_focus_scope(node_id: WidgetId, ir: &CoreIR) -> Option<WidgetId> {
    let mut curr = Some(node_id);
    while let Some(pid) = curr {
        if let Some(node) = ir.nodes.get(&pid) {
            if let Op::Semantics(s) = &node.op {
                if s.is_focus_scope {
                    return Some(pid);
                }
            }
            curr = node.parent;
        } else {
            break;
        }
    }
    None
}

fn is_focus_barrier(ir: &CoreIR, node_id: WidgetId) -> bool {
    semantics(ir, node_id).is_some_and(|value| value.is_focus_barrier)
}

fn semantics(ir: &CoreIR, node_id: WidgetId) -> Option<&fission_ir::Semantics> {
    match &ir.nodes.get(&node_id)?.op {
        Op::Semantics(value) => Some(value),
        _ => None,
    }
}

pub fn find_neighbor_focus_node(
    ir: &CoreIR,
    layout: &LayoutSnapshot,
    current: WidgetId,
    direction: FocusDirection,
) -> Option<WidgetId> {
    let current_rect = layout.get_node_rect(current)?;
    let focusable_nodes = get_all_focusable_nodes(ir);

    let mut best_candidate = None;
    let mut best_dist = f32::INFINITY;

    let (cx, cy) = (
        current_rect.x() + current_rect.width() / 2.0,
        current_rect.y() + current_rect.height() / 2.0,
    );

    for node_id in focusable_nodes {
        if node_id == current {
            continue;
        }
        let rect = match layout.get_node_rect(node_id) {
            Some(r) => r,
            None => continue,
        };

        let (nx, ny) = (
            rect.x() + rect.width() / 2.0,
            rect.y() + rect.height() / 2.0,
        );

        let is_in_dir = match direction {
            FocusDirection::Up => ny < cy && (nx - cx).abs() < (ny - cy).abs(),
            FocusDirection::Down => ny > cy && (nx - cx).abs() < (ny - cy).abs(),
            FocusDirection::Left => nx < cx && (ny - cy).abs() < (nx - cx).abs(),
            FocusDirection::Right => nx > cx && (ny - cy).abs() < (nx - cx).abs(),
        };

        if is_in_dir {
            let dist = (nx - cx).powi(2) + (ny - cy).powi(2);
            if dist < best_dist {
                best_dist = dist;
                best_candidate = Some(node_id);
            }
        }
    }

    best_candidate
}