repose-app 0.31.6

Embeddable Repose runtime with composition, input handling, and frame output
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
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
//! Integration tests for the embeddable runtime's event handling core.
//!
//! These drive `ReposeRuntime` with hand-built frames so the behaviour does
//! not depend on the layout engine: Escape fallthrough, built-in text editing
//! shortcuts, and pointer-release click reporting.

use std::cell::RefCell;
use std::rc::Rc;

use repose_app::ReposeRuntime;
use repose_core::input::{Key, KeyEvent, KeyEventType, Modifiers, PhysicalKey, PointerButton};
use repose_core::runtime::{Frame, SemNode};
use repose_core::semantics::Role;
use repose_core::shortcuts::Action;
use repose_core::{CursorIcon, HitRegion, Rect, Scene, Vec2};

const TF_ID: u64 = 100;
const BTN_ID: u64 = 200;

fn textfield_frame(id: u64) -> Frame {
    let hr = HitRegion {
        id,
        rect: Rect {
            x: 0.0,
            y: 0.0,
            w: 200.0,
            h: 30.0,
        },
        focusable: true,
        tf_state_key: Some(id),
        tf_multiline: false,
        tf_enabled: true,
        tf_read_only: false,
        cursor: Some(CursorIcon::Text),
        ..Default::default()
    };

    let rect = hr.rect;
    let sem = SemNode {
        id,
        role: Role::TextField,
        label: Some("Field".into()),
        rect,
        focused: true,
        ..Default::default()
    };

    Frame {
        scene: Scene::default(),
        hit_regions: vec![hr],
        semantics_nodes: vec![sem],
        focus_chain: vec![id],
    }
}

fn key_down(key: Key, modifiers: Modifiers, repeat: bool) -> KeyEvent {
    KeyEvent {
        key,
        modifiers,
        is_repeat: repeat,
        event_type: KeyEventType::Down,
        utf16_code_point: 0,
        physical: None,
    }
}

#[test]
fn escape_not_consumed_when_idle() {
    let mut rt = ReposeRuntime::new();
    // No focus, no frame cache, no active drag: Escape must fall through so
    // hosts can implement back / quit.
    let ev = key_down(Key::Escape, Modifiers::default(), false);
    assert!(!rt.handle_key(&ev));

    // With a cached frame but no focus and no root key handler, Escape
    // still isn't consumed.
    rt.cache_frame(textfield_frame(TF_ID));
    rt.sched.focused = None;
    assert!(!rt.handle_key(&ev));
}

#[test]
fn release_reports_clicked_id() {
    let mut rt = ReposeRuntime::new();
    let clicked = Rc::new(RefCell::new(false));
    let clicked_cb = clicked.clone();
    let hr = HitRegion {
        id: BTN_ID,
        rect: Rect {
            x: 0.0,
            y: 0.0,
            w: 50.0,
            h: 50.0,
        },
        on_click: Some(Rc::new(move || {
            *clicked_cb.borrow_mut() = true;
        })),
        ..Default::default()
    };
    let frame = Frame {
        scene: Scene::default(),
        hit_regions: vec![hr],
        semantics_nodes: Vec::new(),
        focus_chain: Vec::new(),
    };
    rt.cache_frame(frame);

    let pos = Vec2 { x: 10.0, y: 10.0 };
    let _press = rt.handle_pointer_press(pos, PointerButton::Primary);

    let result = rt.handle_pointer_release(pos, PointerButton::Primary);
    assert!(
        result.clicked_id == Some(BTN_ID),
        "clicked_id should be reported: {result:?}"
    );
    assert!(result.needs_a11y_announce);
    assert!(result.consumed);
    assert!(*clicked.borrow(), "on_click should have fired");
    // Runtime state is cleared by the time the host reads the result.
    assert!(rt.capture_id.is_none());
}

