textual 1.0.0-dev

A reactive TUI framework inspired by the Python Textual library
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
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
//! P1G-13 gate: integration tests for tree-mode focus and hover lifecycle.
//!
//! All tests exercise the arena-tree pipeline:
//! - `build_widget_tree_from_root` — build the tree
//! - `dispatch_event_tree` / `dispatch_event_to_target_tree` — dispatch events
//! - `focused_node_id_tree` — verify focus state

use std::sync::{Arc, Mutex};

use rich_rs::{Console, ConsoleOptions, Segments};
use textual::compose;
use textual::event::{BlurEvent, FocusEvent};
use textual::prelude::*;

// ---------------------------------------------------------------------------
// Test probe: focus lifecycle tracking
// ---------------------------------------------------------------------------

/// Lightweight focusable widget that records focus/blur transitions to a
/// shared sink.  Handles `Event::Focus` and `Event::Blur` so that
/// `dispatch_event_to_target_tree` can drive focus changes through the tree.
struct TreeFocusProbe {
    id: &'static str,
    focused: bool,
    sink: Arc<Mutex<Vec<String>>>,
}

impl TreeFocusProbe {
    fn new(id: &'static str, sink: Arc<Mutex<Vec<String>>>) -> Self {
        Self {
            id,
            focused: false,
            sink,
        }
    }
}

impl Widget for TreeFocusProbe {
    fn render(&self, _console: &Console, _options: &ConsoleOptions) -> Segments {
        Segments::new()
    }

    fn layout_height(&self) -> Option<usize> {
        Some(1)
    }

    fn focusable(&self) -> bool {
        true
    }

    fn has_focus(&self) -> bool {
        self.focused
    }

    fn set_focus(&mut self, focused: bool) {
        if self.focused != focused {
            self.focused = focused;
            self.sink
                .lock()
                .unwrap_or_else(|e| e.into_inner())
                .push(format!("{}:{focused}", self.id));
        }
    }

    fn on_event(&mut self, event: &Event, ctx: &mut EventCtx) {
        match event {
            Event::Focus(_) => {
                self.set_focus(true);
                ctx.request_repaint();
                ctx.set_handled();
            }
            Event::Blur(_) => {
                self.set_focus(false);
                ctx.request_repaint();
                ctx.set_handled();
            }
            _ => {}
        }
    }
}

// ---------------------------------------------------------------------------
// Test probe: hover lifecycle tracking
// ---------------------------------------------------------------------------

/// Lightweight hoverable widget that records hover enter/leave to a shared
/// sink.  Handles `Event::Enter` and `Event::Leave`.
struct TreeHoverProbe {
    id: &'static str,
    hovered: bool,
    sink: Arc<Mutex<Vec<String>>>,
}

impl TreeHoverProbe {
    fn new(id: &'static str, sink: Arc<Mutex<Vec<String>>>) -> Self {
        Self {
            id,
            hovered: false,
            sink,
        }
    }
}

impl Widget for TreeHoverProbe {
    fn render(&self, _console: &Console, _options: &ConsoleOptions) -> Segments {
        Segments::new()
    }

    fn layout_height(&self) -> Option<usize> {
        Some(1)
    }

    fn focusable(&self) -> bool {
        true
    }

    fn mouse_interactive(&self) -> bool {
        true
    }

    fn is_hovered(&self) -> bool {
        self.hovered
    }

    fn set_hovered(&mut self, hovered: bool) {
        if self.hovered != hovered {
            self.hovered = hovered;
            self.sink
                .lock()
                .unwrap_or_else(|e| e.into_inner())
                .push(format!("{}:{hovered}", self.id));
        }
    }

    fn on_event(&mut self, event: &Event, ctx: &mut EventCtx) {
        match event {
            Event::Enter(_) => {
                self.set_hovered(true);
                ctx.request_repaint();
                ctx.set_handled();
            }
            Event::Leave(_) => {
                self.set_hovered(false);
                ctx.request_repaint();
                ctx.set_handled();
            }
            _ => {}
        }
    }
}

