aetna-core 0.3.1

Aetna — backend-agnostic UI library core
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
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
//! Lint pass — surfaces the kind of issues an LLM iterating on a UI
//! benefits from knowing about, with provenance so the report only
//! flags things the user code can fix.
//!
//! Categories:
//!
//! - **Raw colors / sizes:** values that aren't tokenized. Often fine
//!   inside library code but a smell in user code.
//! - **Overflow:** child rects extending past their parent, or text
//!   exceeding its container's padded content region (centered text
//!   that spills past the padding reads as visually off-center, even
//!   when it nominally fits inside the outer rect).
//! - **Duplicate IDs:** two nodes with the same computed ID (only
//!   possible via explicit `.key(...)` collisions; pure path IDs are
//!   unique by construction).
//!
//! Provenance: every finding records the source location of the
//! offending node (via `#[track_caller]` propagation up to the user's
//! call site). User code is distinguished from aetna's own widget
//! internals by [`Source::from_library`], which a closure-builder
//! site sets explicitly via [`crate::tree::El::from_library`] when
//! `#[track_caller]` won't reach the user. Findings only attribute to
//! sources where `from_library == false`.
//!
//! Overflow findings (rect and text) walk up to the nearest
//! user-source ancestor for attribution. `#[track_caller]` doesn't
//! propagate through closures, so a widget that builds children
//! inside `.map(...)` either forwards the user's caller via
//! `.at_loc(caller)` (the prevailing pattern in aetna-core today) or
//! marks itself with `.from_library()` so the lint walks up to the
//! user's call site. Either way the user gets a finding pointing at
//! their code, not at aetna-core internals. Raw-color and surface
//! lints are still self-attributed — those are intentional inside
//! widgets and should only fire from user code directly.

use std::fmt::Write as _;

use crate::layout;
use crate::metrics::MetricsRole;
use crate::state::UiState;
use crate::tree::*;

/// A single lint finding.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct Finding {
    pub kind: FindingKind,
    pub node_id: String,
    pub source: Source,
    pub message: String,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum FindingKind {
    RawColor,
    Overflow,
    TextOverflow,
    DuplicateId,
    Alignment,
    Spacing,
    /// `surface_role(SurfaceRole::Panel)` on a node with no fill — the
    /// role only paints stroke + shadow, so the surface reads as a
    /// thin border floating over the parent. Either set a fill
    /// (`tokens::CARD` is the usual choice) or — more often — swap to a
    /// widget like `card()` / `sidebar()` that bundles role + fill +
    /// stroke + radius + shadow correctly. (`Raised` is *also*
    /// decorative but this lint stays narrow to `Panel` since
    /// `button(...).ghost()` legitimately produces a Raised node with
    /// no fill.)
    MissingSurfaceFill,
    /// A `column` / `row` / `stack` whose visual recipe matches a stock
    /// widget (card, sidebar, …). Reach for the named widget instead —
    /// it bundles the right surface role, radius, shadow, and content
    /// padding. The structural smells live in the widget catalog README;
    /// this lint catches the two highest-confidence signatures
    /// (`fill=CARD + stroke=BORDER + radius>0` ⇒ `card()`,
    /// `fill=CARD + stroke=BORDER + width=SIDEBAR_WIDTH` without a Panel
    /// surface role ⇒ `sidebar()`).
    ReinventedWidget,
    /// A focusable node's `paint_overflow` band (the focus-ring band)
    /// would render obscured at runtime — either because the nearest
    /// clipping ancestor's scissor cuts it, or because a later-painted
    /// sibling's rect overlaps the bleed region and paints on top.
    ///
    /// Common fixes:
    ///
    /// - **Clipped:** give the clipping ancestor (or an intermediate
    ///   container) padding ≥ `tokens::RING_WIDTH` on the clipped
    ///   side so the band lives inside the scissor.
    /// - **Occluded:** add gap between the focusable element and the
    ///   neighbor (≥ `tokens::RING_WIDTH`), or restructure so the
    ///   neighbor doesn't sit on the focusable element's edge.
    FocusRingObscured,
}

#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct LintReport {
    pub findings: Vec<Finding>,
}

impl LintReport {
    pub fn text(&self) -> String {
        if self.findings.is_empty() {
            return "no findings\n".to_string();
        }
        let mut s = String::new();
        for f in &self.findings {
            let _ = writeln!(
                s,
                "{kind:?} node={id} {source} :: {msg}",
                kind = f.kind,
                id = f.node_id,
                source = if f.source.line == 0 {
                    "<no-source>".to_string()
                } else {
                    format!("{}:{}", short_path(f.source.file), f.source.line)
                },
                msg = f.message,
            );
        }
        s
    }
}

/// Run the lint pass over `root`.
///
/// Findings are gated on whether the offending node (or its nearest
/// ancestor) was constructed in user code rather than inside aetna's
/// own widget closures. The signal is [`Source::from_library`], set
/// explicitly via [`crate::tree::El::from_library`] at any closure-
/// builder site that doesn't forward `Location::caller()` back to the
/// user. The vast majority of nodes propagate user source through
/// `#[track_caller]` and pass straight through.
pub fn lint(root: &El, ui_state: &UiState) -> LintReport {
    let mut r = LintReport::default();
    let mut seen_ids: std::collections::BTreeMap<String, usize> = Default::default();
    walk(
        root,
        None,
        None,
        ClipCtx::None,
        ui_state,
        &mut r,
        &mut seen_ids,
    );
    for (id, n) in seen_ids {
        if n > 1 {
            r.findings.push(Finding {
                kind: FindingKind::DuplicateId,
                node_id: id.clone(),
                source: Source::default(),
                message: format!("{n} nodes share id {id}"),
            });
        }
    }
    r
}

fn is_from_user(source: Source) -> bool {
    !source.from_library
}

/// Clipping context propagated through `walk`. Carries the nearest
/// clipping ancestor's scissor rect and, for scrollable ancestors,
/// the axis along which content can be scrolled into view (clipping
/// on that axis is benign — focus rings on partially-clipped rows
/// become visible after auto-scroll-on-focus).
#[derive(Clone, Copy)]
enum ClipCtx {
    None,
    /// Non-scrolling clip — the rect cuts on every side.
    Static(Rect),
    /// Scrolling clip — the rect cuts on the cross axis only;
    /// `scroll_axis` records the axis where overflow becomes scroll
    /// (Column = vertical, Row = horizontal).
    Scrolling {
        rect: Rect,
        scroll_axis: Axis,
    },
}