#[test]
fn release_click_off_target_reports_nothing() {
    let mut rt = ReposeRuntime::new();
    let hr = HitRegion {
        id: BTN_ID,
        rect: Rect {
            x: 0.0,
            y: 0.0,
            w: 50.0,
            h: 50.0,
        },
        on_click: Some(Rc::new(|| {})),
        ..Default::default()
    };
    let frame = Frame {
        scene: Scene::default(),
        hit_regions: vec![hr],
        semantics_nodes: Vec::new(),
        focus_chain: Vec::new(),
    };
    rt.cache_frame(frame);

    // Press inside, release far outside: no click.
    let _press = rt.handle_pointer_press(Vec2 { x: 10.0, y: 10.0 }, PointerButton::Primary);
    let result = rt.handle_pointer_release(
        Vec2 {
            x: 1000.0,
            y: 1000.0,
        },
        PointerButton::Primary,
    );
    assert!(result.clicked_id.is_none());
    assert!(!result.needs_a11y_announce);
}

fn button_frame(
    id: u64,
    on_click: Option<Rc<dyn Fn()>>,
    on_double_click: Option<Rc<dyn Fn()>>,
    on_long_click: Option<Rc<dyn Fn()>>,
) -> Frame {
    let hr = HitRegion {
        id,
        rect: Rect {
            x: 0.0,
            y: 0.0,
            w: 100.0,
            h: 50.0,
        },
        on_click,
        on_double_click,
        on_long_click,
        ..Default::default()
    };
    Frame {
        scene: Scene::default(),
        hit_regions: vec![hr],
        semantics_nodes: Vec::new(),
        focus_chain: Vec::new(),
    }
}

#[test]
fn combined_clickable_delays_single_click_when_double_configured() {
    let mut rt = ReposeRuntime::new();
    let clicks = Rc::new(RefCell::new(0u32));
    let doubles = Rc::new(RefCell::new(0u32));
    let c = clicks.clone();
    let d = doubles.clone();
    rt.cache_frame(button_frame(
        BTN_ID,
        Some(Rc::new(move || *c.borrow_mut() += 1)),
        Some(Rc::new(move || *d.borrow_mut() += 1)),
        None,
    ));
    let pos = Vec2 { x: 10.0, y: 10.0 };
    rt.handle_pointer_press(pos, PointerButton::Primary);
    rt.handle_pointer_release(pos, PointerButton::Primary);
    assert_eq!(*clicks.borrow(), 0);
    std::thread::sleep(web_time::Duration::from_millis(350));
    rt.poll_gesture_timers();
    assert_eq!(*clicks.borrow(), 1);
    assert_eq!(*doubles.borrow(), 0);
}

#[test]
fn combined_clickable_double_tap_skips_on_click() {
    let mut rt = ReposeRuntime::new();
    let clicks = Rc::new(RefCell::new(0u32));
    let doubles = Rc::new(RefCell::new(0u32));
    let c = clicks.clone();
    let d = doubles.clone();
    rt.cache_frame(button_frame(
        BTN_ID,
        Some(Rc::new(move || *c.borrow_mut() += 1)),
        Some(Rc::new(move || *d.borrow_mut() += 1)),
        None,
    ));
    let pos = Vec2 { x: 10.0, y: 10.0 };
    rt.handle_pointer_press(pos, PointerButton::Primary);
    rt.handle_pointer_release(pos, PointerButton::Primary);
    std::thread::sleep(web_time::Duration::from_millis(50));
    rt.handle_pointer_press(pos, PointerButton::Primary);
    rt.handle_pointer_release(pos, PointerButton::Primary);
    assert_eq!(*doubles.borrow(), 1);
    assert_eq!(*clicks.borrow(), 0);
}

#[test]
fn long_press_fires_while_held_and_suppresses_click() {
    let mut rt = ReposeRuntime::new();
    let clicks = Rc::new(RefCell::new(0u32));
    let longs = Rc::new(RefCell::new(0u32));
    let c = clicks.clone();
    let l = longs.clone();
    rt.cache_frame(button_frame(
        BTN_ID,
        Some(Rc::new(move || *c.borrow_mut() += 1)),
        None,
        Some(Rc::new(move || *l.borrow_mut() += 1)),
    ));
    let pos = Vec2 { x: 10.0, y: 10.0 };
    rt.handle_pointer_press(pos, PointerButton::Primary);
    std::thread::sleep(web_time::Duration::from_millis(550));
    rt.poll_gesture_timers();
    assert_eq!(*longs.borrow(), 1);
    rt.handle_pointer_release(pos, PointerButton::Primary);
    assert_eq!(*clicks.borrow(), 0);
}

