y901-ui 0.4.0

Widget tree, layout, events and theming for Y901.
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
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
//! 框架层集成测试。
//!
//! 重点验证内核三条硬指标:
//! 1. 2000 节点树在相同约束下第二次布局,`measure` 调用次数为 **0**;
//! 2. 无界约束返回**有限**内容尺寸,不产生 inf / NaN;
//! 3. 脏区能整棵剪掉不相交的子树,悬停只弄脏两个节点。

use y901_ui::layout::{flex_measure, Flex, LayoutCache};
use y901_ui::{
    Axis, Color, Command, Constraints, EventPhase, EventResult, FlexItem, Json, Pos, Rect,
    RenderCtx, Role, Size, TextMetrics, TextStyle, UiEvent, UiTree, Widget,
};

thread_local! {
    /// 每个测试线程独立计数,避免并行测试互相干扰。
    static MEASURE_CALLS: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
}

fn reset_measures() {
    MEASURE_CALLS.with(|c| c.set(0));
}

fn measure_count() -> u32 {
    MEASURE_CALLS.with(|c| c.get())
}

fn bump_measure() {
    MEASURE_CALLS.with(|c| c.set(c.get() + 1));
}

// ---------- 假后端 ----------

struct MonoMetrics;

impl TextMetrics for MonoMetrics {
    fn measure_text(&self, text: &str, _style: &TextStyle) -> Size {
        Size::new(text.chars().count() as f32 * 8.0, 16.0)
    }
    fn line_height(&self, _style: &TextStyle) -> f32 {
        16.0
    }
    fn scale(&self) -> f32 {
        1.0
    }
}

/// 记录绘制指令的后端(本文件只关心计数,不保留内容)
#[derive(Default)]
struct Recorder {}

impl TextMetrics for Recorder {
    fn measure_text(&self, t: &str, s: &TextStyle) -> Size {
        MonoMetrics.measure_text(t, s)
    }
    fn line_height(&self, s: &TextStyle) -> f32 {
        MonoMetrics.line_height(s)
    }
    fn scale(&self) -> f32 {
        1.0
    }
}

impl RenderCtx for Recorder {
    fn size(&self) -> Size {
        Size::new(800.0, 600.0)
    }
    fn fill_rect(&mut self, _r: Rect, _c: Color) {}
    fn stroke_rect(&mut self, _r: Rect, _c: Color, _w: f32) {}
    fn draw_text(&mut self, _o: Pos, _t: &str, _s: &TextStyle) -> f32 {
        0.0
    }
    fn push_clip(&mut self, _r: Rect) {}
    fn pop_clip(&mut self) {}
}

// ---------- 测试用叶子 ----------

struct Leaf {
    id: String,
    version: u64,
    rect: Rect,
    item: FlexItem,
}

impl Leaf {
    fn new(id: &str) -> Self {
        Self {
            id: id.to_string(),
            version: 0,
            rect: Rect::ZERO,
            item: FlexItem::default(),
        }
    }

    fn flex_item(mut self, item: FlexItem) -> Self {
        self.item = item;
        self
    }
}

impl Widget for Leaf {
    fn id(&self) -> &str {
        &self.id
    }

    fn layout_version(&self) -> u64 {
        self.version
    }

    fn flex(&self) -> FlexItem {
        self.item
    }

    /// 测试夹具:Leaf 需要能被 set_focus(新语义要求目标 `focusable()`)。
    fn focusable(&self) -> bool {
        true
    }

    fn measure(&mut self, _m: &dyn TextMetrics, c: Constraints, _cache: &mut LayoutCache) -> Size {
        bump_measure();
        c.constrain(Size::new(10.0, 20.0))
    }

    fn arrange(&mut self, rect: Rect, _m: &dyn TextMetrics, _cache: &mut LayoutCache) {
        self.rect = rect;
    }

    fn rect(&self) -> Rect {
        self.rect
    }

    fn render(&mut self, ctx: &mut dyn RenderCtx) {
        // 只记录"我画了",用一个标记 id 进入 texts 不方便,这里用 rect 占位
        ctx.fill_rect(self.rect, Color::WHITE);
    }
}

/// 会记录自己被画过的叶子。
struct Tracked {
    inner: Leaf,
    seen: std::rc::Rc<std::cell::RefCell<Vec<String>>>,
}