// ===========================================================================
// P1G-13(a): Focus dispatch crosses wrapper boundaries in the arena tree.
//
// NOTE: Runtime-level Tab cycling (FocusNext/FocusPrev) is handled by
// `App::move_focus_auto`, which is pub(crate).  These tests validate the
// prerequisite: Focus/Blur events dispatched through the tree reach widgets
// across nested wrapper boundaries (Container, Vertical, VerticalScroll).
// ===========================================================================

#[test]
fn p1g13_focus_crosses_wrapper_boundary_via_tree_dispatch() {
    // Tree: Container -> Vertical -> [ProbeA, VerticalScroll -> [ProbeB, ProbeC]]
    let sink = Arc::new(Mutex::new(Vec::new()));
    let mut root = Container::new().with_child(
        Vertical::new()
            .with_child(TreeFocusProbe::new("A", sink.clone()))
            .with_child(
                VerticalScroll::new()
                    .with_child(TreeFocusProbe::new("B", sink.clone()))
                    .with_child(TreeFocusProbe::new("C", sink.clone()))
                    .height(5),
            ),
    );

    let mut tree = build_widget_tree_from_root(&mut root).expect("tree should have children");
    run_layout_pass(&mut tree, (40, 12));

    let root_id = tree.root().unwrap();
    let all_nodes = tree.walk_depth_first(root_id);

    // Collect focusable leaf nodes (our probes) in depth-first order.
    let focusable: Vec<NodeId> = all_nodes
        .iter()
        .copied()
        .filter(|&id| {
            tree.get(id)
                .map(|_| tree.children(id).is_empty()) // leaf nodes
                .unwrap_or(false)
        })
        .collect();

    // We expect at least 3 focusable leaves (A, B, C).
    assert!(
        focusable.len() >= 3,
        "expected at least 3 focusable leaves; got {} in {focusable:?}",
        focusable.len()
    );

    let probe_a = focusable[0];
    let probe_b = focusable[1];
    let probe_c = focusable[2];

    // Focus probe A via tree dispatch.
    let outcome_a = dispatch_event_to_target_tree(
        &mut tree,
        probe_a,
        &Event::Focus(FocusEvent { node: probe_a }),
    );
    assert!(
        outcome_a.handled,
        "Focus event on probe A should be handled"
    );
    assert_eq!(
        focused_node_id_tree(&tree),
        Some(probe_a),
        "focused_node_id_tree should return probe A"
    );

    // Transfer focus to probe B (across VerticalScroll boundary).
    dispatch_event_to_target_tree(
        &mut tree,
        probe_a,
        &Event::Blur(BlurEvent { node: probe_a }),
    );
    let outcome_b = dispatch_event_to_target_tree(
        &mut tree,
        probe_b,
        &Event::Focus(FocusEvent { node: probe_b }),
    );
    assert!(
        outcome_b.handled,
        "Focus event on probe B should be handled"
    );
    assert_eq!(
        focused_node_id_tree(&tree),
        Some(probe_b),
        "focus should cross the VerticalScroll wrapper boundary to probe B"
    );

    // Transfer focus to probe C (same wrapper, next sibling).
    dispatch_event_to_target_tree(
        &mut tree,
        probe_b,
        &Event::Blur(BlurEvent { node: probe_b }),
    );
    let outcome_c = dispatch_event_to_target_tree(
        &mut tree,
        probe_c,
        &Event::Focus(FocusEvent { node: probe_c }),
    );
    assert!(
        outcome_c.handled,
        "Focus event on probe C should be handled"
    );
    assert_eq!(
        focused_node_id_tree(&tree),
        Some(probe_c),
        "focus should move to probe C"
    );

    // Verify sink recorded the full traversal.
    let events = sink.lock().unwrap_or_else(|e| e.into_inner()).clone();
    assert!(
        events.contains(&"A:true".to_string()),
        "probe A should have received focus; events={events:?}"
    );
    assert!(
        events.contains(&"A:false".to_string()),
        "probe A should have lost focus; events={events:?}"
    );
    assert!(
        events.contains(&"B:true".to_string()),
        "probe B should have received focus across wrapper boundary; events={events:?}"
    );
    assert!(
        events.contains(&"C:true".to_string()),
        "probe C should have received focus; events={events:?}"
    );
}