#[test]
fn pending_click_survives_press_on_another_id() {
    let mut rt = ReposeRuntime::new();
    let a_clicks = Rc::new(RefCell::new(0u32));
    let b_clicks = Rc::new(RefCell::new(0u32));
    let ac = a_clicks.clone();
    let bc = b_clicks.clone();
    let a = button_frame(
        BTN_ID,
        Some(Rc::new(move || *ac.borrow_mut() += 1)),
        Some(Rc::new(|| {})),
        None,
    );
    let mut b = button_frame(
        BTN_ID + 1,
        Some(Rc::new(move || *bc.borrow_mut() += 1)),
        None,
        None,
    );
    b.hit_regions[0].rect.x = 200.0;
    rt.cache_frame(Frame {
        scene: Scene::default(),
        hit_regions: [a.hit_regions, b.hit_regions].concat(),
        semantics_nodes: Vec::new(),
        focus_chain: Vec::new(),
    });
    let pos_a = Vec2 { x: 10.0, y: 10.0 };
    let pos_b = Vec2 { x: 210.0, y: 10.0 };
    rt.handle_pointer_press(pos_a, PointerButton::Primary);
    rt.handle_pointer_release(pos_a, PointerButton::Primary);
    std::thread::sleep(web_time::Duration::from_millis(50));
    rt.handle_pointer_press(pos_b, PointerButton::Primary);
    rt.handle_pointer_release(pos_b, PointerButton::Primary);
    assert_eq!(*b_clicks.borrow(), 1);
    assert_eq!(*a_clicks.borrow(), 0);
    std::thread::sleep(web_time::Duration::from_millis(350));
    rt.poll_gesture_timers();
    assert_eq!(*a_clicks.borrow(), 1);
}

/// A press that travels past tap slop is a drag: Compose's
/// `detectTapGestures` drops the tap, so releasing mid-element must not
/// activate it. Guards against re-introducing click-on-drag-release.
#[test]
fn drag_past_slop_does_not_fire_click() {
    for drag in [0.0f32, 4.0, 12.0] {
        let mut rt = ReposeRuntime::new();
        let clicks = Rc::new(RefCell::new(0u32));
        let c = clicks.clone();
        rt.cache_frame(button_frame(
            BTN_ID,
            Some(Rc::new(move || *c.borrow_mut() += 1)),
            None,
            None,
        ));
        let start = Vec2 { x: 10.0, y: 10.0 };
        let end = Vec2 {
            x: 10.0 + drag,
            y: 10.0,
        };
        rt.handle_pointer_press(start, PointerButton::Primary);
        if drag > 0.0 {
            rt.handle_pointer_move(end);
        }
        let result = rt.handle_pointer_release(end, PointerButton::Primary);
        rt.poll_gesture_timers();
        std::thread::sleep(web_time::Duration::from_millis(350));
        rt.poll_gesture_timers();
        assert_eq!(
            *clicks.borrow(),
            1,
            "a {drag}px move is within slop and should still click"
        );
        assert_eq!(result.clicked_id, Some(BTN_ID));
    }
}

#[test]
fn drag_past_slop_cancels_click() {
    for drag in [25.0f32, 60.0, 90.0] {
        let mut rt = ReposeRuntime::new();
        let clicks = Rc::new(RefCell::new(0u32));
        let c = clicks.clone();
        rt.cache_frame(button_frame(
            BTN_ID,
            Some(Rc::new(move || *c.borrow_mut() += 1)),
            None,
            None,
        ));
        let start = Vec2 { x: 10.0, y: 10.0 };
        // Stay inside the 100x50 hit region so only slop can cancel the tap.
        let end = Vec2 {
            x: 10.0 + drag.min(80.0),
            y: 10.0,
        };
        rt.handle_pointer_press(start, PointerButton::Primary);
        rt.handle_pointer_move(end);
        let result = rt.handle_pointer_release(end, PointerButton::Primary);
        rt.poll_gesture_timers();
        std::thread::sleep(web_time::Duration::from_millis(350));
        rt.poll_gesture_timers();
        assert_eq!(*clicks.borrow(), 0, "a {drag}px drag must not click");
        assert_eq!(result.clicked_id, None);
        assert!(!result.needs_a11y_announce);
    }
}