impl Widget for Tracked {
    fn id(&self) -> &str {
        self.inner.id()
    }
    fn layout_version(&self) -> u64 {
        self.inner.version
    }
    fn measure(&mut self, m: &dyn TextMetrics, c: Constraints, cache: &mut LayoutCache) -> Size {
        self.inner.measure(m, c, cache)
    }
    fn arrange(&mut self, r: Rect, m: &dyn TextMetrics, cache: &mut LayoutCache) {
        self.inner.arrange(r, m, cache)
    }
    fn rect(&self) -> Rect {
        self.inner.rect()
    }
    fn render(&mut self, ctx: &mut dyn RenderCtx) {
        self.seen.borrow_mut().push(self.inner.id().to_string());
        self.inner.render(ctx);
    }
}

// ---------- 1. 2000 节点:第二次布局 measure = 0 ----------

fn build_2000() -> UiTree {
    // 20 组 × 100 个叶子 = 2000 个叶子 + 21 个容器
    let mut root = Flex::column("root");
    for g in 0..20 {
        let mut row = Flex::row(format!("row{g}")).flex_item(FlexItem::height(20.0));
        for i in 0..100 {
            row = row.push(Box::new(Leaf::new(&format!("leaf{g}_{i}"))));
        }
        root = root.push(Box::new(row));
    }
    UiTree::new(Box::new(root))
}

#[test]
fn second_layout_measures_zero() {
    reset_measures();
    let mut tree = build_2000();

    tree.layout(Size::new(800.0, 600.0), &MonoMetrics);
    let first = measure_count();
    assert_eq!(first, 2000, "首帧应测 2000 个叶子,实际 {first}");
    assert!(!tree.layout_stats().skipped);

    reset_measures();
    tree.layout(Size::new(800.0, 600.0), &MonoMetrics);
    let stats = tree.layout_stats();
    let second = measure_count();
    assert_eq!(second, 0, "相同约束下第二次布局必须 0 次 measure");
    assert!(stats.skipped, "整次布局应被跳过");
}

#[test]
fn changing_one_leaf_only_remeasures_its_path() {
    reset_measures();
    let mut tree = build_2000();
    tree.layout(Size::new(800.0, 600.0), &MonoMetrics);

    // 让某个叶子"尺寸变了"
    if let Some(node) = tree.find_mut("leaf7_42") {
        // 通过 downcast 拿不到具体类型,这里用事件让树自己标记脏
        let _ = node;
    }
    // 直接对布局缓存标脏(模拟 EventResult::Relayout 的效果)
    tree.mark_layout_dirty("leaf7_42");

    reset_measures();
    tree.layout(Size::new(800.0, 600.0), &MonoMetrics);
    let calls = measure_count();

    // 该叶子 + row7 + root ≈ 3,绝不应该重新测 2000 个
    assert!(calls <= 4, "只应重测脏路径,实际 {calls}");
    assert!(calls >= 1);
}

// ---------- 2. 无界约束 ----------

struct ScrollLike {
    id: String,
    child: Box<dyn Widget>,
    rect: Rect,
}

impl Widget for ScrollLike {
    fn id(&self) -> &str {
        &self.id
    }

    fn measure(&mut self, m: &dyn TextMetrics, c: Constraints, cache: &mut LayoutCache) -> Size {
        // 主轴无界:问内容到底多高
        let content = cache.measure(
            self.child.as_mut(),
            m,
            Constraints::unbounded_main(Axis::Vertical, c.max),
        );
        assert!(content.h.is_finite(), "内容高度必须是有限值");
        // 视口只取 100 高
        c.constrain(Size::new(content.w, content.h.min(100.0)))
    }

    fn arrange(&mut self, rect: Rect, m: &dyn TextMetrics, cache: &mut LayoutCache) {
        self.rect = rect;
        // 内容坐标系:子节点从视口原点向下排,不因为滚动产生巨大坐标
        self.child
            .arrange(Rect::new(rect.x, rect.y, rect.w, rect.h), m, cache);
    }

    fn rect(&self) -> Rect {
        self.rect
    }

    fn children(&self) -> &[Box<dyn Widget>] {
        std::slice::from_ref(&self.child)
    }

    fn render(&mut self, _ctx: &mut dyn RenderCtx) {}
}

#[test]
fn unbounded_measure_returns_finite_content() {
    let mut column = Flex::column("content");
    for i in 0..50 {
        column = column.push(Box::new(Leaf::new(&format!("row{i}"))));
    }
    let mut scroll = ScrollLike {
        id: "scroll".into(),
        child: Box::new(column),
        rect: Rect::ZERO,
    };

    let mut cache = LayoutCache::new();
    let size = scroll.measure(
        &MonoMetrics,
        Constraints::unbounded_main(Axis::Vertical, Size::new(300.0, 0.0)),
        &mut cache,
    );

    assert!(size.h.is_finite());
    assert_eq!(size.h, 100.0, "视口应被限制在 100");
    // 内容真实高度 = 50 × 20
    let content = cache.measure(
        scroll.child.as_mut(),
        &MonoMetrics,
        Constraints::unbounded_main(Axis::Vertical, Size::new(300.0, 0.0)),
    );
    assert_eq!(content.h, 1000.0, "内容尺寸必须是真实值,不是 inf");
}

