lemon 0.2.0-alpha.5

A reactive UI toolkit for Rust
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
//! Hit-testing in logical coordinates against a [`LayoutMap`].

use crate::layout::{LayoutMap, LayoutRect};
use crate::retained::{RetainedKind, RetainedNode};

/// Cursor position in logical points (pre-HiDPI layout space).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct LogicalPoint {
    pub x: f32,
    pub y: f32,
}

impl LogicalPoint {
    pub fn new(x: f32, y: f32) -> Self {
        Self { x, y }
    }
}

/// Convert physical pixel coordinates to logical points using the window scale factor.
pub fn physical_to_logical(physical_x: f64, physical_y: f64, scale_factor: f32) -> LogicalPoint {
    let scale = f64::from(scale_factor);
    LogicalPoint::new((physical_x / scale) as f32, (physical_y / scale) as f32)
}

fn point_in_rect(point: LogicalPoint, rect: &LayoutRect) -> bool {
    point.x >= rect.x
        && point.x < rect.x + rect.width
        && point.y >= rect.y
        && point.y < rect.y + rect.height
}

/// Normalize `point` into the `[0.0, 1.0]` coordinate space of `rect`.
///
/// Values outside the rect are clamped so handlers always receive a value in `[0.0, 1.0]`.
pub fn normalize_coords(point: LogicalPoint, rect: &LayoutRect) -> (f32, f32) {
    let nx = if rect.width > 0.0 {
        ((point.x - rect.x) / rect.width).clamp(0.0, 1.0)
    } else {
        0.0
    };
    let ny = if rect.height > 0.0 {
        ((point.y - rect.y) / rect.height).clamp(0.0, 1.0)
    } else {
        0.0
    };
    (nx, ny)
}

/// Walk the retained tree in post-order and return the top-most node under `point` that has
/// an [`on_pointer_down`](crate::retained::EventHandlers::on_pointer_down) handler,
/// together with the hit coordinates normalized to `[0.0, 1.0]` within the node's bounds.
pub fn hit_test_pointer_down<'a>(
    node: &'a RetainedNode,
    layout: &LayoutMap,
    point: LogicalPoint,
) -> Option<(&'a RetainedNode, (f32, f32))> {
    if matches!(node.kind, RetainedKind::Component { .. }) {
        let mut hit = None;
        for child in &node.children {
            hit = hit_test_pointer_down(child, layout, point).or(hit);
        }
        return hit;
    }

    let mut hit = None;
    for child in &node.children {
        hit = hit_test_pointer_down(child, layout, point).or(hit);
    }

    if node.handlers.on_pointer_down.is_some() {
        if let Some(id) = node.taffy_id {
            if let Some(rect) = layout.get(id) {
                if point_in_rect(point, rect) {
                    hit = Some((node, normalize_coords(point, rect)));
                }
            }
        }
    }

    hit
}

/// Walk the entire retained tree and call [`on_click_outside`](crate::retained::EventHandlers::on_click_outside)
/// on every node whose handler is set but whose layout bounds do **not** contain `point`.
///
/// Used by the platform layer to close popovers or dropdowns when the user clicks elsewhere.
pub fn dispatch_outside_clicks(node: &RetainedNode, layout: &LayoutMap, point: LogicalPoint) {
    if matches!(node.kind, RetainedKind::Component { .. }) {
        for child in &node.children {
            dispatch_outside_clicks(child, layout, point);
        }
        return;
    }

    if let Some(handler) = node.handlers.on_click_outside.as_ref() {
        let is_outside = node
            .taffy_id
            .and_then(|id| layout.get(id))
            .is_none_or(|rect| !point_in_rect(point, rect));
        if is_outside {
            handler();
        }
    }

    for child in &node.children {
        dispatch_outside_clicks(child, layout, point);
    }
}