/// Compose requires the two taps of a double tap to land within touch slop of
/// each other; taps far apart are two independent taps.
#[test]
fn double_tap_beyond_slop_is_not_a_double_tap() {
    let mut rt = ReposeRuntime::new();
    let clicks = Rc::new(RefCell::new(0u32));
    let doubles = Rc::new(RefCell::new(0u32));
    let (c, d) = (clicks.clone(), doubles.clone());
    rt.cache_frame(button_frame(
        BTN_ID,
        Some(Rc::new(move || *c.borrow_mut() += 1)),
        Some(Rc::new(move || *d.borrow_mut() += 1)),
        None,
    ));
    let near = Vec2 { x: 10.0, y: 10.0 };
    // 80px apart, well past the 18dp tap slop, but both inside the region.
    let far = Vec2 { x: 90.0, y: 10.0 };
    rt.handle_pointer_press(near, PointerButton::Primary);
    rt.handle_pointer_release(near, PointerButton::Primary);
    std::thread::sleep(web_time::Duration::from_millis(60));
    rt.handle_pointer_press(far, PointerButton::Primary);
    rt.handle_pointer_release(far, PointerButton::Primary);
    rt.poll_gesture_timers();
    std::thread::sleep(web_time::Duration::from_millis(350));
    rt.poll_gesture_timers();
    assert_eq!(*doubles.borrow(), 0, "taps 80px apart are not a double tap");
    assert_eq!(*clicks.borrow(), 2, "each distant tap is its own click");
}

/// A drag that ends on the element must not be able to manufacture a double
/// tap, even when both halves fall inside the timing window.
#[test]
fn dragging_twice_is_not_a_double_tap() {
    let mut rt = ReposeRuntime::new();
    let clicks = Rc::new(RefCell::new(0u32));
    let doubles = Rc::new(RefCell::new(0u32));
    let (c, d) = (clicks.clone(), doubles.clone());
    rt.cache_frame(button_frame(
        BTN_ID,
        Some(Rc::new(move || *c.borrow_mut() += 1)),
        Some(Rc::new(move || *d.borrow_mut() += 1)),
        None,
    ));
    let start = Vec2 { x: 10.0, y: 10.0 };
    let moved = Vec2 { x: 90.0, y: 10.0 };
    for _ in 0..2 {
        rt.handle_pointer_press(start, PointerButton::Primary);
        rt.handle_pointer_move(moved);
        rt.handle_pointer_release(moved, PointerButton::Primary);
        std::thread::sleep(web_time::Duration::from_millis(60));
    }
    rt.poll_gesture_timers();
    std::thread::sleep(web_time::Duration::from_millis(350));
    rt.poll_gesture_timers();
    assert_eq!(
        *doubles.borrow(),
        0,
        "drags must not compose into a double tap"
    );
    assert_eq!(*clicks.borrow(), 0, "drags must not click either");
}

#[test]
fn keyboard_hold_long_press_fires_and_suppresses_click() {
    let mut rt = ReposeRuntime::new();
    let clicks = Rc::new(RefCell::new(0u32));
    let longs = Rc::new(RefCell::new(0u32));
    let c = clicks.clone();
    let l = longs.clone();
    rt.cache_frame(button_frame(
        BTN_ID,
        Some(Rc::new(move || *c.borrow_mut() += 1)),
        None,
        Some(Rc::new(move || *l.borrow_mut() += 1)),
    ));
    rt.sched.focused = Some(BTN_ID);
    let down = KeyEvent {
        key: Key::Space,
        modifiers: Modifiers::default(),
        is_repeat: false,
        event_type: KeyEventType::Down,
        utf16_code_point: 0,
        physical: Some(PhysicalKey::Space),
    };
    let up = KeyEvent { ..down.clone() };
    let mut up = up;
    up.event_type = KeyEventType::Up;
    assert!(rt.handle_key(&down));
    std::thread::sleep(web_time::Duration::from_millis(550));
    rt.poll_gesture_timers();
    assert_eq!(*longs.borrow(), 1);
    assert!(rt.handle_key(&up));
    assert_eq!(*clicks.borrow(), 0);
}