#[test]
fn infinite_constraints_never_produce_nan() {
    let mut cache = LayoutCache::new();
    let mut leaf = Leaf::new("x");
    let c = Constraints {
        max: Size::new(f32::INFINITY, f32::INFINITY),
        min: Size::ZERO,
        unbounded: y901_ui::Axis2::BOTH,
    };
    let size = leaf.measure(&MonoMetrics, c, &mut cache);
    assert!(size.w.is_finite() && size.h.is_finite());
}

// ---------- 3. 脏区剪枝 ----------

#[test]
fn dirty_region_prunes_untouched_subtrees() {
    let seen = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
    let mk = |id: &str| {
        Box::new(Tracked {
            inner: Leaf::new(id),
            seen: seen.clone(),
        }) as Box<dyn Widget>
    };

    let root = Flex::row("root")
        // 两列之间留 8px 缝:标脏会按墨迹外扩(默认度量下每边 2px),
        // 贴边时外扩会越过中缝碰到右半树,那属于"应该重画",不是剪枝失败。
        .gap(8.0)
        .push(Box::new(
            Flex::column("left")
                .flex_item(FlexItem::fill())
                .push(mk("a"))
                .push(mk("b")),
        ))
        .push(Box::new(
            Flex::column("right")
                .flex_item(FlexItem::fill())
                .push(mk("c"))
                .push(mk("d")),
        ));

    let mut tree = UiTree::new(Box::new(root));
    tree.layout(Size::new(400.0, 200.0), &MonoMetrics);

    // 首帧:全画
    let mut rec = Recorder::default();
    tree.render(&mut rec);
    assert_eq!(seen.borrow().len(), 4, "首帧应画出全部 4 个叶子");

    seen.borrow_mut().clear();
    tree.invalidate("a");
    tree.render(&mut rec);

    let drawn = seen.borrow().clone();
    assert!(drawn.contains(&"a".to_string()));
    assert!(!drawn.contains(&"c".to_string()), "右半树应被剪掉");
    assert!(!drawn.contains(&"d".to_string()), "右半树应被剪掉");
}

#[test]
fn hover_only_dirties_two_nodes() {
    let root = Flex::row("root")
        .push(Box::new(Leaf::new("a").flex_item(FlexItem {
            width: y901_ui::Dimension::Px(100.0),
            height: y901_ui::Dimension::Flex(1.0),
            // 新增的 min/max 字段用默认值(无限制)。
            ..FlexItem::NO_LIMITS
        })))
        .push(Box::new(Leaf::new("b").flex_item(FlexItem {
            width: y901_ui::Dimension::Px(100.0),
            height: y901_ui::Dimension::Flex(1.0),
            ..FlexItem::NO_LIMITS
        })));

    let mut tree = UiTree::new(Box::new(root));
    tree.layout(Size::new(200.0, 100.0), &MonoMetrics);
    // 消费首帧脏区
    let mut rec = Recorder::default();
    tree.render(&mut rec);

    tree.dispatch(&UiEvent::MouseMove {
        pos: Pos::new(50.0, 50.0),
    });
    assert_eq!(tree.hovered(), Some("a"));
    assert_eq!(tree.dirty().len(), 1, "只有 a 变脏");

    tree.dispatch(&UiEvent::MouseMove {
        pos: Pos::new(150.0, 50.0),
    });
    assert_eq!(tree.hovered(), Some("b"));
    // a 与 b 是相邻兄弟(共用一条边)。边贴边合并之后只剩 1 块脏区——
    // 这是预期行为(合并只会让脏区变大,不会漏画),所以改成断言覆盖范围。
    let b = tree.dirty().bounds().expect("应有脏区");
    let (ra, rb) = (tree.rect_of("a").expect("a"), tree.rect_of("b").expect("b"));
    assert!(
        b.contains(y901_ui::Pos::new(ra.x + 1.0, ra.y + 1.0))
            && b.contains(y901_ui::Pos::new(rb.x + 1.0, rb.y + 1.0)),
        "脏区必须同时覆盖旧节点 a 与新节点 b:{b:?}"
    );
    assert!(!tree.dirty().is_full(), "不能退化成整窗");

    // 渲染后脏区清空
    tree.render(&mut rec);
    assert!(tree.dirty().is_empty());
}

// ---------- 4. 命令仍然是纯搬运 ----------

