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
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
//! TUI rasteriser for [`crate::MultiSectionView`].
//!
//! This function asks the primitive for a [`crate::MultiSectionViewLayout`]
//! using TUI-native metrics (1 cell per header, 1 cell per scrollbar, 1 cell
//! per divider) and paints the resolved positions verbatim. Body content is
//! dispatched to the existing per-primitive rasterisers (`draw_tree`,
//! `draw_list`, etc.) using the body bounds returned by the layout.
//!
//! Vertical-only in v1; horizontal sections fall through to a no-op until the
//! horizontal rasteriser ships.
use ratatui::buffer::Buffer;
use ratatui::layout::Rect as TuiRect;
use super::{
draw_form, draw_list, draw_message_list, draw_tree, qc, ratatui_color, set_cell, set_cell_wide,
};
use crate::event::Rect as QRect;
use crate::primitives::multi_section_view::{
Axis, EmptyBody, MsvLayoutMetrics, MultiSectionView, MultiSectionViewLayout, SectionAux,
SectionBody, SectionHeader, SectionMeasure,
};
use crate::text_util::char_cell_width;
use crate::theme::Theme;
use crate::types::StyledText;
/// Draw a [`MultiSectionView`] into `area` on `buf`. Body content is
/// dispatched to the appropriate body-primitive rasteriser using the
/// layout's body bounds.
///
/// `nerd_fonts_enabled` is forwarded to body painters that consume it
/// (currently `draw_tree` and `draw_list`).
pub fn draw_multi_section_view(
buf: &mut Buffer,
area: TuiRect,
view: &MultiSectionView,
theme: &Theme,
nerd_fonts_enabled: bool,
) {
if area.width == 0 || area.height == 0 || view.axis == Axis::Horizontal {
// Horizontal axis is not yet rasterised. Paint nothing
// rather than draw incorrect chrome — the host gets a visibly
// empty region and surfaces the gap in their tests.
return;
}
let layout = tui_msv_layout(view, area);
let panel_bg = ratatui_color(theme.background);
let viewport_top = layout.bounds.y;
let viewport_bottom = layout.bounds.y + layout.bounds.height;
for s_layout in &layout.sections {
let section = &view.sections[s_layout.section_idx];
// Header — clipped against viewport.
if let Some(clipped) =
clip_to_viewport(s_layout.header_bounds, viewport_top, viewport_bottom)
{
paint_header(buf, clipped, §ion.header, section.collapsed, theme);
}
if !s_layout.collapsed {
if let Some(aux_b) = s_layout.aux_bounds {
if let Some(clipped) = clip_to_viewport(aux_b, viewport_top, viewport_bottom) {
if let Some(aux) = §ion.aux {
paint_aux(buf, clipped, aux, theme);
}
}
}
// Body fill — only clear the visible portion.
if let Some(clipped_body) =
clip_to_viewport(s_layout.body_bounds, viewport_top, viewport_bottom)
{
fill_rect(buf, clipped_body, ' ', panel_bg, panel_bg);
paint_body(
buf,
s_layout.body_bounds,
clipped_body,
§ion.body,
theme,
nerd_fonts_enabled,
);
}
if let Some(sb_b) = s_layout.scrollbar_bounds {
if let Some(clipped) = clip_to_viewport(sb_b, viewport_top, viewport_bottom) {
let clipped_thumb = s_layout
.thumb_bounds
.and_then(|t| clip_to_viewport(t, viewport_top, viewport_bottom));
paint_scrollbar(buf, clipped, clipped_thumb, theme);
}
}
}
}
// Dividers (horizontal stripes between sections when allow_resize).
if view.allow_resize {
for d in &layout.dividers {
paint_divider(buf, d.bounds, theme);
}
}
// Panel-level scrollbar (WholePanel mode when content overflows).
// Thumb geometry comes straight from `layout.panel_scrollbar_thumb`,
// computed once via `fit_thumb` in `MultiSectionView::layout`.
if let Some(panel_sb) = layout.panel_scrollbar {
paint_panel_scrollbar(buf, panel_sb, layout.panel_scrollbar_thumb, theme);
}
}
/// Compute the layout the TUI rasteriser would produce for `view` in
/// `area`. Hosts and tests call this to drive hit-testing without
/// re-deriving metrics that could drift from paint. `draw_multi_section_view`
/// uses this same helper internally so paint and hit_test consume one
/// layout instance produced by one set of metrics — the source-of-truth
/// contract `MultiSectionView` exists to enforce.
pub fn tui_msv_layout(view: &MultiSectionView, area: TuiRect) -> MultiSectionViewLayout {
// TUI metrics: 1 cell per header row, 1 cell per scrollbar gutter,
// 1 cell per divider (only when allow_resize is true; otherwise we
// omit the strip entirely). `cell_quantum: 1.0` snaps section sizes
// to whole cells inside `MultiSectionView::layout` so paint
// (rounded to integer rows) and hit_test (raw fractional bounds)
// agree by construction.
let metrics = MsvLayoutMetrics {
header_size: 1.0,
divider_size: if view.allow_resize { 1.0 } else { 0.0 },
scrollbar_size: 1.0,
cell_quantum: 1.0,
};
let bounds = QRect::new(
area.x as f32,
area.y as f32,
area.width as f32,
area.height as f32,
);
// Per-section measure: aux is always 1 cell tall in TUI; content
// size is the inner body's natural height in cells.
let measure = |i: usize| -> SectionMeasure {
let s = &view.sections[i];
let aux_size = if s.aux.is_some() { 1.0 } else { 0.0 };
let content_size = body_content_rows(&s.body) as f32;
SectionMeasure {
content_size,
aux_size,
}
};
view.layout(bounds, metrics, measure)
}
// ── Section paint helpers ──────────────────────────────────────────────────
fn paint_header(
buf: &mut Buffer,
bounds: QRect,
header: &SectionHeader,
collapsed: bool,
theme: &Theme,
) {
let bg = ratatui_color(theme.header_bg);
let fg = ratatui_color(theme.header_fg);
let dim = ratatui_color(theme.muted_fg);
fill_rect(buf, bounds, ' ', fg, bg);
let row_y = bounds.y.round() as u16;
if row_y >= buf.area.y + buf.area.height {
return;
}
let left = bounds.x.round() as i32;
let right = (bounds.x + bounds.width).round() as i32;
let mut col = left;
if header.show_chevron {
// ▾ when expanded, ▸ when collapsed. Match the GTK convention
// and VSCode's chevron direction.
let glyph = if collapsed { '▸' } else { '▾' };
if col < right {
set_cell(buf, col as u16, row_y, glyph, fg, bg);
col += 1;
}
if col < right {
set_cell(buf, col as u16, row_y, ' ', fg, bg);
col += 1;
}
}
// Reserve the trailing slot for action buttons (right-to-left).
let mut right_cursor = right;
for action in header.actions.iter().rev() {
let glyph_chars = action.icon.fallback.chars().count() as i32;
let action_w = glyph_chars.max(1) + 1; // glyph + 1 space pad
if right_cursor - action_w < col {
break;
}
let icon_x = right_cursor - action_w + 1; // skip the trailing space
let action_fg = if action.enabled { fg } else { dim };
for (x, ch) in (icon_x..).zip(action.icon.fallback.chars()) {
if x >= right_cursor {
break;
}
set_cell(buf, x as u16, row_y, ch, action_fg, bg);
}
right_cursor -= action_w;
}
// Title in the middle. Truncate if it doesn't fit.
let title_w = (right_cursor - col).max(0);
if title_w > 0 {
let mut x = col;
for span in &header.title.spans {
let span_fg = span.fg.map(qc).unwrap_or(fg);
for ch in span.text.chars() {
if x >= col + title_w {
break;
}
set_cell(buf, x as u16, row_y, ch, span_fg, bg);
x += 1;
}
if x >= col + title_w {
break;
}
}
// Badge after title (if room).
if let Some(badge) = &header.badge {
// Pad single space, then badge.
if x + 1 < col + title_w {
set_cell(buf, x as u16, row_y, ' ', fg, bg);
x += 1;
for span in &badge.spans {
let span_fg = span.fg.map(qc).unwrap_or(dim);
for ch in span.text.chars() {
if x >= col + title_w {
break;
}
set_cell(buf, x as u16, row_y, ch, span_fg, bg);
x += 1;
}
if x >= col + title_w {
break;
}
}
}
}
}
}
fn paint_aux(buf: &mut Buffer, bounds: QRect, aux: &SectionAux, theme: &Theme) {
let bg = ratatui_color(theme.input_bg);
let fg = ratatui_color(theme.foreground);
let dim = ratatui_color(theme.muted_fg);
fill_rect(buf, bounds, ' ', fg, bg);
let row_y = bounds.y.round() as u16;
let left = bounds.x.round() as i32;
let right = (bounds.x + bounds.width).round() as i32;
if row_y >= buf.area.y + buf.area.height || right <= left {
return;
}
match aux {
SectionAux::Input(input) | SectionAux::Search(input) => {
let mut col = left;
// Show the actual text or the placeholder if empty + unfocused.
if input.text.is_empty() && !input.has_focus {
if let Some(ph) = &input.placeholder {
for ch in ph.chars() {
if col >= right {
break;
}
set_cell(buf, col as u16, row_y, ch, dim, bg);
col += 1;
}
}
} else {
for ch in input.text.chars() {
if col >= right {
break;
}
set_cell(buf, col as u16, row_y, ch, fg, bg);
col += 1;
}
// Caret block: invert the cell at caret column when focused.
if input.has_focus {
let caret_col = left + input.caret as i32;
if caret_col >= left && caret_col < right {
let cell = &mut buf[(caret_col as u16, row_y)];
cell.set_bg(fg).set_fg(bg);
}
}
}
}
SectionAux::Toolbar(actions) => {
let mut col = left;
for a in actions {
let action_fg = if a.enabled { fg } else { dim };
for ch in a.icon.fallback.chars() {
if col >= right {
break;
}
set_cell(buf, col as u16, row_y, ch, action_fg, bg);
col += 1;
}
if col < right {
set_cell(buf, col as u16, row_y, ' ', fg, bg);
col += 1;
}
}
}
SectionAux::Custom(_) => {
// Host paints in the bounds we already cleared.
}
}
}
fn paint_body(
buf: &mut Buffer,
full_bounds: QRect,
visible_bounds: QRect,
body: &SectionBody,
theme: &Theme,
nerd_fonts_enabled: bool,
) {
let area = q_to_tui_rect(visible_bounds);
if area.width == 0 || area.height == 0 {
return;
}
// How many TUI rows of the body extend above the viewport — these
// need to be skipped via the inner primitive's scroll_offset so the
// visible area shows the right rows. TUI = 1 cell per row, so the
// skip count equals the clipped-above height.
let clip_above = (full_bounds.y - visible_bounds.y).abs().round() as usize;
match body {
SectionBody::Tree(t) => {
if clip_above == 0 {
draw_tree(buf, area, t, theme, nerd_fonts_enabled);
} else {
let mut t_clone = t.clone();
t_clone.scroll_offset = t.scroll_offset.saturating_add(clip_above);
draw_tree(buf, area, &t_clone, theme, nerd_fonts_enabled);
}
}
SectionBody::List(l) => {
if clip_above == 0 {
draw_list(buf, area, l, theme, nerd_fonts_enabled);
} else {
let mut l_clone = l.clone();
l_clone.scroll_offset = l.scroll_offset.saturating_add(clip_above);
draw_list(buf, area, &l_clone, theme, nerd_fonts_enabled);
}
}
SectionBody::Form(f) => draw_form(buf, area, f, theme),
SectionBody::Chart(c) => {
super::draw_chart(buf, area, c, theme, None, None);
}
SectionBody::MessageList(m) => draw_message_list(buf, area, m, theme.background),
SectionBody::Terminal(_) => {
// No standalone Terminal rasteriser today — host paints.
}
SectionBody::Text(lines) => paint_text_lines(buf, area, lines, theme),
SectionBody::Empty(empty) => paint_empty_body(buf, area, empty, theme),
SectionBody::Custom(_) => {
// Host paints in the bounds.
}
}
}
fn paint_text_lines(buf: &mut Buffer, area: TuiRect, lines: &[StyledText], theme: &Theme) {
let bg = ratatui_color(theme.background);
let fg = ratatui_color(theme.foreground);
for (i, line) in lines.iter().enumerate() {
if i as u16 >= area.height {
break;
}
let y = area.y + i as u16;
let mut x = area.x;
for span in &line.spans {
let span_fg = span.fg.map(qc).unwrap_or(fg);
let span_bg = span.bg.map(qc).unwrap_or(bg);
for ch in span.text.chars() {
if x >= area.x + area.width {
break;
}
let w = char_cell_width(ch);
if w == 2 && x + 1 < area.x + area.width {
set_cell_wide(buf, x, y, ch, span_fg, span_bg);
} else {
set_cell(buf, x, y, ch, span_fg, span_bg);
}
x += w;
}
}
}
}
fn paint_empty_body(buf: &mut Buffer, area: TuiRect, empty: &EmptyBody, theme: &Theme) {
let bg = ratatui_color(theme.background);
let fg = ratatui_color(theme.muted_fg);
let primary_fg = ratatui_color(theme.foreground);
let action_fg = ratatui_color(theme.accent_fg);
if area.height == 0 || area.width == 0 {
return;
}
// Compute total content height: icon (1) + text (1) + hint (1 if any) + action (1 if any).
let mut lines: Vec<(StyledText, ratatui::style::Color)> = Vec::new();
if let Some(icon) = &empty.icon {
lines.push((StyledText::plain(icon.fallback.clone()), primary_fg));
}
lines.push((empty.text.clone(), primary_fg));
if let Some(hint) = &empty.hint {
lines.push((hint.clone(), fg));
}
if let Some(action) = &empty.action {
// Render as `[ tooltip-or-icon ]`.
let label = action
.tooltip
.clone()
.unwrap_or_else(|| action.icon.fallback.clone());
lines.push((StyledText::plain(format!("[ {label} ]")), action_fg));
}
let total = lines.len() as u16;
if total == 0 {
return;
}
let start_y = area.y + area.height.saturating_sub(total) / 2;
for (i, (line, default_fg)) in lines.iter().enumerate() {
let y = start_y + i as u16;
if y >= area.y + area.height {
break;
}
// Center horizontally.
let line_w = line.visible_width() as u16;
let x_start = area.x + area.width.saturating_sub(line_w) / 2;
let mut x = x_start;
for span in &line.spans {
let span_fg = span.fg.map(qc).unwrap_or(*default_fg);
for ch in span.text.chars() {
if x >= area.x + area.width {
break;
}
let w = char_cell_width(ch);
if w == 2 && x + 1 < area.x + area.width {
set_cell_wide(buf, x, y, ch, span_fg, bg);
} else {
set_cell(buf, x, y, ch, span_fg, bg);
}
x += w;
}
}
}
}
fn paint_scrollbar(buf: &mut Buffer, gutter: QRect, thumb_bounds: Option<QRect>, theme: &Theme) {
let bg = ratatui_color(theme.background);
let track = ratatui_color(theme.scrollbar_track);
let thumb = ratatui_color(theme.scrollbar_thumb);
let x = gutter.x.round() as u16;
let y_start = gutter.y.round() as u16;
let height = gutter.height.round() as u16;
if height == 0 {
return;
}
// Track first; thumb overlays on top.
for dy in 0..height {
let cell_y = y_start + dy;
if cell_y >= buf.area.y + buf.area.height {
break;
}
set_cell(buf, x, cell_y, '░', track, bg);
}
// Thumb at the layout-computed position when the body's scroll state
// was introspectable (Tree, List). Falls back to a 1-cell top-anchored
// thumb for overflowing body types without row-based scroll. Per
// *Primitive Authoring Rule #6*, the thumb position must reflect state —
// the layout owns these bounds, not the rasteriser.
let (thumb_y, thumb_h) = match thumb_bounds {
Some(t) => (t.y.round() as u16, t.height.round().max(1.0) as u16),
None => (y_start, 1),
};
for dy in 0..thumb_h {
let cell_y = thumb_y + dy;
if cell_y >= buf.area.y + buf.area.height {
break;
}
if cell_y >= y_start + height {
break;
}
set_cell(buf, x, cell_y, '█', thumb, bg);
}
}
/// Panel-level scrollbar. Paints the track, then the thumb at
/// `thumb_bounds` — geometry computed once by
/// [`crate::primitives::multi_section_view::MultiSectionView::layout`]
/// (`fit_thumb` + cell quantisation) and published as
/// [`MultiSectionViewLayout::panel_scrollbar_thumb`].
///
/// Mirrors [`paint_scrollbar`]'s (per-section) pattern of consuming
/// pre-computed bounds instead of re-deriving them.
fn paint_panel_scrollbar(
buf: &mut Buffer,
bounds: QRect,
thumb_bounds: Option<QRect>,
theme: &Theme,
) {
let bg = ratatui_color(theme.background);
let track = ratatui_color(theme.scrollbar_track);
let thumb = ratatui_color(theme.scrollbar_thumb);
let x = bounds.x.round() as u16;
let y_start = bounds.y.round() as u16;
let height = bounds.height.round() as u16;
if height == 0 {
return;
}
// Track.
for dy in 0..height {
let cell_y = y_start + dy;
if cell_y >= buf.area.y + buf.area.height {
break;
}
set_cell(buf, x, cell_y, '░', track, bg);
}
// Thumb.
let (thumb_y, thumb_h) = match thumb_bounds {
Some(t) => (t.y.round() as u16, t.height.round().max(1.0) as u16),
None => (y_start, 1),
};
for dy in 0..thumb_h {
let cell_y = thumb_y + dy;
if cell_y >= y_start + height {
break;
}
if cell_y >= buf.area.y + buf.area.height {
break;
}
set_cell(buf, x, cell_y, '█', thumb, bg);
}
}
fn paint_divider(buf: &mut Buffer, bounds: QRect, theme: &Theme) {
let bg = ratatui_color(theme.background);
let fg = ratatui_color(theme.separator);
let y = bounds.y.round() as u16;
let x_start = bounds.x.round() as u16;
let width = bounds.width.round() as u16;
for dx in 0..width {
set_cell(buf, x_start + dx, y, '─', fg, bg);
}
}
// ── Helpers ────────────────────────────────────────────────────────────────
/// Intersect `r` with the y-range `[viewport_top, viewport_bottom)`.
/// Returns `None` when the rect lies entirely outside.
fn clip_to_viewport(r: QRect, viewport_top: f32, viewport_bottom: f32) -> Option<QRect> {
let r_bottom = r.y + r.height;
if r.height <= 0.0 || r_bottom <= viewport_top || r.y >= viewport_bottom {
return None;
}
let new_y = r.y.max(viewport_top);
let new_bottom = r_bottom.min(viewport_bottom);
let new_h = (new_bottom - new_y).max(0.0);
if new_h <= 0.0 {
return None;
}
Some(QRect::new(r.x, new_y, r.width, new_h))
}
fn fill_rect(
buf: &mut Buffer,
bounds: QRect,
ch: char,
fg: ratatui::style::Color,
bg: ratatui::style::Color,
) {
let x_start = bounds.x.round() as i32;
let y_start = bounds.y.round() as i32;
let x_end = (bounds.x + bounds.width).round() as i32;
let y_end = (bounds.y + bounds.height).round() as i32;
let buf_x_end = (buf.area.x + buf.area.width) as i32;
let buf_y_end = (buf.area.y + buf.area.height) as i32;
for y in y_start..y_end.min(buf_y_end) {
for x in x_start..x_end.min(buf_x_end) {
if x < 0 || y < 0 {
continue;
}
set_cell(buf, x as u16, y as u16, ch, fg, bg);
}
}
}
fn q_to_tui_rect(r: QRect) -> TuiRect {
TuiRect {
x: r.x.round().max(0.0) as u16,
y: r.y.round().max(0.0) as u16,
width: r.width.floor().max(0.0) as u16,
height: r.height.floor().max(0.0) as u16,
}
}
fn body_content_rows(body: &SectionBody) -> usize {
match body {
SectionBody::Tree(t) => t.rows.len(),
SectionBody::List(l) => l.items.len() + if l.title.is_some() { 1 } else { 0 },
SectionBody::Form(f) => f.fields.len(),
SectionBody::Chart(c) => {
if matches!(c.kind, crate::primitives::chart::ChartKind::Sparkline) {
1
} else {
8
}
}
SectionBody::MessageList(m) => m.rows.iter().map(|r| 1 + r.text.lines().count()).sum(),
SectionBody::Terminal(_) => 0,
SectionBody::Text(lines) => lines.len(),
SectionBody::Empty(_) => 4, // icon + text + hint + action, capped
SectionBody::Custom(_) => 0,
}
}
// ── Tests ──────────────────────────────────────────────────────────────────
#[cfg(test)]
mod tests {
use super::*;
use crate::primitives::multi_section_view::*;
use crate::types::{Icon, StyledText, WidgetId};
fn empty_section(id: &str, size: SectionSize) -> Section {
Section {
id: id.into(),
header: SectionHeader {
title: StyledText::plain(id.to_uppercase()),
show_chevron: true,
..Default::default()
},
body: SectionBody::Empty(EmptyBody {
text: StyledText::plain("No data"),
..Default::default()
}),
aux: None,
size,
collapsed: false,
min_size: None,
max_size: None,
}
}
fn view_with(sections: Vec<Section>) -> MultiSectionView {
MultiSectionView {
id: WidgetId::new("v"),
sections,
active_section: None,
axis: Axis::Vertical,
allow_resize: false,
allow_collapse: true,
scroll_mode: ScrollMode::PerSection,
has_focus: false,
panel_scroll: 0.0,
}
}
fn cell_char(buf: &Buffer, x: u16, y: u16) -> char {
buf[(x, y)].symbol().chars().next().unwrap_or(' ')
}
#[test]
fn paints_chevron_and_uppercase_title_in_header() {
let mut buf = Buffer::empty(TuiRect::new(0, 0, 30, 6));
let v = view_with(vec![empty_section("a", SectionSize::EqualShare)]);
draw_multi_section_view(
&mut buf,
TuiRect::new(0, 0, 30, 6),
&v,
&Theme::default(),
false,
);
assert_eq!(cell_char(&buf, 0, 0), '▾');
// Title starts at col 2 (chevron + space).
let title: String = (2..3).map(|x| cell_char(&buf, x, 0)).collect();
assert_eq!(title, "A");
}
#[test]
fn horizontal_axis_is_no_op() {
let mut buf = Buffer::empty(TuiRect::new(0, 0, 30, 6));
let mut v = view_with(vec![empty_section("a", SectionSize::EqualShare)]);
v.axis = Axis::Horizontal;
draw_multi_section_view(
&mut buf,
TuiRect::new(0, 0, 30, 6),
&v,
&Theme::default(),
false,
);
// Nothing was painted — chevron isn't there.
assert_ne!(cell_char(&buf, 0, 0), '▾');
}
#[test]
fn action_button_paints_in_rightmost_slot() {
let mut buf = Buffer::empty(TuiRect::new(0, 0, 30, 6));
let mut s = empty_section("a", SectionSize::EqualShare);
s.header.actions = vec![HeaderAction {
id: "r".into(),
icon: Icon::new("", "R"),
tooltip: None,
enabled: true,
}];
let v = view_with(vec![s]);
draw_multi_section_view(
&mut buf,
TuiRect::new(0, 0, 30, 6),
&v,
&Theme::default(),
false,
);
// 'R' is painted at column 28 (icon at right - 2 + 1 = right - 1, but our calc
// uses action_w = glyph_chars + 1 space pad = 2; right_cursor=30; icon_x=29).
// Let's just scan the last 3 cells of row 0 for an 'R'.
let tail: String = (27..30).map(|x| cell_char(&buf, x, 0)).collect();
assert!(tail.contains('R'), "expected 'R' in tail, got {tail:?}");
}
#[test]
fn input_aux_renders_placeholder_when_empty_and_unfocused() {
let mut buf = Buffer::empty(TuiRect::new(0, 0, 30, 6));
let mut s = empty_section("sc", SectionSize::EqualShare);
s.aux = Some(SectionAux::Input(InlineInput {
id: WidgetId::new("commit"),
text: String::new(),
caret: 0,
placeholder: Some("Commit".into()),
has_focus: false,
}));
let v = view_with(vec![s]);
draw_multi_section_view(
&mut buf,
TuiRect::new(0, 0, 30, 6),
&v,
&Theme::default(),
false,
);
// Aux row at y=1.
let placeholder: String = (0..6).map(|x| cell_char(&buf, x, 1)).collect();
assert_eq!(placeholder, "Commit");
}
// ── Paint↔click round-trip harness ─────────────────────────────────────
//
// Primitives that promise paint/click consistency need empirical
// verification, not just structural design. These tests paint a
// `MultiSectionView` into a ratatui `Buffer`, find the cells the
// rasteriser actually wrote glyphs into, then hit_test those exact
// coordinates against the same `MultiSectionViewLayout` and assert the
// hit identifies the painted-into section. If paint and click drift in
// the TUI rasteriser, one of these fails.
use super::{draw_multi_section_view, tui_msv_layout};
use crate::primitives::tree::{TreeRow, TreeView};
use crate::types::SelectionMode;
/// Paint into `buf` and return the layout the rasteriser used. Hit
/// tests query the SAME layout instance — that's the source-of-truth
/// contract the harness verifies. (`draw_multi_section_view`
/// internally calls `tui_msv_layout`; calling it again here returns
/// an equivalent layout because `tui_msv_layout` is pure: same
/// `view` + `area` → identical bounds.)
fn paint_then_layout(
buf: &mut Buffer,
area: TuiRect,
view: &MultiSectionView,
theme: &Theme,
nerd_fonts_enabled: bool,
) -> MultiSectionViewLayout {
draw_multi_section_view(buf, area, view, theme, nerd_fonts_enabled);
tui_msv_layout(view, area)
}
fn tree_section(id: &str, items: &[&str], size: SectionSize) -> Section {
let rows: Vec<TreeRow> = items
.iter()
.enumerate()
.map(|(i, t)| TreeRow {
path: vec![i as u16],
indent: 0,
icon: None,
text: StyledText::plain((*t).to_string()),
badge: None,
is_expanded: None,
decoration: Default::default(),
edit: None,
})
.collect();
Section {
id: id.into(),
header: SectionHeader {
title: StyledText::plain(id.to_uppercase()),
show_chevron: false,
..Default::default()
},
body: SectionBody::Tree(TreeView {
id: WidgetId::new(format!("{}-tree", id)),
rows,
selection_mode: SelectionMode::Single,
selected_path: None,
scroll_offset: 0,
style: Default::default(),
has_focus: true,
}),
aux: None,
size,
collapsed: false,
min_size: None,
max_size: None,
}
}
fn row_text(buf: &Buffer, y: u16) -> String {
let area = buf.area;
(area.x..area.x + area.width)
.map(|x| cell_char(buf, x, y))
.collect()
}
fn find_row_with(buf: &Buffer, needle: &str) -> Option<u16> {
let area = buf.area;
(area.y..area.y + area.height).find(|&y| row_text(buf, y).contains(needle))
}
/// Round-trip: paint, find each section's title row in the buffer,
/// hit_test that coordinate, assert the hit identifies the same
/// section. Uses a fractional `EqualShare` distribution (4 sections
/// in 21 cells = 5.25 each) — the worst case for paint/click drift.
///
/// Run at both the origin and a non-zero `area` origin. `tui_msv_layout`
/// bakes `area.x`/`area.y` straight into the returned bounds (absolute
/// frame), and `paint_then_layout` already takes `area` as a parameter,
/// so this re-runs the identical logic at a shifted origin. `find_row_with`/
/// `row_text` derive their scan range from `buf.area` (not a hardcoded
/// rect), so they track the origin too.
fn header_clicks_land_in_painted_section_under_fractional_distribution_at(
origin_x: u16,
origin_y: u16,
) {
let area = TuiRect::new(origin_x, origin_y, 30, 21);
let mut buf = Buffer::empty(area);
let v = view_with(vec![
tree_section("alpha", &["a1", "a2", "a3"], SectionSize::EqualShare),
tree_section("beta", &["b1", "b2", "b3"], SectionSize::EqualShare),
tree_section("gamma", &["g1", "g2", "g3"], SectionSize::EqualShare),
tree_section("delta", &["d1", "d2", "d3"], SectionSize::EqualShare),
]);
let layout = paint_then_layout(&mut buf, area, &v, &Theme::default(), false);
for s in &layout.sections {
let needle = v.sections[s.section_idx]
.header
.title
.spans
.first()
.map(|sp| sp.text.clone())
.unwrap_or_default();
let painted_y = find_row_with(&buf, &needle).unwrap_or_else(|| {
panic!(
"section {} title {:?} was not painted into the buffer",
s.section_idx, needle
)
});
let hit = layout.hit_test(area.x as f32 + 5.0, painted_y as f32);
match hit {
MultiSectionViewHit::Header { section, .. } => assert_eq!(
section, s.section_idx,
"row {} paints section {} title {:?} but hit_test returns section {}",
painted_y, s.section_idx, needle, section
),
other => panic!(
"row {} paints section {} title {:?} but hit_test returns {:?}",
painted_y, s.section_idx, needle, other
),
}
}
}
#[test]
fn header_clicks_land_in_painted_section_under_fractional_distribution() {
header_clicks_land_in_painted_section_under_fractional_distribution_at(0, 0);
}
/// Non-zero-origin regression guard.
#[test]
fn header_clicks_land_in_painted_section_under_fractional_distribution_at_nonzero_origin() {
header_clicks_land_in_painted_section_under_fractional_distribution_at(7, 13);
}
/// Round-trip: paint, find each section's body item rows (rows
/// containing item glyphs but NOT the title), hit_test those
/// coordinates, assert each lands in the SAME section's `Body`.
///
/// Run at both the origin and a non-zero `area` origin. See
/// `header_clicks_land_in_painted_section_under_fractional_distribution_at`
/// for why coordinate translation via a shifted `area` is necessary.
fn body_clicks_land_in_painted_section_under_fractional_distribution_at(
origin_x: u16,
origin_y: u16,
) {
let area = TuiRect::new(origin_x, origin_y, 30, 21);
let mut buf = Buffer::empty(area);
let v = view_with(vec![
tree_section("alpha", &["a1", "a2", "a3"], SectionSize::EqualShare),
tree_section("beta", &["b1", "b2", "b3"], SectionSize::EqualShare),
tree_section("gamma", &["g1", "g2", "g3"], SectionSize::EqualShare),
tree_section("delta", &["d1", "d2", "d3"], SectionSize::EqualShare),
]);
let layout = paint_then_layout(&mut buf, area, &v, &Theme::default(), false);
for s in &layout.sections {
let body_b = s.body_bounds;
if body_b.height < 1.0 {
continue;
}
// Find an item row painted inside this section's body bounds.
// body_bounds is in absolute coords; iterate cell rows that
// lie strictly inside.
let body_y_start = body_b.y.round() as u16;
let body_y_end = (body_b.y + body_b.height).round() as u16;
let body_x_start = body_b.x.round() as u16;
let body_x_end = (body_b.x + body_b.width).round() as u16;
let item_prefix = match v.sections[s.section_idx].id.chars().next() {
Some(c) => c,
None => continue,
};
let mut painted_item_y: Option<u16> = None;
for y in body_y_start..body_y_end {
let row = row_text(&buf, y);
if row.contains(item_prefix)
&& !row.contains(&v.sections[s.section_idx].id.to_uppercase())
{
painted_item_y = Some(y);
break;
}
}
let painted_y = painted_item_y.unwrap_or_else(|| {
panic!(
"section {} ({}) body bounds y={}..{} contained no painted item row",
s.section_idx, v.sections[s.section_idx].id, body_y_start, body_y_end
)
});
// Hit_test at a column inside the body bounds.
let click_x = (body_x_start + body_x_end) as f32 / 2.0;
let hit = layout.hit_test(click_x, painted_y as f32);
match hit {
MultiSectionViewHit::Body { section } => assert_eq!(
section, s.section_idx,
"row {} paints item in section {} but hit_test returns Body{{section: {}}}",
painted_y, s.section_idx, section
),
other => panic!(
"row {} paints item in section {} but hit_test returns {:?}",
painted_y, s.section_idx, other
),
}
}
}
#[test]
fn body_clicks_land_in_painted_section_under_fractional_distribution() {
body_clicks_land_in_painted_section_under_fractional_distribution_at(0, 0);
}
/// Non-zero-origin regression guard.
#[test]
fn body_clicks_land_in_painted_section_under_fractional_distribution_at_nonzero_origin() {
body_clicks_land_in_painted_section_under_fractional_distribution_at(7, 13);
}
/// Sections with overflowing content reserve a 1-cell scrollbar
/// gutter on the body's trailing edge. Clicks in that column must
/// hit `Scrollbar`, NOT `Body` — otherwise the click would select
/// an empty body row instead of scrolling. Body and Scrollbar hit
/// regions must not overlap, and Body must not extend into the
/// scrollbar column.
#[test]
fn scrollbar_column_hits_scrollbar_not_body_when_section_overflows() {
let area = TuiRect::new(0, 0, 20, 8);
let mut buf = Buffer::empty(area);
// 1 section, 10 items in a 6-row body — overflows.
let v = view_with(vec![tree_section(
"lots",
&["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"],
SectionSize::EqualShare,
)]);
let layout = paint_then_layout(&mut buf, area, &v, &Theme::default(), false);
let s = &layout.sections[0];
let sb = s
.scrollbar_bounds
.expect("overflowing section must reserve a scrollbar gutter (paint↔click contract)");
// Hit_test the centre cell of the scrollbar column.
let click_x = sb.x + sb.width / 2.0;
let click_y = sb.y + sb.height / 2.0;
match layout.hit_test(click_x, click_y) {
MultiSectionViewHit::Scrollbar { section, .. } => {
assert_eq!(section, 0, "expected Scrollbar{{0}}");
}
other => panic!(
"click at ({:.1}, {:.1}) inside scrollbar bounds {:?} returned {:?} — Body has shadowed Scrollbar in hit_regions",
click_x, click_y, sb, other
),
}
// Conversely, hit_test the leftmost body cell — that must be Body, not Scrollbar.
let body_b = s.body_bounds;
if body_b.height >= 1.0 && body_b.width >= 1.0 {
let click = layout.hit_test(body_b.x + 0.5, body_b.y + 0.5);
assert!(
matches!(click, MultiSectionViewHit::Body { section: 0 }),
"leftmost body cell at ({:.1}, {:.1}) returned {:?}",
body_b.x + 0.5,
body_b.y + 0.5,
click
);
}
}
/// Painted scrollbar thumb lands at the y range the layout computed
/// from `(scroll_offset, content_rows, viewport_rows)` — this is the
/// *Primitive Authoring Rule #6* test for state-derived paint geometry.
///
/// Setup: one section with 20 rows in a 10-cell body, scrolled by
/// 2 rows. With the snapping arithmetic in `compute_thumb_bounds`,
/// thumb lands at `sb.y + 1` with height 5.
#[test]
fn scrollbar_thumb_paints_at_layout_position() {
let area = TuiRect::new(0, 0, 30, 11);
let mut buf = Buffer::empty(area);
let mut v = view_with(vec![tree_section(
"scrolly",
&[
"r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12",
"r13", "r14", "r15", "r16", "r17", "r18", "r19",
],
SectionSize::EqualShare,
)]);
// Scroll 2 rows down on the only section.
if let SectionBody::Tree(t) = &mut v.sections[0].body {
t.scroll_offset = 2;
}
let layout = paint_then_layout(&mut buf, area, &v, &Theme::default(), false);
let thumb = layout.sections[0]
.thumb_bounds
.expect("Tree body with overflow should have computed thumb_bounds");
let sb = layout.sections[0].scrollbar_bounds.unwrap();
// Part A — layout's thumb_bounds matches the formula.
// fit_thumb(scroll=2, total=20, visible=10, track=10, min=1) →
// raw_len = 10/20 * 10 = 5; thumb_len = 5
// range = max(20-10, 1) = 10; travel = 10-5 = 5
// thumb_start = (2/10)*5 = 1.0
// With cell_quantum=1.0: start_q=1, end_q=ceil(6)=6, len=5.
// Section 0 starts at y=0; header 1 cell; gutter at y=1, height 10.
// → thumb at sb.y(=1)+1 = 2, height 5. Catches layout-formula
// mutations that move with paint (paint+layout could agree on
// a wrong answer if both reference the same broken formula).
assert!(
(thumb.y - 2.0).abs() < 0.01,
"thumb.y = {} (expected 2.0 from formula)",
thumb.y
);
assert!(
(thumb.height - 5.0).abs() < 0.01,
"thumb.height = {} (expected 5.0 from formula)",
thumb.height
);
// Part B — painted '█' rows match thumb_bounds. Catches paint
// mutations that ignore thumb_bounds.
let gutter_x = sb.x.round() as u16;
let mut painted_thumb_rows: Vec<u16> = Vec::new();
for y in (sb.y.round() as u16)..((sb.y + sb.height).round() as u16) {
if cell_char(&buf, gutter_x, y) == '█' {
painted_thumb_rows.push(y);
}
}
assert_eq!(
painted_thumb_rows,
(thumb.y.round() as u16..(thumb.y + thumb.height).round() as u16).collect::<Vec<_>>(),
"painted thumb rows should match layout's thumb_bounds y range"
);
// Part C — hit_test at a painted thumb cell returns
// `Scrollbar { Thumb }`. Closes the round-trip: paint position,
// layout bounds, and hit region all reference the same
// coordinates.
let painted_mid = painted_thumb_rows[painted_thumb_rows.len() / 2];
match layout.hit_test(sb.x + sb.width / 2.0, painted_mid as f32 + 0.5) {
MultiSectionViewHit::Scrollbar {
section,
kind: ScrollbarHit::Thumb,
} => assert_eq!(section, 0),
other => panic!(
"hit at painted thumb row {} returned {:?}; expected Scrollbar::Thumb",
painted_mid, other
),
}
}
/// Panel-level (`WholePanel`) scrollbar: painted thumb glyphs match
/// [`MultiSectionViewLayout::panel_scrollbar_thumb`] exactly, and
/// that thumb's size accounts for divider strips.
///
/// Regression coverage: `paint_panel_scrollbar` must reuse the thumb
/// geometry from `panel_scrollbar_thumb` (computed once via `fit_thumb`)
/// rather than recomputing from section sizes alone. With two 11-row tree
/// sections (each `1 (header) + 11 (rows) = 12`) plus one 1-cell divider
/// (`allow_resize = true`), the correct total is `25`, not `24`. In a
/// 10-row viewport that difference changes the painted thumb height: 4.0
/// vs. ceil(4.1666) = 5 — a visibly taller, wrong thumb.
#[test]
fn panel_scrollbar_thumb_paints_at_layout_position_with_dividers() {
let area = TuiRect::new(0, 0, 20, 10);
let mut buf = Buffer::empty(area);
let rows: [&str; 11] = [
"r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10",
];
let v = MultiSectionView {
id: WidgetId::new("v"),
sections: vec![
tree_section("a", &rows, SectionSize::EqualShare),
tree_section("b", &rows, SectionSize::EqualShare),
],
active_section: None,
axis: Axis::Vertical,
allow_resize: true,
allow_collapse: true,
scroll_mode: ScrollMode::WholePanel,
has_focus: false,
panel_scroll: 0.0,
};
let layout = paint_then_layout(&mut buf, area, &v, &Theme::default(), false);
let panel_sb = layout
.panel_scrollbar
.expect("total_content (25) > viewport (10) → panel scrollbar present");
let thumb = layout
.panel_scrollbar_thumb
.expect("panel_scrollbar present implies panel_scrollbar_thumb present");
// Part A — matches `fit_thumb(scroll=0, total=25, visible=10,
// track=10, min=1)`: raw_len = 10/25*10 = 4.0, thumb_len = 4.0;
// scroll=0 → thumb_start = 0.
assert!(
(thumb.height - 4.0).abs() < 0.01,
"thumb.height = {} (expected 4.0 — pre-#820 formula would give 5.0 \
by dropping the divider strip from its total)",
thumb.height
);
assert!(
(thumb.y - panel_sb.y).abs() < 0.01,
"thumb.y = {} (expected to start at the track top: panel_scroll=0)",
thumb.y
);
// Part B — painted '█' rows match `panel_scrollbar_thumb` exactly.
let gutter_x = panel_sb.x.round() as u16;
let mut painted_thumb_rows: Vec<u16> = Vec::new();
for y in (panel_sb.y.round() as u16)..((panel_sb.y + panel_sb.height).round() as u16) {
if cell_char(&buf, gutter_x, y) == '█' {
painted_thumb_rows.push(y);
}
}
assert_eq!(
painted_thumb_rows,
(thumb.y.round() as u16..(thumb.y + thumb.height).round() as u16).collect::<Vec<_>>(),
"painted panel-thumb rows should match layout's panel_scrollbar_thumb"
);
// Part C — hit_test at a painted thumb cell returns
// `PanelScrollbar { Thumb }`, closing the paint/layout/hit-test
// round trip.
let painted_mid = painted_thumb_rows[painted_thumb_rows.len() / 2];
match layout.hit_test(panel_sb.x + panel_sb.width / 2.0, painted_mid as f32 + 0.5) {
MultiSectionViewHit::PanelScrollbar {
kind: ScrollbarHit::Thumb,
} => {}
other => panic!(
"hit at painted panel-thumb row {} returned {:?}; expected PanelScrollbar::Thumb",
painted_mid, other
),
}
}
/// Hit-test in the gutter column above the painted thumb returns
/// `TrackBefore`, not `Thumb`. Locks the consumer-page-up
/// contract: clicking above the thumb is meant to page up by the
/// viewport size, not start a thumb drag.
#[test]
fn track_before_thumb_hits_track_before() {
let area = TuiRect::new(0, 0, 30, 11);
let mut v = view_with(vec![tree_section(
"scrolly",
&[
"r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12",
"r13", "r14", "r15", "r16", "r17", "r18", "r19",
],
SectionSize::EqualShare,
)]);
if let SectionBody::Tree(t) = &mut v.sections[0].body {
t.scroll_offset = 2; // thumb lands away from the top
}
let layout = tui_msv_layout(&v, area);
let sb = layout.sections[0].scrollbar_bounds.unwrap();
let thumb = layout.sections[0].thumb_bounds.unwrap();
// Click in the gutter column above the thumb's first y.
let click_x = sb.x + sb.width / 2.0;
let click_y = sb.y + 0.5; // top-of-gutter cell, before thumb starts
assert!(
click_y < thumb.y,
"test setup: click_y must be above thumb.y (got {} vs {})",
click_y,
thumb.y
);
match layout.hit_test(click_x, click_y) {
MultiSectionViewHit::Scrollbar {
section,
kind: ScrollbarHit::TrackBefore,
} => assert_eq!(section, 0),
other => panic!("expected TrackBefore, got {:?}", other),
}
}
/// Symmetric: hit-test below the painted thumb returns
/// `TrackAfter`. Locks the page-down contract.
#[test]
fn track_after_thumb_hits_track_after() {
let area = TuiRect::new(0, 0, 30, 11);
let mut v = view_with(vec![tree_section(
"scrolly",
&[
"r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12",
"r13", "r14", "r15", "r16", "r17", "r18", "r19",
],
SectionSize::EqualShare,
)]);
if let SectionBody::Tree(t) = &mut v.sections[0].body {
t.scroll_offset = 2;
}
let layout = tui_msv_layout(&v, area);
let sb = layout.sections[0].scrollbar_bounds.unwrap();
let thumb = layout.sections[0].thumb_bounds.unwrap();
// Click in the gutter below thumb's last y.
let click_x = sb.x + sb.width / 2.0;
let click_y = thumb.y + thumb.height + 0.5;
assert!(
click_y < sb.y + sb.height,
"test setup: click_y must be inside the gutter"
);
match layout.hit_test(click_x, click_y) {
MultiSectionViewHit::Scrollbar {
section,
kind: ScrollbarHit::TrackAfter,
} => assert_eq!(section, 0),
other => panic!("expected TrackAfter, got {:?}", other),
}
}
/// Each section's body bounds and scrollbar bounds must not
/// overlap. If body extended into the scrollbar column, paint and
/// click would each see the column differently. Walk every section
/// that has a scrollbar and assert the geometric exclusion.
#[test]
fn body_and_scrollbar_bounds_never_overlap() {
let area = TuiRect::new(0, 0, 20, 24);
let v = view_with(vec![
tree_section(
"a",
&["x", "y", "z", "w", "v", "u", "t", "s"],
SectionSize::EqualShare,
),
tree_section(
"b",
&["x", "y", "z", "w", "v", "u", "t", "s"],
SectionSize::EqualShare,
),
]);
let mut buf = Buffer::empty(area);
let layout = paint_then_layout(&mut buf, area, &v, &Theme::default(), false);
for s in &layout.sections {
if let Some(sb) = s.scrollbar_bounds {
let body = s.body_bounds;
let body_right = body.x + body.width;
let sb_left = sb.x;
assert!(
body_right <= sb_left + 0.001,
"section {}: body bounds {:?} extend into scrollbar bounds {:?}",
s.section_idx,
body,
sb
);
}
}
}
#[test]
fn divider_painted_only_when_resize_allowed() {
let mut buf = Buffer::empty(TuiRect::new(0, 0, 10, 8));
let mut v = view_with(vec![
empty_section("a", SectionSize::EqualShare),
empty_section("b", SectionSize::EqualShare),
]);
// Without allow_resize: no divider strip, sections take 4 rows each.
draw_multi_section_view(
&mut buf,
TuiRect::new(0, 0, 10, 8),
&v,
&Theme::default(),
false,
);
// No `─` glyph anywhere.
for y in 0..8 {
for x in 0..10 {
assert_ne!(cell_char(&buf, x, y), '─');
}
}
v.allow_resize = true;
let mut buf = Buffer::empty(TuiRect::new(0, 0, 10, 9));
draw_multi_section_view(
&mut buf,
TuiRect::new(0, 0, 10, 9),
&v,
&Theme::default(),
false,
);
// Should now have a `─` row somewhere.
let mut found = false;
for y in 0..9 {
for x in 0..10 {
if cell_char(&buf, x, y) == '─' {
found = true;
}
}
}
assert!(found, "expected `─` divider strip");
}
// ── Consumer-state round-trip harness ──────────────────────────────────
//
// The primitive-level round-trip tests above prove paint and click
// agree on coordinate geometry. These tests prove the agreement
// still holds under the *consumer pattern* the Debug sidebar (and
// any "N stacked TreeView sections" host) wants:
//
// - Per-section `scroll_offset` and `selected_path` live on the
// host, not on the primitive.
// - Header click activates the section without selecting a row.
// - Body row click activates AND selects.
// - Empty-body click activates without selecting.
// - Scrollbar drag updates ONLY the targeted section's offset.
// - After offset changes, paint shows the offset-th row at the
// body's top — and clicking that top row hit_tests back to the
// same row index.
//
// The runnable counterpart is `quadraui/examples/msv_multi_tree.rs`.
//
// Per CLAUDE.md "Migration discipline (corollary)": a green
// primitive test does not prove the consumer integration is
// correct. These tests are the gate that proves it for this
// consumer shape.
use crate::primitives::tree::TreeRow as TR;
use crate::types::TreePath;
struct ConsumerSection {
id: SectionId,
rows: Vec<TR>,
scroll_offset: usize,
selected_path: Option<TreePath>,
}
struct ConsumerState {
sections: Vec<ConsumerSection>,
active_section: Option<usize>,
}
impl ConsumerState {
fn build_view(&self) -> MultiSectionView {
let sections = self
.sections
.iter()
.enumerate()
.map(|(idx, s)| Section {
id: s.id.clone(),
header: SectionHeader {
title: StyledText::plain(s.id.to_uppercase()),
show_chevron: false,
..Default::default()
},
body: SectionBody::Tree(TreeView {
id: WidgetId::new(format!("{}-tree", s.id)),
rows: s.rows.clone(),
selection_mode: crate::types::SelectionMode::Single,
selected_path: s.selected_path.clone(),
scroll_offset: s.scroll_offset,
style: Default::default(),
has_focus: self.active_section == Some(idx),
}),
aux: None,
size: SectionSize::EqualShare,
collapsed: false,
min_size: None,
max_size: None,
})
.collect();
MultiSectionView {
id: WidgetId::new("consumer"),
sections,
active_section: self.active_section,
axis: Axis::Vertical,
allow_resize: false,
allow_collapse: false,
scroll_mode: ScrollMode::PerSection,
has_focus: true,
panel_scroll: 0.0,
}
}
/// Route a primary click at `(x, y)` inside `area` exactly the
/// way `examples/msv_multi_tree.rs::DebugSidebar::click` does.
/// Header → activate w/o select; Body+Row → activate+select;
/// Body+Empty (empty section) → activate w/o select.
/// Mirror the example's `DebugSidebar::drag_to` arithmetic:
/// 1 cell of drag = 1 row of scroll, clamped to
/// `[0, rows.len() - viewport_rows]`. The natural-max clamp
/// (vs. the naive `rows.len() - 1`) is the bug class
/// `consumer_drag_past_natural_max_clamps_to_keep_viewport_full`
/// catches.
fn drag_scrollbar(
&mut self,
section: usize,
origin_offset: usize,
viewport_rows: usize,
dy: i32,
) {
let row_count = self.sections[section].rows.len();
let max_offset = row_count.saturating_sub(viewport_rows);
let new = (origin_offset as i32 + dy).max(0) as usize;
self.sections[section].scroll_offset = new.min(max_offset);
}
fn click(&mut self, x: f32, y: f32, area: TuiRect) {
let view = self.build_view();
let layout = tui_msv_layout(&view, area);
match layout.hit_test(x, y) {
MultiSectionViewHit::Header { section, .. } => {
self.active_section = Some(section);
self.sections[section].selected_path = None;
}
MultiSectionViewHit::Body { section } => {
self.active_section = Some(section);
let body_b = layout.sections[section].body_bounds;
let tree = match &view.sections[section].body {
SectionBody::Tree(t) => t.clone(),
_ => return,
};
let body_area = TuiRect::new(
body_b.x.round() as u16,
body_b.y.round() as u16,
body_b.width.round() as u16,
body_b.height.round() as u16,
);
let inner = crate::tui::tui_tree_layout(&tree, body_area);
match inner.hit_test(x - body_b.x, y - body_b.y) {
crate::TreeViewHit::Row(idx) | crate::TreeViewHit::Chevron(idx) => {
self.sections[section].selected_path =
Some(tree.rows[idx].path.clone());
}
crate::TreeViewHit::Empty => {
// Activated above; nothing to select.
}
}
}
_ => {}
}
}
}
fn make_rows(prefix: &str, n: usize) -> Vec<TR> {
(0..n)
.map(|i| TR {
path: vec![i as u16],
indent: 0,
icon: None,
text: StyledText::plain(format!("{prefix}{i}")),
badge: None,
is_expanded: None,
decoration: Default::default(),
edit: None,
})
.collect()
}
fn debug_sidebar_state() -> ConsumerState {
ConsumerState {
sections: vec![
ConsumerSection {
id: "vars".into(),
rows: make_rows("v", 12),
scroll_offset: 0,
selected_path: None,
},
ConsumerSection {
id: "watch".into(),
rows: make_rows("w", 8),
scroll_offset: 0,
selected_path: None,
},
ConsumerSection {
id: "stack".into(),
rows: make_rows("frame", 5),
scroll_offset: 0,
selected_path: None,
},
ConsumerSection {
id: "bps".into(),
rows: Vec::new(), // empty body
scroll_offset: 0,
selected_path: None,
},
],
active_section: None,
}
}
/// Header click activates the section but does NOT select a row.
/// Important for VSCode-style sidebars: clicking the header focuses
/// the section; selection is reserved for body interaction.
#[test]
fn consumer_header_click_activates_section_without_selecting() {
let area = TuiRect::new(0, 0, 30, 20);
let mut state = debug_sidebar_state();
// Pre-seed a selection in section 1 — header click on section 2
// must NOT clobber section 1's selection.
state.sections[1].selected_path = Some(vec![3]);
// Find the header row of section 2 by querying the layout.
let view = state.build_view();
let layout = tui_msv_layout(&view, area);
let hb = layout.sections[2].header_bounds;
let click_x = hb.x + hb.width / 2.0;
let click_y = hb.y + 0.5;
state.click(click_x, click_y, area);
assert_eq!(
state.active_section,
Some(2),
"header click should activate section 2"
);
assert!(
state.sections[2].selected_path.is_none(),
"header click must not select a row in the activated section"
);
assert_eq!(
state.sections[1].selected_path,
Some(vec![3]),
"header click on section 2 must not touch section 1's selection"
);
}
/// Body row click activates the section AND selects the clicked
/// row. Round-trip: paint, find a body row in the buffer, click at
/// that exact y, assert the selected_path matches that row's path.
/// Catches the consumer-side off-by-one where paint/click agreed
/// at the primitive layer but the host's inner-tree hit-test
/// translation drifted (subtracting wrong origin, etc).
#[test]
fn consumer_body_row_click_activates_and_selects_clicked_row() {
let area = TuiRect::new(0, 0, 30, 21);
let mut buf = Buffer::empty(area);
let mut state = debug_sidebar_state();
let view = state.build_view();
// Paint, then find the row with text "v2" (vars section, 3rd row).
draw_multi_section_view(&mut buf, area, &view, &Theme::default(), false);
let layout = tui_msv_layout(&view, area);
let body_b = layout.sections[0].body_bounds;
let body_y_start = body_b.y.round() as u16;
let body_y_end = (body_b.y + body_b.height).round() as u16;
// Scan body rows for "v2".
let mut painted_y: Option<u16> = None;
for y in body_y_start..body_y_end {
let row: String = (area.x..area.x + area.width)
.map(|x| cell_char(&buf, x, y))
.collect();
if row.contains("v2") {
painted_y = Some(y);
break;
}
}
let painted_y = painted_y.expect("v2 should be painted in section 0 body");
// Click at the centre of the body width on the painted row.
let click_x = body_b.x + body_b.width / 2.0;
state.click(click_x, painted_y as f32 + 0.5, area);
assert_eq!(state.active_section, Some(0), "section 0 should activate");
assert_eq!(
state.sections[0].selected_path,
Some(vec![2]),
"click on painted v2 should select path [2]"
);
}
/// Body click on an empty section activates the section but does
/// NOT set a selection (no rows to pick). The `Body { section }`
/// hit fires; the host's inner-tree hit_test returns
/// `TreeViewHit::Empty`; the host filters and leaves selection
/// alone.
#[test]
fn consumer_empty_body_click_activates_without_selecting() {
let area = TuiRect::new(0, 0, 30, 21);
let mut state = debug_sidebar_state();
// Section 3 (`bps`) has 0 rows.
let view = state.build_view();
let layout = tui_msv_layout(&view, area);
let body_b = layout.sections[3].body_bounds;
let click_x = body_b.x + body_b.width / 2.0;
let click_y = body_b.y + body_b.height / 2.0;
state.click(click_x, click_y, area);
assert_eq!(
state.active_section,
Some(3),
"empty-body click should still activate the section"
);
assert!(
state.sections[3].selected_path.is_none(),
"empty body has no row to select"
);
}
/// Scrollbar drag (consumer-side) updates ONLY the targeted
/// section's `scroll_offset`. The other sections keep their
/// state — that's the whole point of host-owned per-section state
/// vs. a shared bridging cell. Test simulates the same MouseDown +
/// MouseMoved sequence the example's `DebugSidebar::click` /
/// `drag_to` apply.
#[test]
fn consumer_scrollbar_drag_updates_only_targeted_section_offset() {
// 30 cols × 24 rows so each EqualShare section gets enough
// body height for `vars` (12 rows) to overflow and reserve a
// scrollbar gutter. With 24 cells / 4 sections, each section
// has 6 cells (1 header + 5 body) — vars has 12 rows so
// body_overflows fires.
let area = TuiRect::new(0, 0, 30, 24);
let mut state = debug_sidebar_state();
// Pre-seed a selection in another section so we can verify
// the drag doesn't disturb it.
state.sections[1].selected_path = Some(vec![4]);
let view = state.build_view();
let layout = tui_msv_layout(&view, area);
// Section 0 (vars) overflows — it must have a scrollbar.
let sb = layout.sections[0]
.scrollbar_bounds
.expect("vars body overflows; expected scrollbar gutter");
// Simulate MouseDown on the scrollbar — capture origin and
// section viewport rows the same way the example's
// `DebugSidebar::click` does.
let press_y = sb.y.round() as u16;
let origin_offset = state.sections[0].scroll_offset;
let viewport_rows = layout.sections[0].body_bounds.height as usize;
// Simulate MouseMoved 3 cells down via the consumer's drag
// helper. 1 cell = 1 row.
let drag_y = press_y + 3;
let dy = drag_y as i32 - press_y as i32;
state.drag_scrollbar(0, origin_offset, viewport_rows, dy);
// Only section 0's offset moved.
assert_eq!(state.sections[0].scroll_offset, 3);
assert_eq!(state.sections[1].scroll_offset, 0);
assert_eq!(state.sections[2].scroll_offset, 0);
assert_eq!(state.sections[3].scroll_offset, 0);
// Other sections' selection / state untouched.
assert_eq!(state.sections[1].selected_path, Some(vec![4]));
assert!(state.sections[2].selected_path.is_none());
}
/// Smoke-found regression: dragging past the bottom of the gutter
/// kept advancing the inner tree's `scroll_offset` past the
/// natural max (`rows.len() - viewport_rows`), ending in states
/// where only the trailing row was visible while the saturated
/// thumb sat idle. Per *Primitive Authoring Rule #6* the thumb
/// position correctly saturates at max scroll (`fit_thumb` clamps
/// `scroll/range` to `[0, 1]`); the bug is consumer-side — drag
/// must clamp to the natural max so paint and state stay in sync.
///
/// Catches naive `rows.len() - 1` clamps. Empirically: replacing
/// the clamp denominator with `1` in `drag_scrollbar` makes this
/// test fail.
#[test]
fn consumer_drag_past_natural_max_clamps_to_keep_viewport_full() {
let area = TuiRect::new(0, 0, 30, 24);
let mut state = debug_sidebar_state();
let view = state.build_view();
let layout = tui_msv_layout(&view, area);
let viewport_rows = layout.sections[0].body_bounds.height as usize;
let row_count = state.sections[0].rows.len();
let natural_max = row_count.saturating_sub(viewport_rows);
assert!(
natural_max > 0 && natural_max < row_count - 1,
"test setup: vars must overflow with a non-degenerate natural_max (got {natural_max}, row_count {row_count}, viewport {viewport_rows})"
);
// Drag WAY past the bottom — dy = +1000 cells. Natural-max
// clamp must absorb the overshoot.
state.drag_scrollbar(0, 0, viewport_rows, 1000);
assert_eq!(
state.sections[0].scroll_offset, natural_max,
"drag past bottom should clamp to natural_max ({natural_max}); got {}",
state.sections[0].scroll_offset
);
assert!(
state.sections[0].scroll_offset < row_count - 1,
"scroll_offset reached row_count - 1 ({}) — that's the over-scroll \
state where only the trailing row is visible. The natural-max \
clamp must prevent this by construction.",
row_count - 1
);
}
/// After updating a section's `scroll_offset`, paint shows the
/// offset-th source row at the body's top — and clicking that top
/// row hit_tests back to the same row index. This is the round-
/// trip across the scroll boundary: paint and click both consume
/// `scroll_offset`, so they must agree on which row is at the top
/// after any drag.
#[test]
fn consumer_post_drag_paint_and_click_agree_on_top_row() {
let area = TuiRect::new(0, 0, 30, 24);
let mut buf = Buffer::empty(area);
let mut state = debug_sidebar_state();
// Apply a drag of 3 rows on section 0 (vars).
state.sections[0].scroll_offset = 3;
// Paint the new state.
let view = state.build_view();
draw_multi_section_view(&mut buf, area, &view, &Theme::default(), false);
let layout = tui_msv_layout(&view, area);
// The body of section 0 now shows v3, v4, v5, ... at the top.
// Find "v3" in the buffer; assert it's painted at body's first
// row, and clicking that row selects path [3].
let body_b = layout.sections[0].body_bounds;
let top_y = body_b.y.round() as u16;
let row: String = (area.x..area.x + area.width)
.map(|x| cell_char(&buf, x, top_y))
.collect();
assert!(
row.contains("v3"),
"post-drag top body row should paint v3, got {row:?}"
);
// Click that top row — selected_path must be [3], not [0].
let click_x = body_b.x + body_b.width / 2.0;
state.click(click_x, top_y as f32 + 0.5, area);
assert_eq!(
state.sections[0].selected_path,
Some(vec![3]),
"click on post-drag top row should select path [3] (the offset)"
);
}
// ── Consumer-state round-trip harness — SC panel ─────────────────────
//
// Per-issue #2: the SC panel consumer shape adds a
// `SectionAux::Input` commit-message editor on section 0, plus
// collapsible Tree sections. The contracts the harness verifies:
//
// - Input keystrokes update aux text + caret; paint shows the
// typed text in the aux row.
// - Click on aux focuses the input; click outside blurs it.
// - Click on chevron toggles `collapsed`; round-trip across paint
// of '▾'/'▸' glyphs and click resolution stays consistent.
// - Collapsed section paints header only — the inner Tree's
// items do not appear in the buffer in that section's vertical
// span.
// - For every cell in the view, hit_test never returns
// `Body { section }` for a collapsed section. Locks the
// "click in collapsed body area" semantics (acceptance
// criterion 3): there is no body region for a collapsed
// section; the next section's chrome occupies that y-range.
//
// Runnable counterpart: `quadraui/examples/msv_sc_panel.rs`.
struct SCState {
commit_message: String,
commit_caret: usize,
commit_input_active: bool,
sections: Vec<SCStateSection>,
active_section: Option<usize>,
previous_active: Option<usize>,
}
struct SCStateSection {
id: SectionId,
rows: Vec<TR>,
collapsed: bool,
scroll_offset: usize,
selected_path: Option<TreePath>,
}
impl SCState {
fn new() -> Self {
Self {
commit_message: String::new(),
commit_caret: 0,
commit_input_active: false,
sections: vec![
SCStateSection {
id: "changes".into(),
rows: make_rows("c", 6),
collapsed: false,
scroll_offset: 0,
selected_path: None,
},
SCStateSection {
id: "staged".into(),
rows: make_rows("s", 4),
collapsed: false,
scroll_offset: 0,
selected_path: None,
},
SCStateSection {
id: "worktrees".into(),
rows: make_rows("w", 2),
collapsed: false,
scroll_offset: 0,
selected_path: None,
},
],
active_section: None,
previous_active: None,
}
}
fn build_view(&self) -> MultiSectionView {
let sections = self
.sections
.iter()
.enumerate()
.map(|(idx, s)| {
let aux = if idx == 0 {
Some(SectionAux::Input(InlineInput {
id: WidgetId::new("commit"),
text: self.commit_message.clone(),
caret: self.commit_caret,
placeholder: Some("Commit message".to_string()),
has_focus: self.commit_input_active,
}))
} else {
None
};
let size = if idx == 0 {
SectionSize::Fixed(8)
} else {
SectionSize::EqualShare
};
Section {
id: s.id.clone(),
header: SectionHeader {
title: StyledText::plain(s.id.to_uppercase()),
show_chevron: true,
..Default::default()
},
body: SectionBody::Tree(TreeView {
id: WidgetId::new(format!("{}-tree", s.id)),
rows: s.rows.clone(),
selection_mode: crate::types::SelectionMode::Single,
selected_path: s.selected_path.clone(),
scroll_offset: s.scroll_offset,
style: Default::default(),
has_focus: !self.commit_input_active
&& self.active_section == Some(idx),
}),
aux,
size,
collapsed: s.collapsed,
min_size: None,
max_size: None,
}
})
.collect();
MultiSectionView {
id: WidgetId::new("sc"),
sections,
active_section: self.active_section,
axis: Axis::Vertical,
allow_resize: false,
allow_collapse: true,
scroll_mode: ScrollMode::PerSection,
has_focus: true,
panel_scroll: 0.0,
}
}
/// Click router mirroring `examples/msv_sc_panel.rs::SCSidebar::click`.
/// Aux→focus input; Chevron→toggle collapsed + activate;
/// TitleArea→activate w/o select; outside→blur input.
fn click(&mut self, x: f32, y: f32, area: TuiRect) {
let view = self.build_view();
let layout = tui_msv_layout(&view, area);
match layout.hit_test(x, y) {
MultiSectionViewHit::Aux {
kind: AuxHit::Input,
..
} => {
self.previous_active = self.active_section;
self.commit_input_active = true;
self.active_section = None;
}
MultiSectionViewHit::Header {
section,
kind: HeaderHit::Chevron,
} => {
self.commit_input_active = false;
self.active_section = Some(section);
self.sections[section].collapsed = !self.sections[section].collapsed;
}
MultiSectionViewHit::Header {
section,
kind: HeaderHit::TitleArea,
} => {
self.commit_input_active = false;
self.active_section = Some(section);
}
MultiSectionViewHit::Body { section } => {
self.commit_input_active = false;
self.active_section = Some(section);
}
_ => {
self.commit_input_active = false;
}
}
}
fn type_char(&mut self, c: char) {
if !self.commit_input_active {
return;
}
let mut chars: Vec<char> = self.commit_message.chars().collect();
chars.insert(self.commit_caret.min(chars.len()), c);
self.commit_message = chars.into_iter().collect();
self.commit_caret += 1;
}
fn backspace(&mut self) {
if !self.commit_input_active || self.commit_caret == 0 {
return;
}
let mut chars: Vec<char> = self.commit_message.chars().collect();
chars.remove(self.commit_caret - 1);
self.commit_message = chars.into_iter().collect();
self.commit_caret -= 1;
}
fn blur_input(&mut self) {
self.commit_input_active = false;
self.active_section = self.previous_active.or(Some(0));
}
}
/// Helper: read a buffer row left-to-right.
fn buf_row(buf: &Buffer, y: u16) -> String {
let area = buf.area;
(area.x..area.x + area.width)
.map(|x| cell_char(buf, x, y))
.collect()
}
// ── 1. Aux input keystroke routing ───────────────────────────────────
//
// After focus + typing, the host's commit_message + caret reflect
// the chars entered, AND the painted aux row shows the typed text.
// Catches both state-mutation drift and paint-doesn't-read-state
// bugs.
/// Aux-row click focuses the commit input. Then typed chars
/// update host state AND appear in the painted aux row.
#[test]
fn consumer_sc_input_keystroke_updates_aux_text_and_caret() {
let area = TuiRect::new(0, 0, 30, 24);
let mut buf = Buffer::empty(area);
let mut state = SCState::new();
// Click on the aux row to focus the input.
let view = state.build_view();
let layout = tui_msv_layout(&view, area);
let aux_b = layout.sections[0]
.aux_bounds
.expect("section 0 has aux=Input");
state.click(aux_b.x + 1.0, aux_b.y + 0.5, area);
assert!(
state.commit_input_active,
"click on aux should focus the commit input"
);
// Type "hi".
state.type_char('h');
state.type_char('i');
assert_eq!(state.commit_message, "hi");
assert_eq!(state.commit_caret, 2);
// Paint and verify aux row shows the typed text.
let view = state.build_view();
draw_multi_section_view(&mut buf, area, &view, &Theme::default(), false);
let aux_y = aux_b.y.round() as u16;
let painted = buf_row(&buf, aux_y);
assert!(
painted.starts_with("hi"),
"aux row {} should start with typed 'hi', got {painted:?}",
aux_y
);
// Backspace — host state and paint both update.
state.backspace();
assert_eq!(state.commit_message, "h");
assert_eq!(state.commit_caret, 1);
let mut buf2 = Buffer::empty(area);
draw_multi_section_view(
&mut buf2,
area,
&state.build_view(),
&Theme::default(),
false,
);
let painted = buf_row(&buf2, aux_y);
assert!(
painted.starts_with("h ") || painted.starts_with("h"),
"aux row {} after backspace should start with 'h', got {painted:?}",
aux_y
);
}
/// Click outside the aux row blurs the input. Locks the focus
/// transition contract: a click on a header (or anywhere else)
/// drops input focus.
#[test]
fn consumer_sc_click_outside_aux_blurs_input() {
let area = TuiRect::new(0, 0, 30, 24);
let mut state = SCState::new();
// Focus the input.
let view = state.build_view();
let layout = tui_msv_layout(&view, area);
let aux_b = layout.sections[0].aux_bounds.unwrap();
state.click(aux_b.x + 1.0, aux_b.y + 0.5, area);
assert!(state.commit_input_active);
// Click on section 1's header.
let header1 = layout.sections[1].header_bounds;
state.click(header1.x + 5.0, header1.y + 0.5, area);
assert!(
!state.commit_input_active,
"click outside aux should blur the input"
);
}
/// Esc (blur) restores the active section that was captured when the
/// input gained focus. If no section was active before, defaults to 0.
#[test]
fn consumer_sc_blur_restores_previous_active_section() {
let area = TuiRect::new(0, 0, 30, 24);
let mut state = SCState::new();
// Activate section 1 via header click.
let view = state.build_view();
let layout = tui_msv_layout(&view, area);
let header1 = layout.sections[1].header_bounds;
state.click(header1.x + 5.0, header1.y + 0.5, area);
assert_eq!(state.active_section, Some(1));
// Click aux to focus input.
let view = state.build_view();
let layout = tui_msv_layout(&view, area);
let aux_b = layout.sections[0].aux_bounds.unwrap();
state.click(aux_b.x + 1.0, aux_b.y + 0.5, area);
assert!(state.commit_input_active);
assert_eq!(state.active_section, None);
// Blur — should restore section 1.
state.blur_input();
assert!(!state.commit_input_active);
assert_eq!(
state.active_section,
Some(1),
"blur should restore the previously-active section"
);
}
/// When no section was active before focusing the input, blur
/// defaults to section 0 (matches Tab-from-none behaviour).
#[test]
fn consumer_sc_blur_defaults_to_section_0_when_no_previous() {
let area = TuiRect::new(0, 0, 30, 24);
let mut state = SCState::new();
assert_eq!(state.active_section, None);
// Click aux directly (no prior section activation).
let view = state.build_view();
let layout = tui_msv_layout(&view, area);
let aux_b = layout.sections[0].aux_bounds.unwrap();
state.click(aux_b.x + 1.0, aux_b.y + 0.5, area);
assert!(state.commit_input_active);
// Blur — should default to section 0.
state.blur_input();
assert_eq!(
state.active_section,
Some(0),
"blur with no previous active should default to section 0"
);
}
// ── 2. Chevron toggle round-trip ─────────────────────────────────────
//
// Section starts expanded ('▾'). Click the chevron at the painted
// glyph position; assert collapsed=true and paint flips to '▸'.
// Click again; assert expanded again. Catches any drift between
// the chevron's painted position and the chevron hit region.
#[test]
fn consumer_sc_chevron_click_toggles_collapsed_round_trip() {
let area = TuiRect::new(0, 0, 30, 24);
let mut buf = Buffer::empty(area);
let mut state = SCState::new();
// Section 1 starts expanded.
assert!(!state.sections[1].collapsed);
// Paint and find the chevron in section 1's header row.
// Default TreeStyle shows '▾' for expanded, '▸' for collapsed.
let view = state.build_view();
let layout = tui_msv_layout(&view, area);
draw_multi_section_view(&mut buf, area, &view, &Theme::default(), false);
let header_y = layout.sections[1].header_bounds.y.round() as u16;
let painted = buf_row(&buf, header_y);
assert!(
painted.starts_with('▾'),
"section 1 header should paint expanded chevron '▾' at start, got {painted:?}"
);
// Click the chevron at painted column 0.
state.click(0.5, header_y as f32 + 0.5, area);
assert!(
state.sections[1].collapsed,
"chevron click should toggle collapsed=true"
);
// Re-paint; chevron flips to '▸'.
let mut buf = Buffer::empty(area);
let view = state.build_view();
let layout = tui_msv_layout(&view, area);
draw_multi_section_view(&mut buf, area, &view, &Theme::default(), false);
let header_y = layout.sections[1].header_bounds.y.round() as u16;
let painted = buf_row(&buf, header_y);
assert!(
painted.starts_with('▸'),
"section 1 header should paint collapsed chevron '▸' after toggle, got {painted:?}"
);
// Second click flips back.
state.click(0.5, header_y as f32 + 0.5, area);
assert!(
!state.sections[1].collapsed,
"second chevron click should toggle collapsed=false"
);
}
// ── 3. Collapsed section paints header only ──────────────────────────
//
// When section 1 is collapsed, its inner Tree row prefixes
// (e.g. "s0", "s1") must not appear anywhere in the buffer.
// Catches "collapsed section still paints body" bugs in the
// rasteriser.
#[test]
fn consumer_sc_collapsed_section_paints_header_only() {
let area = TuiRect::new(0, 0, 30, 24);
let mut buf = Buffer::empty(area);
let mut state = SCState::new();
state.sections[1].collapsed = true;
let view = state.build_view();
draw_multi_section_view(&mut buf, area, &view, &Theme::default(), false);
// Scan every row: no row should contain any of section 1's
// item text ("s0".."s3"). The header text "STAGED" is fine.
for y in 0..area.height {
let row = buf_row(&buf, y);
for r in 0..state.sections[1].rows.len() {
let needle = format!("s{}", r);
assert!(
!row.contains(&needle),
"collapsed section's body item '{}' painted at row {}: {row:?}",
needle,
y
);
}
}
}
// ── 4. No click anywhere returns Body for a collapsed section ────────
//
// Locks the acceptance-criterion-3 semantics: a collapsed section
// has no body hit region. The y range that *would* be its body
// (if expanded) is occupied by the next section. Walk every cell
// in the view; assert hit_test never returns Body{collapsed_idx}.
#[test]
fn consumer_sc_collapsed_body_never_hit_testable() {
let area = TuiRect::new(0, 0, 30, 24);
let mut state = SCState::new();
state.sections[1].collapsed = true;
let view = state.build_view();
let layout = tui_msv_layout(&view, area);
for y in 0..area.height {
for x in 0..area.width {
let hit = layout.hit_test(x as f32, y as f32);
assert!(
!matches!(hit, MultiSectionViewHit::Body { section: 1 }),
"click at ({}, {}) returned Body{{1}} despite section 1 collapsed",
x,
y
);
}
}
}
// ── 5. Dynamic section count: layout still snaps integer cells ───────
//
// Acceptance criterion 5: layout works across a range of section
// counts. Sweep 1..=8 sections; assert (a) every bound is
// integer-aligned (cell_quantum=1.0), (b) total resolved size
// never exceeds bounds.height. Mixes Fixed(8) + EqualShare to
// exercise the same shape the SC panel uses.
#[test]
fn consumer_sc_dynamic_section_count_layout_snaps_integer_cells() {
for n in 1..=8 {
let area = TuiRect::new(0, 0, 30, 30);
let mut state = SCState::new();
state.sections.clear();
for i in 0..n {
state.sections.push(SCStateSection {
id: format!("s{i}"),
rows: make_rows("r", 4),
collapsed: false,
scroll_offset: 0,
selected_path: None,
});
}
let view = state.build_view();
let layout = tui_msv_layout(&view, area);
for s in &layout.sections {
assert_eq!(
s.header_bounds.y.round(),
s.header_bounds.y,
"n={}: section {} header y not integer-aligned: {}",
n,
s.section_idx,
s.header_bounds.y
);
assert_eq!(
s.body_bounds.height.round(),
s.body_bounds.height,
"n={}: section {} body height not integer-aligned: {}",
n,
s.section_idx,
s.body_bounds.height
);
}
let total: f32 = layout.sections.iter().map(|s| s.resolved_size).sum();
assert!(
total <= area.height as f32 + 0.001,
"n={n}: total resolved size {total} exceeds bounds height {}",
area.height
);
}
}
// ── 6. Mixed Form + Tree section round-trip ────────────────────────────
//
// Paints a Form section above a Tree section, finds the painted form
// field labels and tree row text, hit-tests the coordinates, and
// asserts each hit lands in the correct section with the correct body
// type. Validates the SidebarSystem → MSV → TUI pipeline end-to-end.
use crate::primitives::form::{FieldKind, Form, FormField};
fn form_section(id: &str, fields: Vec<FormField>, size: SectionSize) -> Section {
Section {
id: id.into(),
header: SectionHeader {
title: StyledText::plain(id.to_uppercase()),
show_chevron: false,
..Default::default()
},
body: SectionBody::Form(Form {
id: WidgetId::new(format!("{}-form", id)),
fields,
focused_field: None,
scroll_offset: 0,
has_focus: false,
}),
aux: None,
size,
collapsed: false,
min_size: None,
max_size: None,
}
}
#[test]
fn mixed_form_tree_paint_click_round_trip() {
let area = TuiRect::new(0, 0, 40, 12);
let mut buf = Buffer::empty(area);
let fields = vec![
FormField {
id: WidgetId::new("query"),
label: StyledText::plain("Query"),
kind: FieldKind::TextInput {
value: "hello".into(),
placeholder: String::new(),
cursor: None,
selection_anchor: None,
},
hint: StyledText::default(),
disabled: false,
validation: None,
},
FormField {
id: WidgetId::new("case"),
label: StyledText::plain("Case"),
kind: FieldKind::Toggle { value: true },
hint: StyledText::default(),
disabled: false,
validation: None,
},
];
let v = view_with(vec![
form_section("search", fields, SectionSize::Content),
tree_section(
"results",
&["file1.rs", "file2.rs", "file3.rs"],
SectionSize::EqualShare,
),
]);
let layout = paint_then_layout(&mut buf, area, &v, &Theme::default(), false);
// Verify both sections painted their headers.
let search_header_y = find_row_with(&buf, "SEARCH").expect("SEARCH header not painted");
let results_header_y = find_row_with(&buf, "RESULTS").expect("RESULTS header not painted");
assert!(
results_header_y > search_header_y,
"RESULTS header should be below SEARCH header"
);
// Verify form field labels are painted.
let query_y = find_row_with(&buf, "Query").expect("Query field label not painted");
let case_y = find_row_with(&buf, "Case").expect("Case field label not painted");
assert!(
query_y > search_header_y && query_y < results_header_y,
"Query field should be in SEARCH section body"
);
assert!(
case_y > search_header_y && case_y < results_header_y,
"Case field should be in SEARCH section body"
);
// Verify tree rows are painted.
let file1_y = find_row_with(&buf, "file1.rs").expect("file1.rs tree row not painted");
assert!(
file1_y > results_header_y,
"file1.rs should be in RESULTS section body"
);
// Round-trip: hit-test at form field row → Body { section: 0 }.
let hit = layout.hit_test(5.0, query_y as f32);
match hit {
MultiSectionViewHit::Body { section, .. } => assert_eq!(
section, 0,
"click at Query row hit section {section}, expected 0"
),
other => panic!(
"click at Query row returned {:?}, expected Body{{0}}",
other
),
}
// Round-trip: hit-test at tree row → Body { section: 1 }.
let hit = layout.hit_test(5.0, file1_y as f32);
match hit {
MultiSectionViewHit::Body { section, .. } => assert_eq!(
section, 1,
"click at file1.rs row hit section {section}, expected 1"
),
other => panic!(
"click at file1.rs row returned {:?}, expected Body{{1}}",
other
),
}
// Round-trip: hit-test at headers → Header { section: N }.
let hit = layout.hit_test(5.0, search_header_y as f32);
assert!(
matches!(hit, MultiSectionViewHit::Header { section: 0, .. }),
"click at SEARCH header returned {:?}",
hit
);
let hit = layout.hit_test(5.0, results_header_y as f32);
assert!(
matches!(hit, MultiSectionViewHit::Header { section: 1, .. }),
"click at RESULTS header returned {:?}",
hit
);
}
#[test]
fn form_toggle_group_items_individually_clickable_in_msv() {
use crate::primitives::form::{FormHit, ToggleGroupItem};
let area = TuiRect::new(0, 0, 40, 6);
let mut buf = Buffer::empty(area);
let fields = vec![FormField {
id: WidgetId::new("flags"),
label: StyledText::plain(""),
kind: FieldKind::ToggleGroup {
toggles: vec![
ToggleGroupItem {
id: WidgetId::new("case"),
label: "Aa".into(),
value: false,
},
ToggleGroupItem {
id: WidgetId::new("regex"),
label: ".*".into(),
value: true,
},
],
},
hint: StyledText::default(),
disabled: false,
validation: None,
}];
let v = view_with(vec![form_section("opts", fields, SectionSize::EqualShare)]);
let layout = paint_then_layout(&mut buf, area, &v, &Theme::default(), false);
let s = &layout.sections[0];
let body_b = s.body_bounds;
// Find the row with the toggles — scan for "Aa" painted text.
let toggle_y = find_row_with(&buf, "Aa").expect("ToggleGroup items not painted");
// The click should land in the body.
let hit = layout.hit_test(5.0, toggle_y as f32);
assert!(
matches!(hit, MultiSectionViewHit::Body { section: 0 }),
"click at toggle row returned {:?}, expected Body{{0}}",
hit
);
// Now hit-test the Form layout inside the body to verify
// individual items are reachable.
if let SectionBody::Form(f) = &v.sections[0].body {
let form_layout = crate::tui::form::tui_form_layout(
f,
TuiRect::new(0, 0, body_b.width as u16, body_b.height as u16),
);
// First item should be individually hit-testable.
let vis = &form_layout.visible_fields[0];
assert!(
!vis.item_bounds.is_empty(),
"ToggleGroup should have per-item bounds in form layout"
);
let (first_id, first_rect) = &vis.item_bounds[0];
assert_eq!(first_id, &WidgetId::new("case"));
let hit = form_layout.hit_test(first_rect.x + 0.5, first_rect.y + 0.5);
assert_eq!(
hit,
FormHit::Field(WidgetId::new("case")),
"hit-test at first toggle item should return its individual ID"
);
} else {
panic!("expected Form body");
}
}
#[test]
fn form_toggle_value_paints_correctly() {
let area = TuiRect::new(0, 0, 40, 6);
let mut buf = Buffer::empty(area);
let fields = vec![FormField {
id: WidgetId::new("toggle"),
label: StyledText::plain("Enabled"),
kind: FieldKind::Toggle { value: true },
hint: StyledText::default(),
disabled: false,
validation: None,
}];
let v = view_with(vec![form_section("opts", fields, SectionSize::EqualShare)]);
draw_multi_section_view(&mut buf, area, &v, &Theme::default(), false);
let toggle_y = find_row_with(&buf, "Enabled").expect("Toggle field not painted");
let row = row_text(&buf, toggle_y);
assert!(
row.contains("[x]"),
"toggle value=true should paint [x], got row: {row:?}"
);
}
// `paint_empty_body` centers the empty-state message using
// `line.visible_width()` (display-width-aware). Pin that the painted
// extent of a CJK message agrees with `visible_width()` exactly, so it
// lands with equal left/right margins.
#[test]
fn empty_body_centers_cjk_message_by_display_width_not_char_count() {
let area = TuiRect::new(0, 0, 20, 3);
let mut buf = Buffer::empty(area);
let empty = EmptyBody {
text: StyledText::plain("日本語"),
..Default::default()
};
assert_eq!(empty.text.visible_width(), 6);
paint_empty_body(&mut buf, area, &empty, &Theme::default());
// total=1 line, start_y = 0 + (3 - 1) / 2 = 1.
let y = 1;
// x_start = 0 + (20 - 6) / 2 = 7.
assert_eq!(cell_char(&buf, 7, y), '日');
assert_eq!(buf[(8u16, y)].symbol(), "");
assert_eq!(cell_char(&buf, 9, y), '本');
assert_eq!(buf[(10u16, y)].symbol(), "");
assert_eq!(cell_char(&buf, 11, y), '語');
assert_eq!(buf[(12u16, y)].symbol(), "");
// Equal margins on both sides: nothing painted before col 7 or at/
// after col 13 (7 + visible_width) on the message row.
for x in 0..7 {
assert_eq!(
cell_char(&buf, x, y),
' ',
"unexpected content left of center at col {x}"
);
}
for x in 13..20 {
assert_eq!(
cell_char(&buf, x, y),
' ',
"unexpected content right of the CJK message's measured width at col {x}"
);
}
}
}