#[test]
fn p1g13_focus_traverses_deep_wrapper_chain() {
    // Tree: Container -> VerticalScroll -> Container -> [ProbeA, ProbeB]
    // Tests focus traversal through a deep wrapper chain.
    let sink = Arc::new(Mutex::new(Vec::new()));
    let mut root = Container::new().with_child(
        VerticalScroll::new()
            .with_child(
                Container::new()
                    .with_child(TreeFocusProbe::new("deep_A", sink.clone()))
                    .with_child(TreeFocusProbe::new("deep_B", sink.clone())),
            )
            .height(8),
    );

    let mut tree = build_widget_tree_from_root(&mut root).expect("tree should have children");
    run_layout_pass(&mut tree, (40, 12));

    let root_id = tree.root().unwrap();
    let all_nodes = tree.walk_depth_first(root_id);

    // Find leaf nodes (probes).
    let leaves: Vec<NodeId> = all_nodes
        .iter()
        .copied()
        .filter(|&id| tree.children(id).is_empty())
        .collect();

    assert!(
        leaves.len() >= 2,
        "expected at least 2 leaves in deep chain; got {} in {leaves:?}",
        leaves.len()
    );

    let deep_a = leaves[0];
    let deep_b = leaves[1];

    // Focus deep_A.
    dispatch_event_to_target_tree(
        &mut tree,
        deep_a,
        &Event::Focus(FocusEvent { node: deep_a }),
    );
    assert_eq!(focused_node_id_tree(&tree), Some(deep_a));

    // Transfer to deep_B through wrapper chain.
    dispatch_event_to_target_tree(&mut tree, deep_a, &Event::Blur(BlurEvent { node: deep_a }));
    dispatch_event_to_target_tree(
        &mut tree,
        deep_b,
        &Event::Focus(FocusEvent { node: deep_b }),
    );
    assert_eq!(
        focused_node_id_tree(&tree),
        Some(deep_b),
        "focus should traverse deep wrapper chain to deep_B"
    );

    let events = sink.lock().unwrap_or_else(|e| e.into_inner()).clone();
    assert!(
        events.contains(&"deep_A:true".to_string()),
        "deep_A should gain focus; events={events:?}"
    );
    assert!(
        events.contains(&"deep_A:false".to_string()),
        "deep_A should lose focus; events={events:?}"
    );
    assert!(
        events.contains(&"deep_B:true".to_string()),
        "deep_B should gain focus across wrappers; events={events:?}"
    );
}

// ===========================================================================
// P1G-13(b): Pointer hover enter/leave updates pseudo-class state and repaint
// ===========================================================================

#[test]
fn p1g13_hover_enter_requests_repaint_via_tree_dispatch() {
    let sink = Arc::new(Mutex::new(Vec::new()));
    let mut root = Container::new()
        .with_child(TreeHoverProbe::new("btn1", sink.clone()))
        .with_child(TreeHoverProbe::new("btn2", sink.clone()));

    let mut tree = build_widget_tree_from_root(&mut root).expect("tree should have children");
    run_layout_pass(&mut tree, (40, 10));

    let root_id = tree.root().unwrap();
    let children: Vec<NodeId> = tree.children(root_id).to_vec();
    assert!(
        children.len() >= 2,
        "expected at least 2 children under root"
    );

    let btn1 = children[0];
    let _btn2 = children[1];

    // Hover enter on btn1.
    let enter_outcome = dispatch_event_to_target_tree(
        &mut tree,
        btn1,
        &Event::Enter(MouseEnterEvent {
            screen_x: 5,
            screen_y: 0,
            x: 5,
            y: 0,
        }),
    );
    assert!(
        enter_outcome.repaint_requested,
        "hover enter should request repaint"
    );

    let events = sink.lock().unwrap_or_else(|e| e.into_inner()).clone();
    assert!(
        events.contains(&"btn1:true".to_string()),
        "btn1 should be marked hovered after Enter; events={events:?}"
    );
}