#[test]
fn commands_are_routed_not_interpreted() {
    struct Emitter {
        id: String,
        rect: Rect,
    }
    impl Widget for Emitter {
        fn id(&self) -> &str {
            &self.id
        }
        fn measure(
            &mut self,
            _m: &dyn TextMetrics,
            c: Constraints,
            _cache: &mut LayoutCache,
        ) -> Size {
            c.constrain(Size::new(10.0, 10.0))
        }
        fn arrange(&mut self, r: Rect, _m: &dyn TextMetrics, _cache: &mut LayoutCache) {
            self.rect = r;
        }
        fn rect(&self) -> Rect {
            self.rect
        }
        fn event(&mut self, ctx: &mut y901_ui::EventCtx, ev: &UiEvent) -> EventResult {
            match ev {
                UiEvent::Action { name, .. } if name == "ping" => {
                    ctx.emit_app("pong", Json::obj());
                    EventResult::Handled
                }
                _ => EventResult::Ignored,
            }
        }
        fn render(&mut self, _ctx: &mut dyn RenderCtx) {}
    }

    let mut tree = UiTree::new(Box::new(Emitter {
        id: "e".into(),
        rect: Rect::ZERO,
    }));
    tree.layout(Size::new(50.0, 20.0), &MonoMetrics);
    tree.dispatch_to(
        "e",
        &UiEvent::Action {
            name: "ping".into(),
            args: Json::obj(),
        },
    );
    let cmds = tree.drain_commands();
    assert_eq!(cmds.len(), 1);
    assert!(matches!(&cmds[0], Command::App { name, .. } if name == "pong"));
}

// ---------- 6. 兼容性:Flex 直接测量 ----------

#[test]
fn flex_measure_is_cached_too() {
    let mut cache = LayoutCache::new();
    let mut children: Vec<Box<dyn Widget>> =
        vec![Box::new(Leaf::new("x")), Box::new(Leaf::new("y"))];

    reset_measures();
    let c = Constraints::loose(Size::new(100.0, 100.0));
    let s1 = flex_measure(
        Axis::Vertical,
        y901_ui::Edges::ZERO,
        0.0,
        &mut children,
        &MonoMetrics,
        c,
        &mut cache,
    );
    let first = measure_count();
    let s2 = flex_measure(
        Axis::Vertical,
        y901_ui::Edges::ZERO,
        0.0,
        &mut children,
        &MonoMetrics,
        c,
        &mut cache,
    );
    assert_eq!(first, 2);
    assert_eq!(measure_count(), 2, "第二次应全部命中缓存");
    assert_eq!(s1, s2);
    assert_eq!(Role::PANEL.as_str(), "panel");
}

// ---------- 7. 三阶段路由 + 指针捕获 ----------

type Log = std::rc::Rc<std::cell::RefCell<Vec<(String, EventPhase)>>>;

/// 记录"我在哪个阶段收到了事件"的探针。
struct Probe {
    id: String,
    log: Log,
    capture_pointer: bool,
    rect: Rect,
    item: FlexItem,
}

impl Probe {
    fn new(id: &str, log: Log) -> Self {
        Self {
            id: id.to_string(),
            log,
            capture_pointer: false,
            rect: Rect::ZERO,
            item: FlexItem::default(),
        }
    }

    fn flex_item(mut self, item: FlexItem) -> Self {
        self.item = item;
        self
    }
}

impl Widget for Probe {
    fn id(&self) -> &str {
        &self.id
    }
    fn flex(&self) -> FlexItem {
        self.item
    }
    fn measure(&mut self, _m: &dyn TextMetrics, c: Constraints, _cache: &mut LayoutCache) -> Size {
        c.constrain(Size::new(10.0, 10.0))
    }
    fn arrange(&mut self, r: Rect, _m: &dyn TextMetrics, _cache: &mut LayoutCache) {
        self.rect = r;
    }
    fn rect(&self) -> Rect {
        self.rect
    }
    fn event(&mut self, ctx: &mut y901_ui::EventCtx, event: &UiEvent) -> EventResult {
        self.log.borrow_mut().push((self.id.clone(), ctx.phase));
        match event {
            UiEvent::MouseDown { .. } if self.capture_pointer => {
                ctx.set_pointer_capture(self.id.clone());
                EventResult::Handled
            }
            UiEvent::MouseDown { .. } | UiEvent::MouseUp { .. } | UiEvent::MouseMove { .. } => {
                EventResult::Handled
            }
            _ => EventResult::Ignored,
        }
    }
    fn render(&mut self, _ctx: &mut dyn RenderCtx) {}
}

/// 单子节点容器:可选在 Capture 阶段把事件停掉。
struct Frame {
    id: String,
    children: Vec<Box<dyn Widget>>,
    rect: Rect,
    log: Log,
    stop_in_capture: bool,
    handle_in_bubble: bool,
}