fn walk(
    n: &El,
    parent_kind: Option<&Kind>,
    parent_blame: Option<Source>,
    nearest_clip: ClipCtx,
    ui_state: &UiState,
    r: &mut LintReport,
    seen: &mut std::collections::BTreeMap<String, usize>,
) {
    *seen.entry(n.computed_id.clone()).or_default() += 1;
    let computed = ui_state.rect(&n.computed_id);

    let from_user_self = is_from_user(n.source);
    // Nearest user-source location attributable to this node — itself
    // when self is from user code, otherwise the closest ancestor's
    // user source. Used by overflow findings so widget-composed leaves
    // (e.g. `tab_trigger` built inside `tabs_list`'s `.map(...)`
    // closure, where `Location::caller()` resolves inside aetna-core)
    // still blame the user code that supplied the offending content.
    let self_blame = if from_user_self {
        Some(n.source)
    } else {
        parent_blame
    };

    // Children of an Inlines paragraph are encoded into one
    // AttributedText draw op by draw_ops; their individual rects are
    // intentionally zero-size. Skip the per-text overflow + per-child
    // overflow checks for them — the paragraph as a whole holds the
    // rect, so any overflow lint applies at the Inlines node level.
    let inside_inlines = matches!(parent_kind, Some(Kind::Inlines));

    // Raw colors are intentional inside library widgets; only flag
    // them when the node is itself in user code.
    if from_user_self {
        if let Some(c) = n.fill
            && c.token.is_none()
            && c.a > 0
        {
            r.findings.push(Finding {
                kind: FindingKind::RawColor,
                node_id: n.computed_id.clone(),
                source: n.source,
                message: format!(
                    "fill is a raw rgba({},{},{},{}) — use a token",
                    c.r, c.g, c.b, c.a
                ),
            });
        }
        if let Some(c) = n.stroke
            && c.token.is_none()
            && c.a > 0
        {
            r.findings.push(Finding {
                kind: FindingKind::RawColor,
                node_id: n.computed_id.clone(),
                source: n.source,
                message: format!(
                    "stroke is a raw rgba({},{},{},{}) — use a token",
                    c.r, c.g, c.b, c.a
                ),
            });
        }
        if let Some(c) = n.text_color
            && c.token.is_none()
            && c.a > 0
        {
            r.findings.push(Finding {
                kind: FindingKind::RawColor,
                node_id: n.computed_id.clone(),
                source: n.source,
                message: format!(
                    "text_color is a raw rgba({},{},{},{}) — use a token",
                    c.r, c.g, c.b, c.a
                ),
            });
        }
        // SurfaceRole::Panel only paints stroke + shadow on top of the
        // node's existing fill. Without a fill, the surface reads as a
        // thin border over BACKGROUND — the classic "invisible panel"
        // mistake. Suggest the right widget. (Raised is also
        // decorative but `button(...).ghost()` legitimately leaves a
        // Raised node with no fill, so the lint stays narrow.)
        if n.fill.is_none() && matches!(n.surface_role, SurfaceRole::Panel) {
            r.findings.push(Finding {
                kind: FindingKind::MissingSurfaceFill,
                node_id: n.computed_id.clone(),
                source: n.source,
                message:
                    "surface_role(Panel) without a fill paints only stroke + shadow — \
                     wrap in card() / sidebar() / dialog() for the canonical recipe, or set .fill(tokens::CARD)"
                        .to_string(),
            });
        }

        // Reinvented widgets: a plain Group whose visual recipe matches
        // a stock widget. The signatures stay narrow on purpose — both
        // require the canonical token pair (fill = CARD, stroke =
        // BORDER) and a structural marker (a non-zero radius for card,
        // an exact SIDEBAR_WIDTH for sidebar). The real widgets escape
        // these checks: `card()` returns Kind::Card, and `sidebar()`
        // sets surface_role(Panel) — so neither stock widget trips its
        // own lint when the user calls them directly.
        //
        // Skip empty Groups — a `column(Vec::<El>::new())` styled with
        // CARD/BORDER is a pure visual swatch (color sample, divider
        // stub) that's not pretending to be a card. Card-mimics
        // always wrap content.
        if matches!(n.kind, Kind::Group) && !n.children.is_empty() {
            let card_fill = n
                .fill
                .as_ref()
                .and_then(|c| c.token)
                .is_some_and(|t| t == "card");
            let border_stroke = n
                .stroke
                .as_ref()
                .and_then(|c| c.token)
                .is_some_and(|t| t == "border");
            if card_fill && border_stroke {
                let is_panel_surface = matches!(n.surface_role, SurfaceRole::Panel);
                let sidebar_width = matches!(n.width, Size::Fixed(w) if (w - crate::tokens::SIDEBAR_WIDTH).abs() < 0.5);
                if !is_panel_surface {
                    if sidebar_width {
                        r.findings.push(Finding {
                            kind: FindingKind::ReinventedWidget,
                            node_id: n.computed_id.clone(),
                            source: n.source,
                            message:
                                "Group with fill=CARD, stroke=BORDER, width=SIDEBAR_WIDTH reinvents sidebar() — \
                                 use sidebar([sidebar_header(...), sidebar_group([sidebar_menu([sidebar_menu_button(label, current)])])]) \
                                 for the panel surface and the canonical row recipe"
                                    .to_string(),
                        });
                    } else {
                        // Any other Group with the canonical card-tone
                        // pair is a hand-rolled card-or-aside surface.
                        // Both the "boxed" case (non-zero radius, fits
                        // inside another container) and the "side panel"
                        // case (full-height inspector pane) collapse
                        // into the same recipe — `card([...])` bundles
                        // it. Mention sidebar() too, since for full-bleed
                        // panels with custom widths (e.g. inspector
                        // rails) the right answer might be sidebar().
                        r.findings.push(Finding {
                            kind: FindingKind::ReinventedWidget,
                            node_id: n.computed_id.clone(),
                            source: n.source,
                            message:
                                "Group with fill=CARD, stroke=BORDER reinvents the panel-surface recipe — \
                                 use card([card_header([card_title(\"...\")]), card_content([...])]) / titled_card(\"Title\", [...]) for boxed content, \
                                 or sidebar([...]) for a full-height nav/inspector pane (sidebar() also handles the custom-width case via .width(Size::Fixed(...)))"
                                    .to_string(),
                        });
                    }
                }
            }
        }
    }

    // Row alignment: mirror CSS flex's default `align-items: stretch`,
    // but catch the common UI-row mistake where a fixed-size visual
    // child (icon/badge/control) is pinned to the row top beside a
    // text sibling. The fix is the familiar `items-center` move:
    // `.align(Align::Center)`.
    if let Some(blame) = self_blame {
        lint_row_alignment(n, computed, ui_state, r, blame);
        lint_overlay_alignment(n, computed, ui_state, r, blame);
        lint_row_visual_text_spacing(n, ui_state, r, blame);
    }

    // Text overflow: detect at the node itself (with the node's own
    // padding-aware content region — text_w includes padding so the
    // check fires when the text exceeds the padded content area, not
    // just the bare rect). Attribute to the nearest user-source
    // ancestor so closure-built widget leaves still blame user code.
    if n.text.is_some()
        && !inside_inlines
        && let Some(blame) = self_blame
    {
        let available_width = match n.text_wrap {
            TextWrap::NoWrap => None,
            TextWrap::Wrap => Some(computed.w),
        };
        if let Some(text_layout) = layout::text_layout(n, available_width) {
            let text_w = text_layout.width + n.padding.left + n.padding.right;
            let text_h = text_layout.height + n.padding.top + n.padding.bottom;
            let raw_overflow_x = (text_w - computed.w).max(0.0);
            let overflow_x = if matches!(
                (n.text_wrap, n.text_overflow),
                (TextWrap::NoWrap, TextOverflow::Ellipsis)
            ) {
                0.0
            } else {
                raw_overflow_x
            };
            let overflow_y = (text_h - computed.h).max(0.0);
            if overflow_x > 0.5 || overflow_y > 0.5 {
                let is_clipped_nowrap = overflow_x > 0.5
                    && matches!(
                        (n.text_wrap, n.text_overflow),
                        (TextWrap::NoWrap, TextOverflow::Clip)
                    );
                let kind = if is_clipped_nowrap {
                    FindingKind::TextOverflow
                } else {
                    FindingKind::Overflow
                };
                let message = if kind == FindingKind::TextOverflow {
                    format!(
                        "nowrap text exceeds its box by X={overflow_x:.0}; use .ellipsis(), wrap_text(), or a wider box"
                    )
                } else {
                    format!(
                        "text content exceeds its box by X={overflow_x:.0} Y={overflow_y:.0}; use paragraph()/wrap_text(), a wider box, or explicit clipping"
                    )
                };
                r.findings.push(Finding {
                    kind,
                    node_id: n.computed_id.clone(),
                    source: blame,
                    message,
                });
            }
        }
    }

    // Overflow: child rect extends past parent. Scrollable parents
    // overflow their content on the main axis by design — that's the
    // whole point — so don't flag children of a scroll viewport.
    // Inlines parents intentionally zero-size their children (the
    // paragraph paints them as one AttributedText), so per-child rect
    // checks would always fire — suppress. The runtime-synthesized
    // toast_stack uses a custom layout that pins cards to the
    // viewport regardless of its own (parent-allocated) rect, so its
    // children naturally extend past the layer's bounds — also
    // suppress.
    let suppress_overflow = n.scrollable
        || matches!(n.kind, Kind::Inlines)
        || matches!(n.kind, Kind::Custom("toast_stack"));

    // Update the nearest-clipping-ancestor rect for descendants. The
    // scissor in `draw_ops` uses `inner_painted_rect` (the layout
    // rect, no padding inset, no overflow outset), so this rect is
    // the right bound to compare descendant ring bands against.
    // Scrollable clips suppress clipping findings on the scroll axis
    // (auto-scroll-on-focus reveals partially-clipped rows there).
    let child_clip = if n.clip {
        if n.scrollable {
            ClipCtx::Scrolling {
                rect: computed,
                scroll_axis: n.axis,
            }
        } else {
            ClipCtx::Static(computed)
        }
    } else {
        nearest_clip
    };

    for (child_idx, c) in n.children.iter().enumerate() {
        let from_user_child = is_from_user(c.source);
        let child_blame = if from_user_child {
            Some(c.source)
        } else {
            self_blame
        };

        let c_rect = ui_state.rect(&c.computed_id);
        if !suppress_overflow
            && !rect_contains(computed, c_rect, 0.5)
            && let Some(blame) = child_blame
        {
            let dx_left = (computed.x - c_rect.x).max(0.0);
            let dx_right = (c_rect.right() - computed.right()).max(0.0);
            let dy_top = (computed.y - c_rect.y).max(0.0);
            let dy_bottom = (c_rect.bottom() - computed.bottom()).max(0.0);
            r.findings.push(Finding {
                kind: FindingKind::Overflow,
                node_id: c.computed_id.clone(),
                source: blame,
                message: format!(
                    "child overflows parent {parent_id} by L={dx_left:.0} R={dx_right:.0} T={dy_top:.0} B={dy_bottom:.0}",
                    parent_id = n.computed_id,
                ),
            });
        }

        // Focus-ring obscurement: only meaningful for focusable nodes
        // that reserve a paint_overflow band (the band is where the
        // ring renders in the stock-shader path).
        if from_user_child
            && c.focusable
            && has_paint_overflow(c.paint_overflow)
            && let Some(blame) = child_blame
        {
            check_focus_ring_obscured(
                c,
                c_rect,
                child_clip,
                &n.children[child_idx + 1..],
                ui_state,
                r,
                blame,
            );
        }

        walk(c, Some(&n.kind), child_blame, child_clip, ui_state, r, seen);
    }
}