#[test]
fn p1g13_hover_leave_clears_state_via_tree_dispatch() {
    let sink = Arc::new(Mutex::new(Vec::new()));
    let mut root = Container::new()
        .with_child(TreeHoverProbe::new("h1", sink.clone()))
        .with_child(TreeHoverProbe::new("h2", sink.clone()));

    let mut tree = build_widget_tree_from_root(&mut root).expect("tree should have children");
    run_layout_pass(&mut tree, (40, 10));

    let root_id = tree.root().unwrap();
    let children: Vec<NodeId> = tree.children(root_id).to_vec();
    let h1 = children[0];

    // Enter then leave.
    dispatch_event_to_target_tree(
        &mut tree,
        h1,
        &Event::Enter(MouseEnterEvent {
            screen_x: 5,
            screen_y: 0,
            x: 5,
            y: 0,
        }),
    );
    let leave_outcome = dispatch_event_to_target_tree(
        &mut tree,
        h1,
        &Event::Leave(MouseLeaveEvent {
            screen_x: 5,
            screen_y: 0,
            x: 5,
            y: 0,
        }),
    );
    assert!(
        leave_outcome.repaint_requested,
        "hover leave should request repaint"
    );

    let events = sink.lock().unwrap_or_else(|e| e.into_inner()).clone();
    assert!(
        events.contains(&"h1:true".to_string()),
        "h1 should have been hovered; events={events:?}"
    );
    assert!(
        events.contains(&"h1:false".to_string()),
        "h1 hover should be cleared after Leave; events={events:?}"
    );
}

#[test]
fn p1g13_hover_transfer_between_siblings_via_tree_dispatch() {
    let sink = Arc::new(Mutex::new(Vec::new()));
    let mut root = Container::new()
        .with_child(TreeHoverProbe::new("top", sink.clone()))
        .with_child(TreeHoverProbe::new("bottom", sink.clone()));

    let mut tree = build_widget_tree_from_root(&mut root).expect("tree should have children");
    run_layout_pass(&mut tree, (40, 10));

    let root_id = tree.root().unwrap();
    let children: Vec<NodeId> = tree.children(root_id).to_vec();
    let top = children[0];
    let bottom = children[1];

    // Hover top.
    dispatch_event_to_target_tree(
        &mut tree,
        top,
        &Event::Enter(MouseEnterEvent {
            screen_x: 5,
            screen_y: 0,
            x: 5,
            y: 0,
        }),
    );

    // Move hover: leave top, enter bottom.
    dispatch_event_to_target_tree(
        &mut tree,
        top,
        &Event::Leave(MouseLeaveEvent {
            screen_x: 5,
            screen_y: 0,
            x: 5,
            y: 0,
        }),
    );
    dispatch_event_to_target_tree(
        &mut tree,
        bottom,
        &Event::Enter(MouseEnterEvent {
            screen_x: 5,
            screen_y: 1,
            x: 5,
            y: 1,
        }),
    );

    let events = sink.lock().unwrap_or_else(|e| e.into_inner()).clone();
    assert!(
        events.contains(&"top:true".to_string()),
        "top should have been hovered; events={events:?}"
    );
    assert!(
        events.contains(&"top:false".to_string()),
        "top hover should be cleared; events={events:?}"
    );
    assert!(
        events.contains(&"bottom:true".to_string()),
        "bottom should become hovered; events={events:?}"
    );
}

// ===========================================================================
// P1G-13(c): Focus transfer clears previous focused widget
// ===========================================================================