impl Frame {
    fn new(id: &str, child: Box<dyn Widget>, log: Log) -> Self {
        Self {
            id: id.to_string(),
            children: vec![child],
            rect: Rect::ZERO,
            log,
            stop_in_capture: false,
            handle_in_bubble: false,
        }
    }
}

impl Widget for Frame {
    fn id(&self) -> &str {
        &self.id
    }
    fn measure(&mut self, m: &dyn TextMetrics, c: Constraints, cache: &mut LayoutCache) -> Size {
        cache.measure(self.children[0].as_mut(), m, c)
    }
    fn arrange(&mut self, r: Rect, m: &dyn TextMetrics, cache: &mut LayoutCache) {
        self.rect = r;
        self.children[0].arrange(r, m, cache);
    }
    fn rect(&self) -> Rect {
        self.rect
    }
    fn children(&self) -> &[Box<dyn Widget>] {
        &self.children
    }
    fn children_mut(&mut self) -> Option<&mut Vec<Box<dyn Widget>>> {
        Some(&mut self.children)
    }
    fn event(&mut self, ctx: &mut y901_ui::EventCtx, ev: &UiEvent) -> EventResult {
        self.log.borrow_mut().push((self.id.clone(), ctx.phase));

        if self.stop_in_capture && ctx.phase == EventPhase::Capture {
            ctx.stop_propagation();
            return EventResult::Handled;
        }
        if self.handle_in_bubble
            && ctx.phase == EventPhase::Bubble
            && matches!(ev, UiEvent::MouseDown { .. })
        {
            return EventResult::Handled;
        }
        EventResult::Ignored
    }
    fn render(&mut self, _ctx: &mut dyn RenderCtx) {}
}

/// 对鼠标事件一律 Ignored 的叶子,用来触发冒泡。
struct Pass {
    id: String,
    rect: Rect,
    log: Log,
}

impl Widget for Pass {
    fn id(&self) -> &str {
        &self.id
    }
    fn measure(&mut self, _m: &dyn TextMetrics, c: Constraints, _cache: &mut LayoutCache) -> Size {
        c.constrain(Size::new(10.0, 10.0))
    }
    fn arrange(&mut self, r: Rect, _m: &dyn TextMetrics, _cache: &mut LayoutCache) {
        self.rect = r;
    }
    fn rect(&self) -> Rect {
        self.rect
    }
    fn event(&mut self, ctx: &mut y901_ui::EventCtx, _ev: &UiEvent) -> EventResult {
        self.log.borrow_mut().push((self.id.clone(), ctx.phase));
        EventResult::Ignored
    }
    fn render(&mut self, _ctx: &mut dyn RenderCtx) {}
}

fn click(x: f32, y: f32) -> UiEvent {
    UiEvent::MouseDown {
        pos: Pos::new(x, y),
        button: y901_ui::MouseButton::Left,
    }
}

#[test]
fn capture_phase_can_stop_propagation() {
    let log: Log = Default::default();

    let mut root = Frame::new(
        "root",
        Box::new(Pass {
            id: "child".into(),
            rect: Rect::ZERO,
            log: log.clone(),
        }),
        log.clone(),
    );
    root.stop_in_capture = true;

    let mut tree = UiTree::new(Box::new(root));
    tree.layout(Size::new(100.0, 100.0), &MonoMetrics);

    tree.dispatch(&click(10.0, 10.0));

    let entries = log.borrow().clone();
    assert_eq!(
        entries.len(),
        1,
        "只应有根节点在 Capture 收到,实际 {entries:?}"
    );
    assert_eq!(entries[0], ("root".to_string(), EventPhase::Capture));
    assert!(
        !entries.iter().any(|(id, _)| id == "child"),
        "Capture 被 stop 后子节点必须收不到"
    );
}

#[test]
fn three_phases_in_order() {
    let log: Log = Default::default();

    let mut root = Frame::new(
        "parent",
        Box::new(Pass {
            id: "child".into(),
            rect: Rect::ZERO,
            log: log.clone(),
        }),
        log.clone(),
    );
    root.handle_in_bubble = true;

    let mut tree = UiTree::new(Box::new(root));
    tree.layout(Size::new(100.0, 100.0), &MonoMetrics);

    tree.dispatch(&click(10.0, 10.0));

    let phases = log.borrow().clone();
    assert_eq!(
        phases,
        vec![
            ("parent".to_string(), EventPhase::Capture),
            ("child".to_string(), EventPhase::Target),
            ("parent".to_string(), EventPhase::Bubble),
        ],
        "顺序必须是 Capture → Target → Bubble"
    );
}