/// Walk the retained tree in post-order (children before parents) and return the top-most
/// node under `point` that has an `on_click` handler.
pub fn hit_test_on_click<'a>(
    node: &'a RetainedNode,
    layout: &LayoutMap,
    point: LogicalPoint,
) -> Option<&'a RetainedNode> {
    if matches!(node.kind, RetainedKind::Component { .. }) {
        let mut hit = None;
        for child in &node.children {
            hit = hit_test_on_click(child, layout, point).or(hit);
        }
        return hit;
    }

    let mut hit = None;
    for child in &node.children {
        hit = hit_test_on_click(child, layout, point).or(hit);
    }

    if node.handlers.on_click.is_some() {
        if let Some(id) = node.taffy_id {
            if let Some(rect) = layout.get(id) {
                if point_in_rect(point, rect) {
                    hit = Some(node);
                }
            }
        }
    }

    hit
}

pub fn hit_test_hover<'a>(
    node: &'a RetainedNode,
    layout: &LayoutMap,
    point: LogicalPoint,
) -> Option<&'a RetainedNode> {
    if matches!(node.kind, RetainedKind::Component { .. }) {
        let mut hit = None;
        for child in &node.children {
            hit = hit_test_hover(child, layout, point).or(hit);
        }
        return hit;
    }

    let mut hit = None;
    for child in &node.children {
        hit = hit_test_hover(child, layout, point).or(hit);
    }

    let is_hoverable = node.handlers.on_hover_enter.is_some()
        || node.handlers.on_hover_leave.is_some()
        || node.style.cursor != crate::element::events::Cursor::Default;

    if is_hoverable {
        if let Some(id) = node.taffy_id {
            if let Some(rect) = layout.get(id) {
                if point_in_rect(point, rect) {
                    hit = Some(node);
                }
            }
        }
    }

    hit
}

/// Walk the retained tree in post-order and return the top-most focusable node under `point`.
pub fn hit_test_focusable<'a>(
    node: &'a RetainedNode,
    layout: &LayoutMap,
    point: LogicalPoint,
) -> Option<&'a RetainedNode> {
    if matches!(node.kind, RetainedKind::Component { .. }) {
        let mut hit = None;
        for child in &node.children {
            hit = hit_test_focusable(child, layout, point).or(hit);
        }
        return hit;
    }

    let mut hit = None;
    for child in &node.children {
        hit = hit_test_focusable(child, layout, point).or(hit);
    }

    if node.style.focusable {
        if let Some(id) = node.taffy_id {
            if let Some(rect) = layout.get(id) {
                if point_in_rect(point, rect) {
                    hit = Some(node);
                }
            }
        }
    }

    hit
}

pub fn find_node_by_taffy_id(node: &RetainedNode, id: taffy::NodeId) -> Option<&RetainedNode> {
    if node.taffy_id == Some(id) {
        return Some(node);
    }

    for child in &node.children {
        if let Some(found) = find_node_by_taffy_id(child, id) {
            return Some(found);
        }
    }

    None
}

/// Invoke `on_click` on `node` if present. Returns whether a handler ran.
pub fn dispatch_click(node: &RetainedNode) -> bool {
    if let Some(handler) = node.handlers.on_click.as_ref() {
        handler();
        true
    } else {
        false
    }
}