#[test]
fn stale_capture_dispatches_one_cancel_before_pruning() {
    use repose_core::input::{PointerEvent, PointerEventKind};
    let mut rt = ReposeRuntime::new();
    let cancels = Rc::new(RefCell::new(0u32));
    let observer = cancels.clone();
    let hit = HitRegion {
        id: BTN_ID,
        rect: Rect {
            x: 0.0,
            y: 0.0,
            w: 100.0,
            h: 50.0,
        },
        on_pointer_down: Some(Rc::new(|_: PointerEvent| {})),
        on_pointer_move: Some(Rc::new(|_: PointerEvent| {})),
        on_pointer_up: Some(Rc::new(|_: PointerEvent| {})),
        on_pointer_cancel: Some(Rc::new(move |event: PointerEvent| {
            assert!(matches!(event.event, PointerEventKind::Cancel));
            *observer.borrow_mut() += 1;
        })),
        ..Default::default()
    };
    rt.cache_frame(Frame {
        scene: Scene::default(),
        hit_regions: vec![hit],
        semantics_nodes: Vec::new(),
        focus_chain: Vec::new(),
    });
    let pos = Vec2 { x: 10.0, y: 10.0 };
    rt.handle_pointer_press(pos, PointerButton::Primary);
    rt.cache_frame(Frame {
        scene: Scene::default(),
        hit_regions: Vec::new(),
        semantics_nodes: Vec::new(),
        focus_chain: Vec::new(),
    });
    assert_eq!(*cancels.borrow(), 1);
    assert!(rt.hit_path.is_none() && rt.capture_id.is_none());
    rt.handle_pointer_move(pos);
    rt.handle_pointer_release(pos, PointerButton::Primary);
    assert_eq!(*cancels.borrow(), 1);
}

#[test]
fn live_capture_keeps_press_time_closures_across_frames() {
    use repose_core::input::{PointerEvent, PointerEventKind};
    let mut rt = ReposeRuntime::new();
    let first = Rc::new(RefCell::new(0u32));
    let second = Rc::new(RefCell::new(0u32));
    let make_hit = |observer: Rc<RefCell<u32>>| HitRegion {
        id: BTN_ID,
        rect: Rect {
            x: 0.0,
            y: 0.0,
            w: 100.0,
            h: 50.0,
        },
        on_pointer_up: Some(Rc::new(move |event: PointerEvent| {
            assert!(matches!(event.event, PointerEventKind::Up(_)));
            *observer.borrow_mut() += 1;
        })),
        ..Default::default()
    };
    rt.cache_frame(Frame {
        scene: Scene::default(),
        hit_regions: vec![make_hit(first.clone())],
        semantics_nodes: Vec::new(),
        focus_chain: Vec::new(),
    });
    let pos = Vec2 { x: 10.0, y: 10.0 };
    rt.handle_pointer_press(pos, PointerButton::Primary);
    rt.cache_frame(Frame {
        scene: Scene::default(),
        hit_regions: vec![make_hit(second.clone())],
        semantics_nodes: Vec::new(),
        focus_chain: Vec::new(),
    });
    rt.handle_pointer_release(pos, PointerButton::Primary);
    assert_eq!(*first.borrow(), 1);
    assert_eq!(*second.borrow(), 0);
}

#[test]
fn pointer_cancel_clears_capture_for_reentry() {
    let mut rt = ReposeRuntime::new();
    rt.cache_frame(button_frame(BTN_ID, None, None, None));
    let pos = Vec2 { x: 10.0, y: 10.0 };
    let _ = rt.handle_pointer_press(pos, PointerButton::Primary);
    assert!(rt.hit_path.is_some());
    rt.handle_pointer_cancel();
    assert!(rt.hit_path.is_none() && rt.capture_id.is_none());
}

#[test]
fn plain_clickable_is_immediate() {
    let mut rt = ReposeRuntime::new();
    let clicks = Rc::new(RefCell::new(0u32));
    let c = clicks.clone();
    let frame = button_frame(
        BTN_ID,
        Some(Rc::new(move || *c.borrow_mut() += 1)),
        None,
        None,
    );
    rt.cache_frame(frame);
    let pos = Vec2 { x: 10.0, y: 10.0 };
    let _ = rt.handle_pointer_press(pos, PointerButton::Primary);
    let result = rt.handle_pointer_release(pos, PointerButton::Primary);
    assert_eq!(*clicks.borrow(), 1, "plain click must fire on release");
    assert_eq!(result.clicked_id, Some(BTN_ID));
}