fn has_paint_overflow(s: Sides) -> bool {
    s.left > 0.0 || s.right > 0.0 || s.top > 0.0 || s.bottom > 0.0
}

fn check_focus_ring_obscured(
    n: &El,
    n_rect: Rect,
    nearest_clip: ClipCtx,
    later_siblings: &[El],
    ui_state: &UiState,
    r: &mut LintReport,
    blame: Source,
) {
    let band = n_rect.outset(n.paint_overflow);

    // 1. Clipped by ancestor scissor. For scrollable clips, only the
    // cross axis is checked — the scroll axis can bring partially
    // clipped rows into view on focus.
    let (clip_rect, check_horiz, check_vert) = match nearest_clip {
        ClipCtx::None => (None, false, false),
        ClipCtx::Static(rect) => (Some(rect), true, true),
        ClipCtx::Scrolling { rect, scroll_axis } => match scroll_axis {
            Axis::Column => (Some(rect), true, false),
            Axis::Row => (Some(rect), false, true),
            Axis::Overlay => (Some(rect), true, true),
        },
    };
    if let Some(clip) = clip_rect {
        let dx_left = if check_horiz {
            (clip.x - band.x).max(0.0)
        } else {
            0.0
        };
        let dx_right = if check_horiz {
            (band.right() - clip.right()).max(0.0)
        } else {
            0.0
        };
        let dy_top = if check_vert {
            (clip.y - band.y).max(0.0)
        } else {
            0.0
        };
        let dy_bottom = if check_vert {
            (band.bottom() - clip.bottom()).max(0.0)
        } else {
            0.0
        };
        if dx_left + dx_right + dy_top + dy_bottom > 0.5 {
            r.findings.push(Finding {
                kind: FindingKind::FocusRingObscured,
                node_id: n.computed_id.clone(),
                source: blame,
                message: format!(
                    "focus ring band clipped by ancestor scissor (L={dx_left:.0} R={dx_right:.0} T={dy_top:.0} B={dy_bottom:.0}) — give a clipping ancestor padding ≥ tokens::RING_WIDTH on the clipped side",
                ),
            });
        }
    }

    // 2. Occluded by a later-painted sibling whose rect overlaps the
    // bleed band on a side where the focusable reserves overflow.
    // Skip overlay parents (siblings are intentionally stacked).
    for sib in later_siblings {
        let sib_rect = ui_state.rect(&sib.computed_id);
        if let Some(side) = bleed_occlusion(n_rect, n.paint_overflow, sib_rect)
            && paints_pixels(sib)
        {
            r.findings.push(Finding {
                kind: FindingKind::FocusRingObscured,
                node_id: n.computed_id.clone(),
                source: blame,
                message: format!(
                    "focus ring band occluded on the {side} edge by later-painted sibling {sib_id} — increase gap to ≥ tokens::RING_WIDTH or restructure so the neighbor doesn't sit on the edge",
                    sib_id = sib.computed_id,
                ),
            });
            // First occluder is enough — don't double-report.
            break;
        }
    }
}