#[test]
fn p1g13_focus_transfer_clears_previous_in_separate_branches() {
    // Tree: Container -> [Vertical -> ProbeLeft, Vertical -> ProbeRight]
    let sink = Arc::new(Mutex::new(Vec::new()));
    let mut root = Container::new()
        .with_child(Vertical::new().with_child(TreeFocusProbe::new("left", sink.clone())))
        .with_child(Vertical::new().with_child(TreeFocusProbe::new("right", sink.clone())));

    let mut tree = build_widget_tree_from_root(&mut root).expect("tree should have children");
    run_layout_pass(&mut tree, (40, 10));

    let root_id = tree.root().unwrap();
    let all_nodes = tree.walk_depth_first(root_id);

    // Find leaf focusable probes.
    let leaves: Vec<NodeId> = all_nodes
        .iter()
        .copied()
        .filter(|&id| tree.children(id).is_empty())
        .collect();
    assert!(
        leaves.len() >= 2,
        "expected at least 2 leaves; got {leaves:?}"
    );

    let left = leaves[0];
    let right = leaves[1];

    // Focus left probe.
    dispatch_event_to_target_tree(&mut tree, left, &Event::Focus(FocusEvent { node: left }));
    assert_eq!(
        focused_node_id_tree(&tree),
        Some(left),
        "left probe should have focus"
    );

    // Transfer focus: blur left, focus right.
    dispatch_event_to_target_tree(&mut tree, left, &Event::Blur(BlurEvent { node: left }));
    dispatch_event_to_target_tree(&mut tree, right, &Event::Focus(FocusEvent { node: right }));

    assert_eq!(
        focused_node_id_tree(&tree),
        Some(right),
        "right probe should have focus after transfer"
    );

    // Verify sink: left gained then lost, right gained.
    let events = sink.lock().unwrap_or_else(|e| e.into_inner()).clone();
    assert!(
        events.contains(&"left:true".to_string()),
        "left should have gained focus; events={events:?}"
    );
    assert!(
        events.contains(&"left:false".to_string()),
        "left should have lost focus after transfer; events={events:?}"
    );
    assert!(
        events.contains(&"right:true".to_string()),
        "right should have gained focus; events={events:?}"
    );

    // Verify ordering: left:true before left:false before right:true.
    let left_true_pos = events.iter().position(|e| e == "left:true").unwrap();
    let left_false_pos = events.iter().position(|e| e == "left:false").unwrap();
    let right_true_pos = events.iter().position(|e| e == "right:true").unwrap();
    assert!(
        left_true_pos < left_false_pos && left_false_pos < right_true_pos,
        "focus events should be ordered: left:true < left:false < right:true; events={events:?}"
    );
}

#[test]
fn p1g13_focus_transfer_no_dual_focus() {
    // Verify that after transfer, only one node reports has_focus == true.
    let sink = Arc::new(Mutex::new(Vec::new()));
    let mut root = Container::new()
        .with_child(TreeFocusProbe::new("one", sink.clone()))
        .with_child(TreeFocusProbe::new("two", sink.clone()))
        .with_child(TreeFocusProbe::new("three", sink.clone()));

    let mut tree = build_widget_tree_from_root(&mut root).expect("tree should have children");
    run_layout_pass(&mut tree, (40, 10));

    let root_id = tree.root().unwrap();
    let children: Vec<NodeId> = tree.children(root_id).to_vec();
    assert!(children.len() >= 3);

    let one = children[0];
    let two = children[1];
    let three = children[2];

    // Focus "one".
    dispatch_event_to_target_tree(&mut tree, one, &Event::Focus(FocusEvent { node: one }));
    assert_eq!(focused_node_id_tree(&tree), Some(one));

    // Transfer: one -> two.
    dispatch_event_to_target_tree(&mut tree, one, &Event::Blur(BlurEvent { node: one }));
    dispatch_event_to_target_tree(&mut tree, two, &Event::Focus(FocusEvent { node: two }));
    assert_eq!(focused_node_id_tree(&tree), Some(two));

    // Transfer: two -> three.
    dispatch_event_to_target_tree(&mut tree, two, &Event::Blur(BlurEvent { node: two }));
    dispatch_event_to_target_tree(&mut tree, three, &Event::Focus(FocusEvent { node: three }));
    assert_eq!(
        focused_node_id_tree(&tree),
        Some(three),
        "only 'three' should be focused"
    );
}

// ===========================================================================
// Additional: tree-wide focus tracking with focused_node_id_tree
// ===========================================================================

#[test]
fn p1g13_focused_node_id_tree_returns_none_when_no_focus() {
    let sink = Arc::new(Mutex::new(Vec::new()));
    let mut root = Container::new()
        .with_child(TreeFocusProbe::new("x", sink.clone()))
        .with_child(TreeFocusProbe::new("y", sink.clone()));

    let tree = build_widget_tree_from_root(&mut root).expect("tree should have children");

    assert_eq!(
        focused_node_id_tree(&tree),
        None,
        "no node should be focused initially"
    );
}