#[test]
fn pointer_capture_routes_moves_outside_the_node() {
    let log: Log = Default::default();

    let mut a = Probe::new("a", log.clone()).flex_item(FlexItem::fill());
    a.capture_pointer = true;
    let b = Probe::new("b", log.clone()).flex_item(FlexItem::fill());

    let root = Flex::row("root")
        .push(Box::new(
            Flex::column("left")
                .flex_item(FlexItem::fill())
                .push(Box::new(a)),
        ))
        .push(Box::new(
            Flex::column("right")
                .flex_item(FlexItem::fill())
                .push(Box::new(b)),
        ));

    let mut tree = UiTree::new(Box::new(root));
    tree.layout(Size::new(200.0, 100.0), &MonoMetrics);

    // 在左半边按下 → a 捕获指针
    tree.dispatch(&click(20.0, 50.0));
    log.borrow_mut().clear();

    // 移到右半边(几何上命中 b),但仍应派发给 a
    tree.dispatch(&UiEvent::MouseMove {
        pos: Pos::new(180.0, 50.0),
    });

    let entries = log.borrow().clone();
    assert!(
        entries.iter().any(|(id, _)| id == "a"),
        "捕获者应收到越界移动,实际 {entries:?}"
    );
    assert!(
        !entries.iter().any(|(id, _)| id == "b"),
        "未被捕获的节点不应收到移动"
    );

    // 抬起后自动释放
    tree.dispatch(&UiEvent::MouseUp {
        pos: Pos::new(180.0, 50.0),
        button: y901_ui::MouseButton::Left,
    });
    log.borrow_mut().clear();

    // 之后的移动回到正常命中测试(b)
    tree.dispatch(&UiEvent::MouseMove {
        pos: Pos::new(180.0, 50.0),
    });
    let entries = log.borrow().clone();
    assert!(
        entries.iter().any(|(id, _)| id == "b"),
        "释放后应恢复正常命中,实际 {entries:?}"
    );
}

// ---------- 8. 路径查找 O(d) + 模态作用域 ----------

use std::cell::Cell;
use std::rc::Rc;

/// 每收到一次事件就 +1 的链式容器。
struct Counted {
    id: String,
    kids: Vec<Box<dyn Widget>>,
    rect: Rect,
    count: Rc<Cell<u32>>,
}

impl Widget for Counted {
    fn id(&self) -> &str {
        &self.id
    }
    fn measure(&mut self, m: &dyn TextMetrics, c: Constraints, cache: &mut LayoutCache) -> Size {
        match self.kids.first_mut() {
            Some(k) => cache.measure(k.as_mut(), m, c),
            None => c.constrain(Size::new(100.0, 100.0)),
        }
    }
    fn arrange(&mut self, r: Rect, m: &dyn TextMetrics, cache: &mut LayoutCache) {
        self.rect = r;
        // 只排布首个孩子:多出来的"兄弟"保持零矩形,不参与命中
        if let Some(k) = self.kids.first_mut() {
            k.arrange(r, m, cache);
        }
    }
    fn rect(&self) -> Rect {
        self.rect
    }
    fn children(&self) -> &[Box<dyn Widget>] {
        &self.kids
    }
    fn children_mut(&mut self) -> Option<&mut Vec<Box<dyn Widget>>> {
        Some(&mut self.kids)
    }
    fn event(&mut self, _ctx: &mut y901_ui::EventCtx, _ev: &UiEvent) -> EventResult {
        self.count.set(self.count.get() + 1);
        EventResult::Ignored
    }
    fn render(&mut self, _ctx: &mut dyn RenderCtx) {}
}

fn chain(depth: usize, count: Rc<Cell<u32>>, with_siblings: usize) -> UiTree {
    // 从叶子往上套 depth 层
    let mut node: Box<dyn Widget> = Box::new(Counted {
        id: format!("n{depth}"),
        kids: Vec::new(),
        rect: Rect::ZERO,
        count: count.clone(),
    });
    for i in (0..depth).rev() {
        node = Box::new(Counted {
            id: format!("n{i}"),
            kids: vec![node],
            rect: Rect::ZERO,
            count: count.clone(),
        });
    }
    // 根节点额外挂一堆兄弟(只为把 n 放大,几何上不参与命中)
    let mut root = Counted {
        id: "root".into(),
        kids: vec![node],
        rect: Rect::ZERO,
        count: count.clone(),
    };
    for i in 0..with_siblings {
        root.kids.push(Box::new(Counted {
            id: format!("s{i}"),
            kids: Vec::new(),
            rect: Rect::ZERO,
            count: count.clone(),
        }));
    }
    // 根必须是 Flex 才能让 kids[0] 拿到整个视口
    UiTree::new(Box::new(Flex::column("frame").push(Box::new(root))))
}