/// Returns the deepest node under `point` that has an [`on_scroll`](crate::element::builders::Column::on_scroll) handler.
///
/// Used by the platform layer to route `MouseWheel` events before paint.
pub fn hit_test_scroll<'a>(
    node: &'a RetainedNode,
    layout: &LayoutMap,
    point: LogicalPoint,
) -> Option<&'a RetainedNode> {
    if matches!(node.kind, RetainedKind::Component { .. }) {
        let mut hit = None;
        for child in &node.children {
            hit = hit_test_scroll(child, layout, point).or(hit);
        }
        return hit;
    }

    let mut hit = None;
    for child in &node.children {
        hit = hit_test_scroll(child, layout, point).or(hit);
    }

    if node.handlers.on_scroll.is_some() {
        if let Some(id) = node.taffy_id {
            if let Some(rect) = layout.get(id) {
                if point_in_rect(point, rect) {
                    hit = Some(node);
                }
            }
        }
    }

    hit
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::element::builders::{Button, Column, Text, View};
    use crate::layout::{layout_pass, Viewport};
    use crate::retained::RetainedTree;
    use std::cell::Cell;
    use std::rc::Rc;

    #[test]
    fn physical_to_logical_divides_by_scale_factor() {
        let p = physical_to_logical(200.0, 100.0, 2.0);
        assert_eq!(p, LogicalPoint::new(100.0, 50.0));
    }

    #[test]
    fn hit_test_returns_deepest_clickable_node() {
        let clicked = Rc::new(Cell::new(false));
        let flag = clicked.clone();
        let mut tree = RetainedTree::mount(
            Column::new()
                .width(200.0)
                .height(200.0)
                .child(
                    Button::new("Click")
                        .width(80.0)
                        .height(40.0)
                        .on_click(move || flag.set(true)),
                )
                .into_element(),
        )
        .unwrap();
        let layout = layout_pass(
            &mut tree,
            Viewport {
                width: 200.0,
                height: 200.0,
            },
        )
        .unwrap();

        let root = tree.root.as_ref().unwrap();
        let button = &root.children[0];
        let rect = layout.get(button.taffy_id.unwrap()).unwrap();
        let hit = hit_test_on_click(root, &layout, LogicalPoint::new(rect.x + 4.0, rect.y + 4.0));

        assert!(hit.is_some());
        assert!(dispatch_click(hit.unwrap()));
        assert!(clicked.get());
    }

    #[test]
    fn hit_test_skips_non_clickable_sibling() {
        let button_clicked = Rc::new(Cell::new(false));
        let flag = button_clicked.clone();
        let mut tree = RetainedTree::mount(
            Column::new()
                .width(200.0)
                .height(120.0)
                .child(Text::new("label").font_size(16.0))
                .child(
                    Button::new("OK")
                        .width(60.0)
                        .height(30.0)
                        .on_click(move || flag.set(true)),
                )
                .into_element(),
        )
        .unwrap();
        let layout = layout_pass(
            &mut tree,
            Viewport {
                width: 200.0,
                height: 120.0,
            },
        )
        .unwrap();

        let root = tree.root.as_ref().unwrap();
        let text_rect = layout.get(root.children[0].taffy_id.unwrap()).unwrap();
        let miss = hit_test_on_click(
            root,
            &layout,
            LogicalPoint::new(text_rect.x + 2.0, text_rect.y + 2.0),
        );
        assert!(miss.is_none());

        let button_rect = layout.get(root.children[1].taffy_id.unwrap()).unwrap();
        let hit = hit_test_on_click(
            root,
            &layout,
            LogicalPoint::new(button_rect.x + 2.0, button_rect.y + 2.0),
        );
        assert!(hit.is_some());
        dispatch_click(hit.unwrap());
        assert!(button_clicked.get());
    }

    #[test]
    fn hover_hit_test_finds_node_with_hover_enter_handler() {
        let entered = Rc::new(Cell::new(false));
        let e = entered.clone();

        let mut tree = RetainedTree::mount(
            Column::new()
                .width(200.0)
                .height(200.0)
                .child(
                    View::new()
                        .width(80.0)
                        .height(40.0)
                        .on_hover_enter(move || e.set(true)),
                )
                .into_element(),
        )
        .unwrap();
        let layout = layout_pass(
            &mut tree,
            Viewport {
                width: 200.0,
                height: 200.0,
            },
        )
        .unwrap();

        let root = tree.root.as_ref().unwrap();
        let child = &root.children[0];
        let rect = layout.get(child.taffy_id.unwrap()).unwrap();

        let hit = hit_test_hover(root, &layout, LogicalPoint::new(rect.x + 4.0, rect.y + 4.0));
        assert!(hit.is_some());

        let miss = hit_test_hover(
            root,
            &layout,
            LogicalPoint::new(rect.x + rect.width + 10.0, rect.y),
        );
        assert!(miss.is_none());
    }

    #[test]
    fn find_node_by_taffy_id_returns_correct_node() {
        let mut tree = RetainedTree::mount(
            Column::new()
                .child(Text::new("a"))
                .child(Text::new("b"))
                .into_element(),
        )
        .unwrap();
        let layout = layout_pass(
            &mut tree,
            Viewport {
                width: 200.0,
                height: 200.0,
            },
        )
        .unwrap();
        let _ = layout;

        let root = tree.root.as_ref().unwrap();
        let child_id = root.children[1].taffy_id.unwrap();
        let found = find_node_by_taffy_id(root, child_id);
        assert!(found.is_some());
        assert_eq!(found.unwrap().text_content(), Some("b"));
    }

    #[test]
    fn hit_test_scroll_finds_node_with_on_scroll() {
        use std::cell::Cell;
        let scrolled = Rc::new(Cell::new(false));
        let s = scrolled.clone();

        let mut tree = RetainedTree::mount(
            View::new()
                .width(200.0)
                .height(150.0)
                .on_scroll(move |_| s.set(true))
                .into_element(),
        )
        .unwrap();
        let layout = layout_pass(
            &mut tree,
            Viewport {
                width: 400.0,
                height: 400.0,
            },
        )
        .unwrap();

        let root = tree.root.as_ref().unwrap();
        let hit = hit_test_scroll(root, &layout, LogicalPoint::new(50.0, 50.0));
        assert!(hit.is_some());
        if let Some(node) = hit {
            node.handlers.on_scroll.as_ref().unwrap()(10.0);
        }
        assert!(scrolled.get());

        let miss = hit_test_scroll(root, &layout, LogicalPoint::new(300.0, 300.0));
        assert!(miss.is_none());
    }

    #[test]
    fn hit_test_focusable_finds_node_with_focusable_flag() {
        let mut tree = RetainedTree::mount(
            Column::new()
                .width(200.0)
                .height(200.0)
                .child(View::new().width(80.0).height(40.0).focusable())
                .child(View::new().width(80.0).height(40.0))
                .into_element(),
        )
        .unwrap();
        let layout = layout_pass(
            &mut tree,
            Viewport {
                width: 200.0,
                height: 200.0,
            },
        )
        .unwrap();

        let root = tree.root.as_ref().unwrap();
        let focusable_rect = layout.get(root.children[0].taffy_id.unwrap()).unwrap();

        let hit = hit_test_focusable(
            root,
            &layout,
            LogicalPoint::new(focusable_rect.x + 4.0, focusable_rect.y + 4.0),
        );
        assert!(hit.is_some());
        assert_eq!(hit.unwrap().taffy_id, root.children[0].taffy_id);

        let miss = hit_test_focusable(
            root,
            &layout,
            LogicalPoint::new(focusable_rect.x + 4.0, focusable_rect.y + 60.0),
        );
        assert!(miss.is_none());
    }

    #[test]
    fn hit_test_pointer_down_returns_node_with_normalized_coords() {
        let pressed = Rc::new(Cell::new((0.0_f32, 0.0_f32)));
        let flag = pressed.clone();
        let mut tree = RetainedTree::mount(
            Column::new()
                .width(200.0)
                .height(200.0)
                .child(
                    View::new()
                        .width(100.0)
                        .height(50.0)
                        .on_pointer_down(move |x, y| flag.set((x, y))),
                )
                .into_element(),
        )
        .unwrap();
        let layout = layout_pass(
            &mut tree,
            Viewport {
                width: 200.0,
                height: 200.0,
            },
        )
        .unwrap();

        let root = tree.root.as_ref().unwrap();
        let rect = layout.get(root.children[0].taffy_id.unwrap()).unwrap();

        // Hit at the center of the node.
        let cx = rect.x + rect.width * 0.5;
        let cy = rect.y + rect.height * 0.5;
        let hit = hit_test_pointer_down(root, &layout, LogicalPoint::new(cx, cy));
        assert!(hit.is_some());
        let (node, (nx, ny)) = hit.unwrap();
        node.handlers.on_pointer_down.as_ref().unwrap()(nx, ny);
        let (rx, ry) = pressed.get();
        assert!((rx - 0.5).abs() < 1e-4);
        assert!((ry - 0.5).abs() < 1e-4);

        // Miss outside the node.
        let miss = hit_test_pointer_down(
            root,
            &layout,
            LogicalPoint::new(rect.x + rect.width + 10.0, rect.y),
        );
        assert!(miss.is_none());
    }

    #[test]
    fn dispatch_outside_clicks_fires_for_nodes_outside_point() {
        let outside_fired = Rc::new(Cell::new(false));
        let flag = outside_fired.clone();

        let mut tree = RetainedTree::mount(
            Column::new()
                .width(200.0)
                .height(200.0)
                .child(
                    View::new()
                        .width(80.0)
                        .height(40.0)
                        .on_click_outside(move || flag.set(true)),
                )
                .into_element(),
        )
        .unwrap();
        let layout = layout_pass(
            &mut tree,
            Viewport {
                width: 200.0,
                height: 200.0,
            },
        )
        .unwrap();

        let root = tree.root.as_ref().unwrap();
        let rect = layout.get(root.children[0].taffy_id.unwrap()).unwrap();

        // Click well outside the node → handler must fire.
        dispatch_outside_clicks(
            root,
            &layout,
            LogicalPoint::new(rect.x + rect.width + 20.0, rect.y),
        );
        assert!(outside_fired.get());
    }

    #[test]
    fn dispatch_outside_clicks_skips_node_containing_point() {
        let outside_fired = Rc::new(Cell::new(false));
        let flag = outside_fired.clone();

        let mut tree = RetainedTree::mount(
            Column::new()
                .width(200.0)
                .height(200.0)
                .child(
                    View::new()
                        .width(80.0)
                        .height(40.0)
                        .on_click_outside(move || flag.set(true)),
                )
                .into_element(),
        )
        .unwrap();
        let layout = layout_pass(
            &mut tree,
            Viewport {
                width: 200.0,
                height: 200.0,
            },
        )
        .unwrap();

        let root = tree.root.as_ref().unwrap();
        let rect = layout.get(root.children[0].taffy_id.unwrap()).unwrap();

        // Click inside the node → handler must NOT fire.
        dispatch_outside_clicks(root, &layout, LogicalPoint::new(rect.x + 4.0, rect.y + 4.0));
        assert!(!outside_fired.get());
    }

    #[test]
    fn normalize_coords_produces_clamped_fractions() {
        use crate::layout::LayoutRect;
        let rect = LayoutRect {
            x: 10.0,
            y: 20.0,
            width: 100.0,
            height: 50.0,
        };

        // Center of the rect → (0.5, 0.5)
        let (nx, ny) = normalize_coords(LogicalPoint::new(60.0, 45.0), &rect);
        assert!((nx - 0.5).abs() < 1e-4);
        assert!((ny - 0.5).abs() < 1e-4);

        // Outside the rect → clamped to 1.0
        let (nx, ny) = normalize_coords(LogicalPoint::new(200.0, 200.0), &rect);
        assert_eq!(nx, 1.0);
        assert_eq!(ny, 1.0);

        // Before the rect → clamped to 0.0
        let (nx, ny) = normalize_coords(LogicalPoint::new(0.0, 0.0), &rect);
        assert_eq!(nx, 0.0);
        assert_eq!(ny, 0.0);
    }
}