fn focused_textfield_rt() -> ReposeRuntime {
    let mut rt = ReposeRuntime::new();
    rt.sched.focused = Some(TF_ID);
    rt.cache_frame(textfield_frame(TF_ID));
    // Pre-create the persistent state so editing paths can act on it.
    let _ = rt.ensure_textfield_state(TF_ID);
    rt
}

#[test]
fn undo_redo_via_action() {
    let mut rt = focused_textfield_rt();

    rt.ensure_textfield_state(TF_ID)
        .borrow_mut()
        .insert_text_atomic("hello");

    assert!(rt.dispatch_action(Action::Undo));
    assert_eq!(rt.ensure_textfield_state(TF_ID).borrow().text, "");

    assert!(rt.dispatch_action(Action::Redo));
    assert_eq!(rt.ensure_textfield_state(TF_ID).borrow().text, "hello");
}

#[test]
fn copy_cut_paste_via_action() {
    let mut rt = focused_textfield_rt();
    let clipboard = Rc::new(RefCell::new(String::new()));

    let write = clipboard.clone();
    repose_core::clipboard::set_clipboard_fn(Box::new(move |t| {
        *write.borrow_mut() = t.to_string();
    }));

    rt.ensure_textfield_state(TF_ID)
        .borrow_mut()
        .insert_text_atomic("hello");

    // Select all + copy.
    assert!(rt.dispatch_action(Action::SelectAll));
    assert!(rt.dispatch_action(Action::Copy));
    assert_eq!(*clipboard.borrow(), "hello");

    // Cut removes the selection and copies it too.
    assert!(rt.dispatch_action(Action::Cut));
    assert_eq!(rt.ensure_textfield_state(TF_ID).borrow().text, "");
    assert_eq!(*clipboard.borrow(), "hello");

    // Paste reads back from the (mock) OS clipboard.
    let read_clipboard = clipboard.clone();
    repose_core::clipboard::set_clipboard_read_fn(Box::new(move || {
        Some(read_clipboard.borrow().clone())
    }));
    assert!(rt.dispatch_action(Action::Paste));
    assert_eq!(rt.ensure_textfield_state(TF_ID).borrow().text, "hello");
}

#[test]
fn insert_text_into_focused_filters_controls() {
    let mut rt = focused_textfield_rt();

    // Single-line: newlines and CR are stripped, control chars dropped.
    assert!(rt.insert_text_into_focused("a\nb\r\x01c"));
    assert_eq!(rt.ensure_textfield_state(TF_ID).borrow().text, "abc");

    // Multiline keeps newlines.
    let mut rt = ReposeRuntime::new();
    let mut multiline_frame = textfield_frame(TF_ID);
    multiline_frame.hit_regions[0].tf_multiline = true;
    multiline_frame.hit_regions[0].tf_content_origin = Some((0.0, 0.0));
    rt.sched.focused = Some(TF_ID);
    rt.cache_frame(multiline_frame);
    let _ = rt.ensure_textfield_state(TF_ID);

    assert!(rt.insert_text_into_focused("x\ny"));
    assert_eq!(rt.ensure_textfield_state(TF_ID).borrow().text, "x\ny");

    // Ctrl-modified insert is rejected (host should never send this, but be safe).
    rt.modifiers.ctrl = true;
    assert!(!rt.insert_text_into_focused("z"));
}

#[test]
fn insert_text_respects_ime_preedit() {
    let mut rt = focused_textfield_rt();
    rt.ime_preedit = true;
    assert!(!rt.insert_text_into_focused("ignored"));
    assert_eq!(rt.ensure_textfield_state(TF_ID).borrow().text, "");
}