/// True if `n` paints visible pixels (so it can occlude a sibling's
/// focus ring band). Pure structural columns/rows with no fill/
/// stroke/text/image/shadow don't occlude.
fn paints_pixels(n: &El) -> bool {
    n.fill.is_some()
        || n.stroke.is_some()
        || n.image.is_some()
        || n.icon.is_some()
        || n.shadow > 0.0
        || n.text.is_some()
        || !matches!(n.surface_role, SurfaceRole::None)
}

/// Whichever side of `n_rect`'s `paint_overflow` band `sib_rect`
/// intersects (above the EPS adjacency threshold). `EPS` keeps a
/// sibling whose edge merely touches the focusable's edge (gap = 0)
/// from triggering — touching is adjacency, not yet occlusion.
fn bleed_occlusion(n_rect: Rect, overflow: Sides, sib_rect: Rect) -> Option<&'static str> {
    const EPS: f32 = 0.5;
    let bands: [(&'static str, Rect); 4] = [
        (
            "top",
            Rect::new(n_rect.x, n_rect.y - overflow.top, n_rect.w, overflow.top),
        ),
        (
            "bottom",
            Rect::new(n_rect.x, n_rect.bottom(), n_rect.w, overflow.bottom),
        ),
        (
            "left",
            Rect::new(n_rect.x - overflow.left, n_rect.y, overflow.left, n_rect.h),
        ),
        (
            "right",
            Rect::new(n_rect.right(), n_rect.y, overflow.right, n_rect.h),
        ),
    ];
    for (side, band) in bands {
        if band.w <= 0.0 || band.h <= 0.0 {
            continue;
        }
        let iw = band.right().min(sib_rect.right()) - band.x.max(sib_rect.x);
        let ih = band.bottom().min(sib_rect.bottom()) - band.y.max(sib_rect.y);
        if iw > EPS && ih > EPS {
            return Some(side);
        }
    }
    None
}

fn lint_row_alignment(
    n: &El,
    computed: Rect,
    ui_state: &UiState,
    r: &mut LintReport,
    blame: Source,
) {
    if !matches!(n.axis, Axis::Row) || !matches!(n.align, Align::Stretch) || n.children.len() < 2 {
        return;
    }
    if !n.children.iter().any(is_text_like_child) {
        return;
    }

    let inner = computed.inset(n.padding);
    if inner.h <= 0.0 {
        return;
    }

    for child in &n.children {
        if !is_fixed_visual_child(child) {
            continue;
        }
        let child_rect = ui_state.rect(&child.computed_id);
        let top_pinned = (child_rect.y - inner.y).abs() <= 0.5;
        let visibly_short = child_rect.h + 2.0 < inner.h;
        if top_pinned && visibly_short {
            r.findings.push(Finding {
                kind: FindingKind::Alignment,
                node_id: n.computed_id.clone(),
                source: blame,
                message: "row has a fixed-size visual child pinned to the top beside text; add .align(Align::Center) to vertically center row content"
                    .to_string(),
            });
            return;
        }
    }
}

fn lint_overlay_alignment(
    n: &El,
    computed: Rect,
    ui_state: &UiState,
    r: &mut LintReport,
    blame: Source,
) {
    if !matches!(n.axis, Axis::Overlay)
        || n.children.is_empty()
        || !matches!(n.align, Align::Start | Align::Stretch)
        || !matches!(n.justify, Justify::Start | Justify::SpaceBetween)
        || !has_visible_surface(n)
    {
        return;
    }

    let inner = computed.inset(n.padding);
    if inner.w <= 0.0 || inner.h <= 0.0 {
        return;
    }

    for child in &n.children {
        if !is_fixed_visual_child(child) {
            continue;
        }
        let child_rect = ui_state.rect(&child.computed_id);
        let left_pinned = (child_rect.x - inner.x).abs() <= 0.5;
        let top_pinned = (child_rect.y - inner.y).abs() <= 0.5;
        let visibly_narrow = child_rect.w + 2.0 < inner.w;
        let visibly_short = child_rect.h + 2.0 < inner.h;
        if left_pinned && top_pinned && visibly_narrow && visibly_short {
            r.findings.push(Finding {
                kind: FindingKind::Alignment,
                node_id: n.computed_id.clone(),
                source: blame,
                message: "overlay has a smaller fixed-size visual child pinned to the top-left; add .align(Align::Center).justify(Justify::Center) to center overlay content"
                    .to_string(),
            });
            return;
        }
    }
}