#[test]
fn p1g13_focused_node_id_tree_tracks_single_focus() {
    let sink = Arc::new(Mutex::new(Vec::new()));
    let mut root = Container::new()
        .with_child(TreeFocusProbe::new("alpha", sink.clone()))
        .with_child(Label::new("not focusable"))
        .with_child(TreeFocusProbe::new("beta", sink.clone()));

    let mut tree = build_widget_tree_from_root(&mut root).expect("tree should have children");
    run_layout_pass(&mut tree, (40, 10));

    let root_id = tree.root().unwrap();
    let children: Vec<NodeId> = tree.children(root_id).to_vec();

    // Alpha is first child, beta is third.
    let alpha = children[0];

    dispatch_event_to_target_tree(&mut tree, alpha, &Event::Focus(FocusEvent { node: alpha }));
    assert_eq!(
        focused_node_id_tree(&tree),
        Some(alpha),
        "focused_node_id_tree should track the focused probe"
    );

    // Verify non-focusable Label doesn't interfere.
    let events = sink.lock().unwrap_or_else(|e| e.into_inner()).clone();
    assert!(
        events.contains(&"alpha:true".to_string()),
        "alpha should record focus; events={events:?}"
    );
}

// ===========================================================================
// Structural: build_widget_tree_from_root produces correct tree shape
// ===========================================================================

#[test]
fn p1g13_tree_structure_matches_widget_hierarchy() {
    let sink = Arc::new(Mutex::new(Vec::new()));
    let mut root = Container::new()
        .with_child(TreeFocusProbe::new("A", sink.clone()))
        .with_child(
            Vertical::new()
                .with_child(TreeFocusProbe::new("B", sink.clone()))
                .with_child(TreeFocusProbe::new("C", sink)),
        );

    let tree = build_widget_tree_from_root(&mut root).expect("tree should build");
    let root_id = tree.root().unwrap();

    // Root (TreeStub) should have 2 children: ProbeA and Vertical.
    let top_children = tree.children(root_id);
    assert_eq!(
        top_children.len(),
        2,
        "root should have 2 top-level children"
    );

    // Second child (Vertical) should have 2 children: ProbeB and ProbeC.
    let vertical = top_children[1];
    let vertical_children = tree.children(vertical);
    assert_eq!(
        vertical_children.len(),
        2,
        "Vertical container should have 2 children"
    );

    // All leaf nodes should be focusable probes.
    let probe_a = top_children[0];
    let probe_b = vertical_children[0];
    let probe_c = vertical_children[1];

    assert!(
        tree.children(probe_a).is_empty(),
        "probe A should be a leaf"
    );
    assert!(
        tree.children(probe_b).is_empty(),
        "probe B should be a leaf"
    );
    assert!(
        tree.children(probe_c).is_empty(),
        "probe C should be a leaf"
    );
}

// ===========================================================================
// Event dispatch through tree: key events reach focused widget
// ===========================================================================

#[test]
fn p1g13_key_event_dispatched_to_focused_node_via_tree() {
    use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

    /// Probe that records key events.
    struct KeyProbe {
        focused: bool,
        keys: Arc<Mutex<Vec<String>>>,
    }

    impl KeyProbe {
        fn new(keys: Arc<Mutex<Vec<String>>>) -> Self {
            Self {
                focused: false,
                keys,
            }
        }
    }

    impl Widget for KeyProbe {
        fn render(&self, _console: &Console, _options: &ConsoleOptions) -> Segments {
            Segments::new()
        }
        fn layout_height(&self) -> Option<usize> {
            Some(1)
        }
        fn focusable(&self) -> bool {
            true
        }
        fn has_focus(&self) -> bool {
            self.focused
        }
        fn set_focus(&mut self, focused: bool) {
            self.focused = focused;
        }
        fn on_event(&mut self, event: &Event, ctx: &mut EventCtx) {
            match event {
                Event::Focus(_) => {
                    self.set_focus(true);
                    ctx.set_handled();
                }
                Event::Key(key_data) => {
                    self.keys
                        .lock()
                        .unwrap_or_else(|e| e.into_inner())
                        .push(key_data.key.clone());
                    ctx.set_handled();
                }
                _ => {}
            }
        }
    }

    let keys = Arc::new(Mutex::new(Vec::new()));
    let mut root = Container::new()
        .with_child(Label::new("header"))
        .with_child(KeyProbe::new(keys.clone()));

    let mut tree = build_widget_tree_from_root(&mut root).expect("tree should have children");
    run_layout_pass(&mut tree, (40, 10));

    let root_id = tree.root().unwrap();
    let children: Vec<NodeId> = tree.children(root_id).to_vec();
    let probe_id = children[1]; // KeyProbe is the second child.

    // Focus the probe.
    dispatch_event_to_target_tree(
        &mut tree,
        probe_id,
        &Event::Focus(FocusEvent { node: probe_id }),
    );
    assert_eq!(focused_node_id_tree(&tree), Some(probe_id));

    // Dispatch a key event to the focused node.
    let tab_event = Event::Key(KeyEventData::from_crossterm(KeyEvent::new(
        KeyCode::Char('a'),
        KeyModifiers::NONE,
    )));
    let outcome = dispatch_event_tree(&mut tree, Some(probe_id), &tab_event);
    assert!(
        outcome.handled,
        "key event should be handled by focused probe"
    );

    let recorded = keys.lock().unwrap_or_else(|e| e.into_inner()).clone();
    assert!(
        !recorded.is_empty(),
        "focused probe should receive the key event; recorded={recorded:?}"
    );
}