#[test]
fn click_dispatch_is_linear_in_depth() {
    // 32 个计数节点(root + n0..n30)→ Capture 31 + Target 1 + Bubble 31 = 63
    let count = Rc::new(Cell::new(0));
    let mut tree = chain(30, count.clone(), 0);
    tree.layout(Size::new(200.0, 200.0), &MonoMetrics);

    count.set(0);
    tree.dispatch(&UiEvent::MouseDown {
        pos: Pos::new(10.0, 10.0),
        button: y901_ui::MouseButton::Left,
    });
    let small = count.get();
    assert_eq!(small, 63, "32 个节点的链应恰好访问 63 次(2d-1)");

    // 同一深度,但树里多 1000 个节点:访问次数必须完全不变
    let count2 = Rc::new(Cell::new(0));
    let mut big = chain(30, count2.clone(), 1000);
    big.layout(Size::new(200.0, 200.0), &MonoMetrics);

    count2.set(0);
    big.dispatch(&UiEvent::MouseDown {
        pos: Pos::new(10.0, 10.0),
        button: y901_ui::MouseButton::Left,
    });
    assert_eq!(
        count2.get(),
        small,
        "访问次数只与深度有关,与节点总数无关(不是 O(d²) 也不是 O(n·d))"
    );
}

/// 可精确摆放子节点绝对矩形的容器,用来构造重叠与分层。
struct Stack {
    id: String,
    kids: Vec<Box<dyn Widget>>,
    slots: Vec<Rect>,
    rect: Rect,
}

impl Widget for Stack {
    fn id(&self) -> &str {
        &self.id
    }
    fn measure(&mut self, m: &dyn TextMetrics, c: Constraints, cache: &mut LayoutCache) -> Size {
        for k in self.kids.iter_mut() {
            let _ = cache.measure(k.as_mut(), m, c);
        }
        c.constrain(Size::new(200.0, 200.0))
    }
    fn arrange(&mut self, r: Rect, m: &dyn TextMetrics, cache: &mut LayoutCache) {
        self.rect = r;
        for (k, slot) in self.kids.iter_mut().zip(self.slots.iter()) {
            k.arrange(*slot, m, cache);
        }
    }
    fn rect(&self) -> Rect {
        self.rect
    }
    fn children(&self) -> &[Box<dyn Widget>] {
        &self.kids
    }
    fn children_mut(&mut self) -> Option<&mut Vec<Box<dyn Widget>>> {
        Some(&mut self.kids)
    }
    fn render(&mut self, _ctx: &mut dyn RenderCtx) {}
}

/// 可以指定是否模态的叶子。
struct Layered {
    id: String,
    rect: Rect,
    hits: Rc<Cell<u32>>,
    kids: Vec<Box<dyn Widget>>,
    /// 模态语义(画在哪层 ≠ 是否阻塞底层)。
    modal: bool,
}

impl Layered {
    fn new(id: &str, hits: Rc<Cell<u32>>) -> Self {
        Self {
            id: id.to_string(),
            rect: Rect::ZERO,
            hits,
            kids: Vec::new(),
            modal: false,
        }
    }

    /// 把它标记为模态(影响焦点与点击嗝掉)。
    fn modal(mut self) -> Self {
        self.modal = true;
        self
    }
}

impl Widget for Layered {
    fn id(&self) -> &str {
        &self.id
    }

    /// 测试夹具:Modal 内的 `modal_btn` 需要能被 set_focus。
    fn focusable(&self) -> bool {
        true
    }
    fn is_modal(&self) -> bool {
        self.modal
    }
    fn measure(&mut self, m: &dyn TextMetrics, c: Constraints, cache: &mut LayoutCache) -> Size {
        for k in self.kids.iter_mut() {
            let _ = cache.measure(k.as_mut(), m, c);
        }
        c.constrain(Size::new(100.0, 100.0))
    }
    fn arrange(&mut self, r: Rect, m: &dyn TextMetrics, cache: &mut LayoutCache) {
        self.rect = r;
        for k in self.kids.iter_mut() {
            k.arrange(r, m, cache);
        }
    }
    fn rect(&self) -> Rect {
        self.rect
    }
    fn children(&self) -> &[Box<dyn Widget>] {
        &self.kids
    }
    fn children_mut(&mut self) -> Option<&mut Vec<Box<dyn Widget>>> {
        Some(&mut self.kids)
    }
    fn event(&mut self, _ctx: &mut y901_ui::EventCtx, _ev: &UiEvent) -> EventResult {
        self.hits.set(self.hits.get() + 1);
        EventResult::Handled
    }
    fn render(&mut self, _ctx: &mut dyn RenderCtx) {}
}