fn lint_row_visual_text_spacing(n: &El, ui_state: &UiState, r: &mut LintReport, blame: Source) {
    if !matches!(n.axis, Axis::Row) || n.children.len() < 2 {
        return;
    }

    for pair in n.children.windows(2) {
        let [visual, text] = pair else {
            continue;
        };
        if !is_visual_cluster_child(visual) || !is_text_like_child(text) {
            continue;
        }

        let visual_rect = ui_state.rect(&visual.computed_id);
        let text_rect = ui_state.rect(&text.computed_id);
        let gap = text_rect.x - visual_rect.right();
        if gap < 4.0 {
            r.findings.push(Finding {
                kind: FindingKind::Spacing,
                node_id: n.computed_id.clone(),
                source: blame,
                message: format!(
                    "row places text {:.0}px after an icon/control slot; add .gap(tokens::SPACE_2) or use a stock menu/list row",
                    gap.max(0.0)
                ),
            });
            return;
        }
    }
}

fn is_text_like_child(c: &El) -> bool {
    c.text.is_some()
        || c.children
            .iter()
            .any(|child| child.text.is_some() || matches!(child.kind, Kind::Text | Kind::Heading))
}

fn has_visible_surface(n: &El) -> bool {
    n.fill.is_some() || n.stroke.is_some()
}

fn is_fixed_visual_child(c: &El) -> bool {
    let fixed_height = matches!(c.height, Size::Fixed(_));
    fixed_height
        && (c.icon.is_some()
            || matches!(c.kind, Kind::Badge)
            || matches!(
                c.metrics_role,
                Some(
                    MetricsRole::Button
                        | MetricsRole::IconButton
                        | MetricsRole::Input
                        | MetricsRole::Badge
                        | MetricsRole::TabTrigger
                        | MetricsRole::ChoiceControl
                        | MetricsRole::Slider
                        | MetricsRole::Progress
                )
            ))
}

fn is_visual_cluster_child(c: &El) -> bool {
    let fixed_box = matches!(c.width, Size::Fixed(_)) && matches!(c.height, Size::Fixed(_));
    fixed_box
        && (c.icon.is_some()
            || matches!(c.kind, Kind::Badge)
            || matches!(
                c.metrics_role,
                Some(MetricsRole::IconButton | MetricsRole::Badge | MetricsRole::ChoiceControl)
            )
            || (has_visible_surface(c) && c.children.iter().any(is_fixed_visual_child)))
}

fn rect_contains(parent: Rect, child: Rect, tol: f32) -> bool {
    child.x >= parent.x - tol
        && child.y >= parent.y - tol
        && child.right() <= parent.right() + tol
        && child.bottom() <= parent.bottom() + tol
}