#[test]
fn p1g13_buttons_advanced_like_chain_focus_transfer_is_single_owner() {
    let sink = Arc::new(Mutex::new(Vec::new()));
    let mut root =
        Dock::new().push_fill(ScrollView::new(Horizontal::new().with_compose(compose![
            VerticalScroll::new().with_compose(compose![
                TreeFocusProbe::new("left_a", sink.clone()),
                TreeFocusProbe::new("left_b", sink.clone()),
            ]),
            VerticalScroll::new().with_compose(compose![
                TreeFocusProbe::new("right_a", sink.clone()),
                TreeFocusProbe::new("right_b", sink.clone()),
            ]),
        ])));

    let mut tree = build_widget_tree_from_root(&mut root).expect("tree should have children");
    run_layout_pass(&mut tree, (80, 20));

    let root_id = tree.root().unwrap();
    let leaves: Vec<NodeId> = tree
        .walk_depth_first(root_id)
        .into_iter()
        .filter(|&id| tree.children(id).is_empty())
        .collect();
    assert!(
        leaves.len() >= 4,
        "expected at least four focus probes in wrapper chain, got {}",
        leaves.len()
    );

    let mut left_a = None;
    let mut right_a = None;
    for leaf in leaves {
        let before_len = sink.lock().unwrap_or_else(|e| e.into_inner()).len();
        let outcome = dispatch_event_to_target_tree(
            &mut tree,
            leaf,
            &Event::Focus(FocusEvent { node: leaf }),
        );
        let focused = focused_node_id_tree(&tree);
        let events = sink.lock().unwrap_or_else(|e| e.into_inner()).clone();
        let new_events = &events[before_len..];
        if outcome.handled && focused == Some(leaf) {
            if new_events.iter().any(|event| event == "left_a:true") {
                left_a = Some(leaf);
            }
            if new_events.iter().any(|event| event == "right_a:true") {
                right_a = Some(leaf);
            }
        }
        if let Some(current) = focused {
            dispatch_event_to_target_tree(
                &mut tree,
                current,
                &Event::Blur(BlurEvent { node: current }),
            );
        }
        if left_a.is_some() && right_a.is_some() {
            break;
        }
    }
    let left_a = left_a.expect("left_a probe node should be discoverable in tree leaves");
    let right_a = right_a.expect("right_a probe node should be discoverable in tree leaves");

    dispatch_event_to_target_tree(
        &mut tree,
        left_a,
        &Event::Focus(FocusEvent { node: left_a }),
    );
    assert_eq!(focused_node_id_tree(&tree), Some(left_a));

    dispatch_event_to_target_tree(&mut tree, left_a, &Event::Blur(BlurEvent { node: left_a }));
    dispatch_event_to_target_tree(
        &mut tree,
        right_a,
        &Event::Focus(FocusEvent { node: right_a }),
    );
    assert_eq!(focused_node_id_tree(&tree), Some(right_a));

    let events = sink.lock().unwrap_or_else(|e| e.into_inner()).clone();
    assert!(events.contains(&"left_a:true".to_string()));
    assert!(events.contains(&"left_a:false".to_string()));
    assert!(events.contains(&"right_a:true".to_string()));
}