fn layered_tree(modal: bool, overlay: bool) -> (UiTree, Rc<Cell<u32>>) {
    let base_hits = Rc::new(Cell::new(0));
    let modal_hits = Rc::new(Cell::new(0));
    let overlay_hits = Rc::new(Cell::new(0));

    let mut kids: Vec<Box<dyn Widget>> =
        vec![Box::new(Layered::new("base_btn", base_hits.clone()))];
    let mut slots = vec![Rect::new(0.0, 0.0, 200.0, 200.0)];

    if overlay {
        kids.push(Box::new(Layered::new("overlay", overlay_hits.clone())));
        slots.push(Rect::new(150.0, 0.0, 50.0, 50.0));
    }
    if modal {
        let mut modal_node = Layered::new("modal", modal_hits.clone()).modal();
        modal_node
            .kids
            .push(Box::new(Layered::new("modal_btn", modal_hits.clone())));
        kids.push(Box::new(modal_node));
        slots.push(Rect::new(50.0, 50.0, 100.0, 100.0));
    }

    let mut tree = UiTree::new(Box::new(Stack {
        id: "root".into(),
        kids,
        slots,
        rect: Rect::ZERO,
    }));
    tree.layout(Size::new(200.0, 200.0), &MonoMetrics);
    (tree, base_hits)
}

#[test]
fn modal_blocks_clicks_outside_and_traps_focus() {
    let (mut tree, base_hits) = layered_tree(true, false);
    let modal_hits = Rc::new(Cell::new(0));
    let _ = &modal_hits;

    // 点 Modal 外部(左上角):事件被吞掉,底层收不到
    tree.dispatch(&UiEvent::MouseDown {
        pos: Pos::new(10.0, 10.0),
        button: y901_ui::MouseButton::Left,
    });
    assert_eq!(base_hits.get(), 0, "Modal 外部点击不能穿透到底层");
    assert!(
        tree.hit_path(Pos::new(10.0, 10.0)).is_none(),
        "命中应被吞掉"
    );

    // 点 Modal 内部:命中 Modol 子树
    let hit = tree
        .hit_path(Pos::new(60.0, 60.0))
        .expect("应命中 Modal 内部");
    let id = tree.hit_test(Pos::new(60.0, 60.0)).unwrap();
    assert!(id == "modal_btn" || id == "modal", "实际命中 {id}");

    // 焦点被限制在 Modal 内
    assert!(
        !tree.set_focus(Some("base_btn".into())),
        "Modal 外节点不能获焦"
    );
    assert!(
        tree.set_focus(Some("modal_btn".into())),
        "Modal 内节点可以获焦"
    );
    assert_eq!(tree.focus(), Some("modal_btn"));
    let _ = hit;
}

#[test]
fn overlay_is_on_top_but_lets_clicks_through() {
    let (mut tree, base_hits) = layered_tree(false, true);

    // Overlay 覆盖 (150,0)-(200,50):点这里应命中 Overlay 而不是底层
    let id = tree.hit_test(Pos::new(160.0, 10.0)).unwrap();
    assert_eq!(id, "overlay");

    // Overlay 之外:点击正常落到 Base(能"穿透")
    let id = tree.hit_test(Pos::new(10.0, 10.0)).unwrap();
    assert_eq!(id, "base_btn");

    tree.dispatch(&UiEvent::MouseDown {
        pos: Pos::new(10.0, 10.0),
        button: y901_ui::MouseButton::Left,
    });
    assert_eq!(base_hits.get(), 1, "Overlay 不应阻挡底层点击");
}

#[test]
fn paint_order_follows_tree_order() {
    // 没有 `Layer` 了:**绘制顺序 = 树序**(后访问的在上)。
    // 命中与绘制共用同一份排序,所以用 hit_test 验证。
    let (tree, _) = layered_tree(false, true);
    // base 盖整窗;overlay 只盖 (150,0)-(200,50),且树序更后
    assert_eq!(
        tree.hit_test(Pos::new(160.0, 10.0)).as_deref(),
        Some("overlay"),
        "重叠处应命中树序靠后的 overlay(后画的在上)"
    );
    assert_eq!(
        tree.hit_test(Pos::new(10.0, 10.0)).as_deref(),
        Some("base_btn"),
        "未被覆盖处应命中 base"
    );

    // 模态作用域焱由 `Widget::is_modal()` 驱动(不再看 Layer)
    let (modal_tree, _) = layered_tree(true, false);
    assert!(
        modal_tree.modal_scope().is_some(),
        "模态节点应提供焦点/点击作用域"
    );
}