#[test]
fn after_compose_lazy_inits_focused_textfield() {
    let mut rt = ReposeRuntime::new();
    rt.sched.focused = Some(TF_ID);
    let frame = textfield_frame(TF_ID);
    assert!(!rt.textfield_states.contains_key(&TF_ID));

    rt.after_compose(&frame, 1.0);
    assert!(
        rt.textfield_states.contains_key(&TF_ID),
        "after_compose should lazy-init the focused text field"
    );
}

#[test]
fn physical_keys_track_without_focus() {
    let mut rt = ReposeRuntime::new();
    rt.cache_frame(textfield_frame(TF_ID));
    rt.sched.focused = None;

    rt.set_physical_key("KeyW", true);
    assert!(rt.physical_key_held("KeyW"));
    assert_eq!(rt.held_physical_keys(), vec!["KeyW".to_string()]);

    // A stuck down survives redundant presses; a release clears it.
    rt.set_physical_key("KeyW", true);
    assert!(rt.physical_key_held("KeyW"));
    rt.set_physical_key("KeyW", false);
    assert!(!rt.physical_key_held("KeyW"));
}

#[test]
fn focus_loss_clears_polled_levels() {
    let mut rt = ReposeRuntime::new();
    rt.set_physical_key("KeyW", true);
    let pos = Vec2 { x: 10.0, y: 10.0 };
    rt.cache_frame(textfield_frame(TF_ID));
    let _ = rt.handle_pointer_press(pos, PointerButton::Primary);
    assert!(rt.mouse_button_held(PointerButton::Primary));

    rt.handle_focus_lost();
    assert!(
        rt.held_physical_keys().is_empty(),
        "alt-tab must not leave a stuck key"
    );
    assert!(!rt.mouse_button_held(PointerButton::Primary));
}

#[test]
fn mouse_buttons_track_press_release() {
    let mut rt = ReposeRuntime::new();
    rt.cache_frame(textfield_frame(TF_ID));
    let pos = Vec2 { x: 10.0, y: 10.0 };
    assert!(!rt.mouse_button_held(PointerButton::Secondary));
    let _ = rt.handle_pointer_press(pos, PointerButton::Secondary);
    assert!(rt.mouse_button_held(PointerButton::Secondary));
    let _ = rt.handle_pointer_release(pos, PointerButton::Secondary);
    assert!(!rt.mouse_button_held(PointerButton::Secondary));
}

#[test]
fn pointer_pos_tracks_mouse_only() {
    let mut rt = ReposeRuntime::new();
    assert_eq!(rt.sched.pointer_pos_px, None);
    let pos = Vec2 { x: 10.0, y: 20.0 };
    rt.cache_frame(textfield_frame(TF_ID));
    let _ = rt.handle_pointer_move(pos);
    assert_eq!(rt.sched.pointer_pos_px, Some((10.0, 20.0)));
    let _ = rt.handle_touch_move(Some(7), Vec2 { x: 99.0, y: 99.0 });
    assert_eq!(rt.sched.pointer_pos_px, Some((10.0, 20.0)));
    rt.handle_pointer_cancel();
    assert_eq!(rt.sched.pointer_pos_px, None);
    let _ = rt.handle_pointer_press(pos, PointerButton::Primary);
    assert_eq!(rt.sched.pointer_pos_px, Some((10.0, 20.0)));
    rt.handle_focus_lost();
    assert_eq!(rt.sched.pointer_pos_px, None);
}

#[test]
fn shortcut_resolution_uses_event_modifiers() {
    use std::cell::Cell;

    let mut rt = ReposeRuntime::new();
    let fired = Rc::new(Cell::new(false));
    let handler_fired = fired.clone();
    rt.shortcuts.default_map.insert(
        Key::Character('s'),
        Modifiers {
            ctrl: true,
            ..Modifiers::default()
        },
        Action::Custom("save".into()),
    );
    rt.shortcuts.handler = Some(Rc::new(move |action| {
        if matches!(action, Action::Custom(ref key) if key.as_ref() == "save") {
            handler_fired.set(true);
            true
        } else {
            false
        }
    }));
    rt.cache_frame(Frame {
        scene: Scene::default(),
        hit_regions: Vec::new(),
        semantics_nodes: Vec::new(),
        focus_chain: Vec::new(),
    });
    let event = key_down(
        Key::Character('s'),
        Modifiers {
            ctrl: true,
            ..Modifiers::default()
        },
        false,
    );
    assert!(rt.handle_key(&event));
    assert!(fired.get());
}