fn short_path(p: &str) -> String {
    let parts: Vec<&str> = p.split(['/', '\\']).collect();
    if parts.len() >= 2 {
        format!("{}/{}", parts[parts.len() - 2], parts[parts.len() - 1])
    } else {
        p.to_string()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn lint_one(mut root: El) -> LintReport {
        let mut ui_state = UiState::new();
        layout::layout(&mut root, &mut ui_state, Rect::new(0.0, 0.0, 160.0, 48.0));
        lint(&root, &ui_state)
    }

    #[test]
    fn clipped_nowrap_text_reports_text_overflow() {
        let root = crate::text("A very long dashboard label")
            .width(Size::Fixed(42.0))
            .height(Size::Fixed(20.0));

        let report = lint_one(root);

        assert!(
            report
                .findings
                .iter()
                .any(|finding| finding.kind == FindingKind::TextOverflow),
            "{}",
            report.text()
        );
    }

    #[test]
    fn ellipsis_nowrap_text_satisfies_horizontal_overflow_policy() {
        let root = crate::text("A very long dashboard label")
            .ellipsis()
            .width(Size::Fixed(42.0))
            .height(Size::Fixed(20.0));

        let report = lint_one(root);

        assert!(
            !report
                .findings
                .iter()
                .any(|finding| finding.kind == FindingKind::TextOverflow),
            "{}",
            report.text()
        );
    }

    #[test]
    fn padding_aware_text_overflow_fires_when_text_spills_past_padded_region() {
        // Box is wide enough for the bare text (66 ≤ 80) but padding
        // eats so much that the text spills past the padded content
        // area (66 > 80 - 40). Centered text in this state visually
        // reads as off-center — the lint must flag it even though the
        // text would technically fit inside the outer rect.
        //
        // Wrap in a row so the inner Fixed(80) is honored; the layout
        // pass forces the root rect to the viewport regardless of its
        // own size, so a single-node test would mis-measure.
        let leaf = crate::text("dashboard")
            .width(Size::Fixed(80.0))
            .height(Size::Fixed(28.0))
            .padding(Sides::xy(20.0, 0.0));
        let root = crate::row([leaf]);

        let report = lint_one(root);

        assert!(
            report
                .findings
                .iter()
                .any(|finding| finding.kind == FindingKind::TextOverflow),
            "{}",
            report.text()
        );
    }

    #[test]
    fn stretch_row_with_top_pinned_icon_and_text_suggests_center_alignment() {
        let root = crate::row([
            crate::icon("settings").icon_size(crate::tokens::ICON_SM),
            crate::text("Settings").width(Size::Fill(1.0)),
        ])
        .height(Size::Fixed(36.0));

        let report = lint_one(root);

        assert!(
            report
                .findings
                .iter()
                .any(|finding| finding.kind == FindingKind::Alignment
                    && finding.message.contains(".align(Align::Center)")),
            "{}",
            report.text()
        );
    }

    #[test]
    fn centered_row_with_icon_and_text_satisfies_alignment_policy() {
        let root = crate::row([
            crate::icon("settings").icon_size(crate::tokens::ICON_SM),
            crate::text("Settings").width(Size::Fill(1.0)),
        ])
        .height(Size::Fixed(36.0))
        .align(Align::Center);

        let report = lint_one(root);

        assert!(
            !report
                .findings
                .iter()
                .any(|finding| finding.kind == FindingKind::Alignment),
            "{}",
            report.text()
        );
    }

    #[test]
    fn row_with_icon_slot_touching_text_reports_spacing() {
        let icon_slot = crate::stack([crate::icon("settings").icon_size(crate::tokens::ICON_XS)])
            .align(Align::Center)
            .justify(Justify::Center)
            .fill(crate::tokens::MUTED)
            .width(Size::Fixed(26.0))
            .height(Size::Fixed(26.0));
        let root = crate::row([icon_slot, crate::text("Settings").width(Size::Fill(1.0))])
            .height(Size::Fixed(32.0))
            .align(Align::Center);

        let report = lint_one(root);

        assert!(
            report
                .findings
                .iter()
                .any(|finding| finding.kind == FindingKind::Spacing
                    && finding.message.contains(".gap(tokens::SPACE_2)")),
            "{}",
            report.text()
        );
    }

    #[test]
    fn row_with_icon_slot_and_text_gap_satisfies_spacing_policy() {
        let icon_slot = crate::stack([crate::icon("settings").icon_size(crate::tokens::ICON_XS)])
            .align(Align::Center)
            .justify(Justify::Center)
            .fill(crate::tokens::MUTED)
            .width(Size::Fixed(26.0))
            .height(Size::Fixed(26.0));
        let root = crate::row([icon_slot, crate::text("Settings").width(Size::Fill(1.0))])
            .height(Size::Fixed(32.0))
            .align(Align::Center)
            .gap(crate::tokens::SPACE_2);

        let report = lint_one(root);

        assert!(
            !report
                .findings
                .iter()
                .any(|finding| finding.kind == FindingKind::Spacing),
            "{}",
            report.text()
        );
    }

    #[test]
    fn overlay_with_top_left_pinned_icon_suggests_center_alignment() {
        let icon_slot = crate::stack([crate::icon("settings").icon_size(crate::tokens::ICON_XS)])
            .fill(crate::tokens::MUTED)
            .width(Size::Fixed(26.0))
            .height(Size::Fixed(26.0));
        let root = crate::column([icon_slot]);

        let report = lint_one(root);

        assert!(
            report
                .findings
                .iter()
                .any(|finding| finding.kind == FindingKind::Alignment
                    && finding.message.contains(".justify(Justify::Center)")),
            "{}",
            report.text()
        );
    }

    #[test]
    fn centered_overlay_icon_satisfies_alignment_policy() {
        let icon_slot = crate::stack([crate::icon("settings").icon_size(crate::tokens::ICON_XS)])
            .align(Align::Center)
            .justify(Justify::Center)
            .fill(crate::tokens::MUTED)
            .width(Size::Fixed(26.0))
            .height(Size::Fixed(26.0));
        let root = crate::column([icon_slot]);

        let report = lint_one(root);

        assert!(
            !report
                .findings
                .iter()
                .any(|finding| finding.kind == FindingKind::Alignment),
            "{}",
            report.text()
        );
    }

    #[test]
    fn overflow_findings_attribute_to_nearest_user_source_ancestor() {
        // Closure-built-widget shape: an Element constructed inside an
        // aetna widget closure carries `from_library: true`. Its
        // overflow finding should attribute to the nearest non-library
        // ancestor's source.
        let user_source = Source {
            file: "src/screen.rs",
            line: 42,
            from_library: false,
        };
        let widget_source = Source {
            file: "src/widgets/tabs.rs",
            line: 200,
            from_library: true,
        };

        let mut leaf = crate::text("A very long dashboard label")
            .width(Size::Fixed(40.0))
            .height(Size::Fixed(20.0));
        leaf.source = widget_source;

        let mut root = crate::row([leaf])
            .width(Size::Fixed(160.0))
            .height(Size::Fixed(48.0));
        root.source = user_source;

        let mut ui_state = UiState::new();
        layout::layout(&mut root, &mut ui_state, Rect::new(0.0, 0.0, 160.0, 48.0));
        let report = lint(&root, &ui_state);

        let text_overflow = report
            .findings
            .iter()
            .find(|f| f.kind == FindingKind::TextOverflow)
            .unwrap_or_else(|| panic!("expected TextOverflow finding\n{}", report.text()));
        assert_eq!(text_overflow.source.file, user_source.file);
        assert_eq!(text_overflow.source.line, user_source.line);
    }

    #[test]
    fn overflow_finding_self_attributes_when_node_is_already_user_source() {
        let mut node = crate::text("A very long dashboard label")
            .width(Size::Fixed(40.0))
            .height(Size::Fixed(20.0));
        let user_source = Source {
            file: "src/screen.rs",
            line: 99,
            from_library: false,
        };
        node.source = user_source;

        let mut ui_state = UiState::new();
        layout::layout(&mut node, &mut ui_state, Rect::new(0.0, 0.0, 160.0, 48.0));
        let report = lint(&node, &ui_state);

        let text_overflow = report
            .findings
            .iter()
            .find(|f| f.kind == FindingKind::TextOverflow)
            .unwrap_or_else(|| panic!("expected TextOverflow finding\n{}", report.text()));
        assert_eq!(text_overflow.source.line, user_source.line);
    }

    #[test]
    fn overflow_lint_fires_for_external_app_paths_issue_13() {
        // Regression for #13: an external app's `Location::caller()`
        // file paths look like `src/sidebar.rs` (relative to its own
        // manifest), not `crates/<name>/src/...`. The old marker-
        // substring filter silently dropped every overflow finding for
        // these. With `from_library: false` (the user-code default),
        // the overflow must fire.
        let user_source = Source {
            file: "src/sidebar.rs",
            line: 17,
            from_library: false,
        };
        let mut child = crate::column(Vec::<El>::new())
            .width(Size::Fixed(32.0))
            .height(Size::Fixed(32.0));
        child.source = user_source;

        let mut row = crate::row([child])
            .width(Size::Fixed(256.0))
            .height(Size::Fixed(28.0));
        row.source = user_source;

        let mut ui_state = UiState::new();
        layout::layout(&mut row, &mut ui_state, Rect::new(0.0, 0.0, 256.0, 28.0));
        let report = lint(&row, &ui_state);

        assert!(
            report
                .findings
                .iter()
                .any(|f| f.kind == FindingKind::Overflow),
            "expected an Overflow finding for the 32px child in a 28px row\n{}",
            report.text()
        );
    }

    #[test]
    fn overflow_finding_suppressed_when_no_user_ancestor_exists() {
        // Pure-library tree: every node carries `from_library: true`,
        // so there's no user code to blame and the finding is dropped.
        let widget_source = Source {
            file: "src/widgets/tabs.rs",
            line: 200,
            from_library: true,
        };
        let mut leaf = crate::text("A very long dashboard label")
            .width(Size::Fixed(40.0))
            .height(Size::Fixed(20.0));
        leaf.source = widget_source;

        let mut wrapper = crate::row([leaf])
            .width(Size::Fixed(160.0))
            .height(Size::Fixed(48.0));
        wrapper.source = widget_source;

        let mut ui_state = UiState::new();
        layout::layout(
            &mut wrapper,
            &mut ui_state,
            Rect::new(0.0, 0.0, 160.0, 48.0),
        );
        let report = lint(&wrapper, &ui_state);

        assert!(
            !report
                .findings
                .iter()
                .any(|f| f.kind == FindingKind::TextOverflow || f.kind == FindingKind::Overflow),
            "{}",
            report.text()
        );
    }

    #[test]
    fn panel_role_without_fill_reports_missing_surface_fill() {
        let root = crate::column([crate::text("body")])
            .surface_role(SurfaceRole::Panel)
            .width(Size::Fixed(120.0))
            .height(Size::Fixed(40.0));

        let report = lint_one(root);

        assert!(
            report
                .findings
                .iter()
                .any(|f| f.kind == FindingKind::MissingSurfaceFill),
            "{}",
            report.text()
        );
    }

    #[test]
    fn panel_role_with_fill_satisfies_surface_policy() {
        let root = crate::column([crate::text("body")])
            .surface_role(SurfaceRole::Panel)
            .fill(crate::tokens::CARD)
            .width(Size::Fixed(120.0))
            .height(Size::Fixed(40.0));

        let report = lint_one(root);

        assert!(
            !report
                .findings
                .iter()
                .any(|f| f.kind == FindingKind::MissingSurfaceFill),
            "{}",
            report.text()
        );
    }

    #[test]
    fn card_widget_satisfies_surface_policy() {
        let root = crate::widgets::card::card([crate::text("body")])
            .width(Size::Fixed(120.0))
            .height(Size::Fixed(40.0));

        let report = lint_one(root);

        assert!(
            !report
                .findings
                .iter()
                .any(|f| f.kind == FindingKind::MissingSurfaceFill),
            "{}",
            report.text()
        );
    }

    #[test]
    fn handrolled_card_recipe_reports_reinvented_widget() {
        // column().fill(CARD).stroke(BORDER).radius(>0) is the canonical
        // hand-rolled card silhouette.
        let root = crate::column([crate::text("body")])
            .fill(crate::tokens::CARD)
            .stroke(crate::tokens::BORDER)
            .radius(crate::tokens::RADIUS_LG)
            .width(Size::Fixed(160.0))
            .height(Size::Fixed(48.0));

        let report = lint_one(root);

        assert!(
            report
                .findings
                .iter()
                .any(|f| f.kind == FindingKind::ReinventedWidget && f.message.contains("card(")),
            "{}",
            report.text()
        );
    }

    #[test]
    fn real_card_widget_does_not_report_reinvented_widget() {
        // card() returns Kind::Card, so the smell signature (which
        // requires Kind::Group) excludes it by construction.
        let root = crate::widgets::card::card([crate::text("body")])
            .width(Size::Fixed(160.0))
            .height(Size::Fixed(48.0));

        let report = lint_one(root);

        assert!(
            !report
                .findings
                .iter()
                .any(|f| f.kind == FindingKind::ReinventedWidget),
            "{}",
            report.text()
        );
    }

    #[test]
    fn handrolled_sidebar_recipe_reports_reinvented_widget() {
        // column().fill(CARD).stroke(BORDER).width(SIDEBAR_WIDTH) without
        // surface_role(Panel) is the volumetric_ui_v2 sidebar pattern.
        let root = crate::column([crate::text("nav")])
            .fill(crate::tokens::CARD)
            .stroke(crate::tokens::BORDER)
            .width(Size::Fixed(crate::tokens::SIDEBAR_WIDTH))
            .height(Size::Fill(1.0));

        let report = lint_one(root);

        assert!(
            report
                .findings
                .iter()
                .any(|f| f.kind == FindingKind::ReinventedWidget && f.message.contains("sidebar(")),
            "{}",
            report.text()
        );
    }

    #[test]
    fn real_sidebar_widget_does_not_report_reinvented_widget() {
        // sidebar() sets surface_role(Panel), which excludes it from the
        // smell signature even though its fill+stroke+width match.
        let root = crate::widgets::sidebar::sidebar([crate::text("nav")]);

        let report = lint_one(root);

        assert!(
            !report
                .findings
                .iter()
                .any(|f| f.kind == FindingKind::ReinventedWidget),
            "{}",
            report.text()
        );
    }

    #[test]
    fn empty_visual_swatch_does_not_report_reinvented_widget() {
        // A childless Group styled with CARD/BORDER is a color sample,
        // not a card-mimic. Card-mimics always wrap content; pure
        // decorative boxes shouldn't trip the lint.
        let root = crate::column(Vec::<El>::new())
            .fill(crate::tokens::CARD)
            .stroke(crate::tokens::BORDER)
            .radius(crate::tokens::RADIUS_SM)
            .width(Size::Fixed(42.0))
            .height(Size::Fixed(34.0));

        let report = lint_one(root);

        assert!(
            !report
                .findings
                .iter()
                .any(|f| f.kind == FindingKind::ReinventedWidget),
            "{}",
            report.text()
        );
    }

    #[test]
    fn plain_column_does_not_report_reinvented_widget() {
        // A normal column with no surface decoration is fine.
        let root = crate::column([crate::text("a"), crate::text("b")])
            .gap(crate::tokens::SPACE_2)
            .width(Size::Fixed(120.0))
            .height(Size::Fixed(40.0));

        let report = lint_one(root);

        assert!(
            !report
                .findings
                .iter()
                .any(|f| f.kind == FindingKind::ReinventedWidget),
            "{}",
            report.text()
        );
    }

    #[test]
    fn fill_providing_roles_do_not_require_explicit_fill() {
        // Sunken paints palette MUTED.darken(0.08) by default — no
        // explicit fill needed. Same shape applies to Selected /
        // Current / Input / Danger; covering Sunken here as a
        // representative.
        let root = crate::column([crate::text("body")])
            .surface_role(SurfaceRole::Sunken)
            .width(Size::Fixed(120.0))
            .height(Size::Fixed(40.0));

        let report = lint_one(root);

        assert!(
            !report
                .findings
                .iter()
                .any(|f| f.kind == FindingKind::MissingSurfaceFill),
            "{}",
            report.text()
        );
    }

    #[test]
    fn focus_ring_lint_fires_when_input_clipped_on_scroll_cross_axis() {
        // The original bug: a focusable text input flush at the left
        // edge of a vertical-scroll viewport gets its ring scissored.
        let selection = crate::selection::Selection::default();
        let mut root = crate::tree::scroll([crate::tree::column([
            crate::widgets::text_input::text_input("", &selection, "field"),
        ])])
        .width(Size::Fixed(300.0))
        .height(Size::Fixed(120.0));
        let mut state = UiState::new();
        layout::layout(&mut root, &mut state, Rect::new(0.0, 0.0, 300.0, 120.0));
        let report = lint(&root, &state);

        assert!(
            report.findings.iter().any(|f| {
                f.kind == FindingKind::FocusRingObscured
                    && f.message.contains("clipped")
                    && (f.message.contains("L=2") || f.message.contains("R=2"))
            }),
            "expected a FocusRingObscured clipping finding (L=2 or R=2)\n{}",
            report.text()
        );
    }

    #[test]
    fn focus_ring_lint_silenced_when_scroll_supplies_horizontal_slack() {
        // Same shape, but the scroll's content is wrapped so the input
        // sits inset by RING_WIDTH on each horizontal edge. No finding.
        let selection = crate::selection::Selection::default();
        let mut root =
            crate::tree::scroll(
                [crate::tree::column([crate::widgets::text_input::text_input(
                    "", &selection, "field",
                )])
                .padding(Sides::xy(crate::tokens::RING_WIDTH, 0.0))],
            )
            .width(Size::Fixed(300.0))
            .height(Size::Fixed(120.0));
        let mut state = UiState::new();
        layout::layout(&mut root, &mut state, Rect::new(0.0, 0.0, 300.0, 120.0));
        let report = lint(&root, &state);

        assert!(
            !report
                .findings
                .iter()
                .any(|f| f.kind == FindingKind::FocusRingObscured),
            "{}",
            report.text()
        );
    }

    #[test]
    fn focus_ring_lint_skips_clipping_on_scroll_axis() {
        // Tall content that runs past a vertical scroll's bottom edge
        // is fine — auto-scroll-on-focus brings the focused row into
        // view. The lint must not fire on the scroll axis.
        let selection = crate::selection::Selection::default();
        let mut root = crate::tree::scroll([crate::tree::column([
            // Big top filler so the input lands well below the viewport.
            crate::tree::column(Vec::<El>::new())
                .width(Size::Fill(1.0))
                .height(Size::Fixed(200.0)),
            crate::widgets::text_input::text_input("", &selection, "field"),
        ])
        .padding(Sides::xy(crate::tokens::RING_WIDTH, 0.0))])
        .width(Size::Fixed(300.0))
        .height(Size::Fixed(120.0));
        let mut state = UiState::new();
        layout::layout(&mut root, &mut state, Rect::new(0.0, 0.0, 300.0, 120.0));
        let report = lint(&root, &state);

        assert!(
            !report
                .findings
                .iter()
                .any(|f| f.kind == FindingKind::FocusRingObscured),
            "expected no FocusRingObscured finding for a row clipped on the scroll axis\n{}",
            report.text()
        );
    }

    #[test]
    fn focus_ring_lint_fires_on_static_clip_in_any_direction() {
        // A non-scrolling clipping container (an ordinary clipped card)
        // doesn't auto-reveal anything, so all four sides count.
        let selection = crate::selection::Selection::default();
        let mut root = crate::tree::column([crate::widgets::text_input::text_input(
            "", &selection, "field",
        )])
        .clip()
        .width(Size::Fixed(300.0))
        .height(Size::Fixed(120.0));
        let mut state = UiState::new();
        layout::layout(&mut root, &mut state, Rect::new(0.0, 0.0, 300.0, 120.0));
        let report = lint(&root, &state);

        assert!(
            report.findings.iter().any(|f| {
                f.kind == FindingKind::FocusRingObscured && f.message.contains("clipped")
            }),
            "expected a static-clip FocusRingObscured finding\n{}",
            report.text()
        );
    }

    #[test]
    fn focus_ring_lint_fires_on_painted_later_sibling_overlap() {
        // Focusable on the left, a card-like sibling immediately to
        // the right at gap=0. The card paints fill+stroke, so the
        // focusable's right ring band gets occluded.
        let selection = crate::selection::Selection::default();
        let mut root = crate::tree::row([
            crate::widgets::text_input::text_input("", &selection, "field"),
            crate::tree::column([crate::text("neighbor")])
                .fill(crate::tokens::CARD)
                .stroke(crate::tokens::BORDER)
                .width(Size::Fixed(80.0))
                .height(Size::Fixed(32.0)),
        ])
        .gap(0.0)
        .width(Size::Fixed(400.0))
        .height(Size::Fixed(32.0));
        let mut state = UiState::new();
        layout::layout(&mut root, &mut state, Rect::new(0.0, 0.0, 400.0, 60.0));
        let report = lint(&root, &state);

        assert!(
            report.findings.iter().any(|f| {
                f.kind == FindingKind::FocusRingObscured
                    && f.message.contains("occluded")
                    && f.message.contains("right")
            }),
            "expected an occlusion finding on the right edge\n{}",
            report.text()
        );
    }

    #[test]
    fn focus_ring_lint_ignores_unpainted_structural_sibling() {
        // A structural column with no fill/stroke/text shouldn't be
        // counted as an occluder — it draws no pixels.
        let selection = crate::selection::Selection::default();
        let mut root = crate::tree::row([
            crate::widgets::text_input::text_input("", &selection, "field"),
            crate::tree::column(Vec::<El>::new())
                .width(Size::Fixed(80.0))
                .height(Size::Fixed(32.0)),
        ])
        .gap(0.0)
        .width(Size::Fixed(400.0))
        .height(Size::Fixed(32.0));
        let mut state = UiState::new();
        layout::layout(&mut root, &mut state, Rect::new(0.0, 0.0, 400.0, 60.0));
        let report = lint(&root, &state);

        assert!(
            !report
                .findings
                .iter()
                .any(|f| f.kind == FindingKind::FocusRingObscured),
            "{}",
            report.text()
        );
    }

    #[test]
    fn focus_ring_lint_is_quiet_inside_form_after_padding_fix() {
        // Regression: with form()'s default RING_WIDTH horizontal
        // padding, a text input flush inside a scroll/form chain
        // doesn't trip the clipping lint.
        let selection = crate::selection::Selection::default();
        let mut root = crate::tree::scroll([crate::widgets::form::form([
            crate::widgets::form::form_item([crate::widgets::form::form_control(
                crate::widgets::text_input::text_input("", &selection, "field"),
            )]),
        ])])
        .width(Size::Fixed(300.0))
        .height(Size::Fixed(120.0));
        let mut state = UiState::new();
        layout::layout(&mut root, &mut state, Rect::new(0.0, 0.0, 300.0, 120.0));
        let report = lint(&root, &state);

        assert!(
            !report
                .findings
                .iter()
                .any(|f| f.kind == FindingKind::FocusRingObscured),
            "{}",
            report.text()
        );
    }
}