#[test]
fn shortcuts_work_before_the_first_frame() {
    use std::cell::Cell;

    let mut rt = ReposeRuntime::new();
    let fired = Rc::new(Cell::new(false));
    let handler_fired = fired.clone();
    rt.shortcuts.default_map.insert(
        Key::Character('s'),
        Modifiers {
            ctrl: true,
            ..Modifiers::default()
        },
        Action::Custom("save".into()),
    );
    rt.shortcuts.handler = Some(Rc::new(move |action| {
        if matches!(action, Action::Custom(ref key) if key.as_ref() == "save") {
            handler_fired.set(true);
            true
        } else {
            false
        }
    }));
    let event = key_down(
        Key::Character('s'),
        Modifiers {
            ctrl: true,
            ..Modifiers::default()
        },
        false,
    );
    assert!(rt.handle_key(&event));
    assert!(fired.get());
}

#[test]
fn runtime_shortcuts_are_per_runtime() {
    use repose_core::shortcuts::KeyChord;
    let mut a = ReposeRuntime::new();
    let mut b = ReposeRuntime::new();
    a.shortcuts.default_map.insert(
        Key::Character('k'),
        Modifiers::default(),
        Action::Custom("a".into()),
    );
    b.shortcuts.default_map.insert(
        Key::Character('k'),
        Modifiers::default(),
        Action::Custom("b".into()),
    );
    let chord = KeyChord::new(Key::Character('k'), Modifiers::default());
    assert_eq!(
        a.shortcuts.resolve_action(&chord),
        Some(Action::Custom("a".into()))
    );
    assert_eq!(
        b.shortcuts.resolve_action(&chord),
        Some(Action::Custom("b".into()))
    );
}

#[test]
fn pointer_move_cursor_follows_frame_override() {
    use repose_core::runtime::Scheduler;
    use repose_core::{RenderContext, View, ViewKind};

    fn empty_root(_: &mut Scheduler, _: &RenderContext) -> View {
        View::new(0, ViewKind::Box)
    }

    let mut rt = ReposeRuntime::new();
    rt.cache_frame(textfield_frame(TF_ID));

    let moved = rt.handle_pointer_move(Vec2 { x: 10.0, y: 10.0 });
    assert_eq!(moved.cursor, Some(CursorIcon::Text));

    rt.sched.cursor_override = Some(CursorIcon::Grab);
    let out = rt.frame(empty_root, &RenderContext::default());
    assert_eq!(out.platform.cursor, Some(CursorIcon::Grab));

    let moved = rt.handle_pointer_move(Vec2 { x: 11.0, y: 10.0 });
    assert_eq!(moved.cursor, Some(CursorIcon::Grab));

    rt.sched.cursor_override = None;
    let _ = rt.frame(empty_root, &RenderContext::default());

    let moved = rt.handle_pointer_move(Vec2 { x: 12.0, y: 10.0 });
    assert_eq!(moved.cursor, Some(CursorIcon::Text));
}

/// A single-line field paints as one unwrapped line, so Home and End must span
/// the whole value rather than the soft-wrap chunks of a multiline layout.
#[test]
fn single_line_home_and_end_span_the_whole_value() {
    let mut rt = ReposeRuntime::new();
    rt.sched.focused = Some(TF_ID);
    let mut frame = textfield_frame(TF_ID);
    frame.hit_regions[0].rect.w = 60.0;
    rt.cache_frame(frame);
    {
        let st = rt.ensure_textfield_state(TF_ID);
        let mut st = st.borrow_mut();
        st.insert_text_atomic("0123456789abcdefghijklmnopqrstuvwxyzABCDEF");
        st.set_inner_width(60.0);
        st.selection = 0..0;
    }

    let press = |rt: &mut ReposeRuntime, key: Key| {
        let _ = rt.handle_key(&key_down(key, Modifiers::default(), false));
        rt.ensure_textfield_state(TF_ID).borrow().selection.end
    };

    let end = press(&mut rt, Key::End);
    let home = press(&mut rt, Key::Home);
    assert_eq!(end, 42);
    assert_eq!(home, 0);
}