ratcn 0.0.1

Themeable terminal UI components and interaction runtime for Ratatui
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
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
use std::fmt;

use ratatui::{
    buffer::Buffer,
    layout::Rect,
    style::{Color, Style},
    text::{Line, Span, Text},
    widgets::Widget,
};

use crate::Theme;
use crate::color::{DISABLED_DIM, FIELD_FOCUS_LIGHTEN, FIELD_HOVER_LIGHTEN, dim, lighten};
use crate::linear_nav::{self, NavOutcome, ScrollStep};
use crate::list_core::{
    self, ListItem, ListItemState, RowViewport, SCROLL_STEP, WheelPark, fit_to_height,
};
use crate::runtime::{
    Component, Event, EventCtx, EventResult, KeyCode, KeyEvent, MouseButton, MouseKind, RenderCtx,
    ScrollDirection,
};
use crate::selection_indicator;
use crate::text_width::display_width;

const ROW_FOCUS_LIGHTEN: u16 = 15;

/// Every color a list can paint.
///
/// Two different meanings of "focused" appear in these names, and getting them
/// straight is most of understanding this struct:
///
/// - **The list itself has focus** — the whole widget is the active control.
///   That picks the list's own backdrop: `focused_background` instead of
///   `background`.
/// - **The list is hovered** — `hovered_background` replaces either backdrop,
///   so moving the pointer remains visible even when the list already has focus.
/// - **A row is the focused row** — the cursor is on it. That styles one row:
///   `focused_foreground` on `focused_row_background`.
/// - **The list is disabled** — `disabled_background` replaces all three
///   backdrops, whatever the focus and hover state.
///
/// Rows are then colored by two independent facts, whether the cursor is on the
/// row and whether the row is selected, giving four combinations. Disabled
/// overrides all of them. Note that a row only counts as focused when the list
/// has focus too, so moving focus away leaves the cursor row painted as an
/// ordinary (or selected) row rather than as a highlight.
///
/// [`from_theme`](Self::from_theme) derives all of this from a [`Theme`]; build
/// one by hand only for colors the theme cannot express, and pass it via
/// [`List::style`] or [`ListWidget::style`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ListStyle {
    /// Text color of an ordinary row.
    pub foreground: Color,
    /// Backdrop of the list while it does not have focus. Disabled wins over
    /// all three backdrops: a disabled list uses
    /// [`disabled_background`](Self::disabled_background) throughout.
    pub background: Color,
    /// Backdrop of the list while it has focus.
    pub focused_background: Color,
    /// Backdrop of the list while it is hovered. Hover wins over focus.
    pub hovered_background: Color,
    /// Text color of a selected row the cursor is not on. Selection has no fill
    /// of its own; the row keeps the list's backdrop.
    pub selected_foreground: Color,
    /// Text color of the cursor row when it is not selected.
    pub focused_foreground: Color,
    /// Fill behind the cursor row when it is not selected.
    pub focused_row_background: Color,
    /// Text color of the cursor row when it is also selected.
    pub selected_focused_foreground: Color,
    /// Fill behind the cursor row when it is also selected.
    pub selected_focused_background: Color,
    /// The `●`/`■` marker on a selected row, in the default row rendering.
    pub selected_marker: Color,
    /// The `○`/`□` marker on an unselected row, in the default row rendering.
    pub unselected_marker: Color,
    /// Text color of a disabled row, and of its marker.
    pub disabled_foreground: Color,
    /// Fill behind a disabled row.
    pub disabled_background: Color,
}

impl ListStyle {
    /// A neutral style using plain ANSI colors, for painting without a
    /// [`Theme`]. Prefer [`from_theme`](Self::from_theme) when one is available.
    #[must_use]
    pub const fn fallback() -> Self {
        Self {
            foreground: Color::Reset,
            background: Color::Reset,
            focused_background: Color::Reset,
            hovered_background: Color::DarkGray,
            selected_foreground: Color::Black,
            focused_foreground: Color::Reset,
            focused_row_background: Color::Cyan,
            selected_focused_foreground: Color::Black,
            selected_focused_background: Color::Cyan,
            selected_marker: Color::LightGreen,
            unselected_marker: Color::DarkGray,
            disabled_foreground: Color::DarkGray,
            disabled_background: Color::Reset,
        }
    }

    /// Derive every list color from `theme`.
    ///
    /// The focus and cursor-row fills are lightened from the theme's field
    /// color rather than being separate theme entries, so a custom theme only
    /// supplies the base colors and the list stays consistent with the rest of
    /// the UI.
    #[must_use]
    pub const fn from_theme(theme: &Theme) -> Self {
        let focused_background = lighten(theme.field, FIELD_FOCUS_LIGHTEN);
        let hovered_background = lighten(theme.field, FIELD_HOVER_LIGHTEN);
        let focused_row_background = lighten(focused_background, ROW_FOCUS_LIGHTEN);
        Self {
            foreground: theme.muted_foreground,
            background: theme.field,
            focused_background,
            hovered_background,
            selected_foreground: theme.foreground,
            focused_foreground: theme.muted_foreground,
            focused_row_background,
            selected_focused_foreground: theme.foreground,
            selected_focused_background: focused_row_background,
            selected_marker: theme.primary,
            unselected_marker: theme.muted_foreground,
            disabled_foreground: theme.muted_foreground,
            disabled_background: dim(theme.field, theme.surface, DISABLED_DIM),
        }
    }

    const fn resolve_surface(&self, focused: bool, hovered: bool, disabled: bool) -> Color {
        if disabled {
            // The same backdrop the rows get, so a list shorter than its area
            // does not show a seam past its last item — and the same answer
            // `SelectStyle` gives for a disabled trigger.
            self.disabled_background
        } else if hovered {
            self.hovered_background
        } else if focused {
            self.focused_background
        } else {
            self.background
        }
    }

    fn resolve_row(
        &self,
        focused: bool,
        selected: bool,
        disabled: bool,
        background: Color,
    ) -> Style {
        if disabled {
            return Style::default()
                .fg(self.disabled_foreground)
                .bg(self.disabled_background);
        }
        let (foreground, background) = match (focused, selected) {
            (true, true) => (
                self.selected_focused_foreground,
                self.selected_focused_background,
            ),
            (true, false) => (self.focused_foreground, self.focused_row_background),
            // Selection has no fill: keep whichever backdrop the list has.
            (false, true) => (self.selected_foreground, background),
            (false, false) => (self.foreground, background),
        };
        Style::default().fg(foreground).bg(background)
    }
}

/// A list that only draws — an ordinary ratatui [`Widget`] with no focus,
/// events, or state.
///
/// **Usable in any ratatui app.** Nothing here depends on
/// [`Ratcn`](crate::runtime::Ratcn) or the component layer: render it directly
/// and keep driving selection and scrolling however you already do.
///
/// Rows are pre-rendered [`Text`]s — one per item, each free to span several
/// lines — and everything else is addressed by *item index*: which item the
/// cursor is on, which are selected, which are disabled.
/// Explicit colors in the supplied text are preserved; row styles provide the
/// colors for text that does not set its own.
/// That makes it easy to drive from any data you like, but it also means the
/// widget has no idea what a row means — reorder your data and the indices refer
/// to different things.
///
/// Use [`List`] instead when you want that handled: it keys focus and selection
/// by a value you choose, and adds keyboard and mouse handling. It paints
/// through this widget internally.
///
/// Scrolling is an input: pass the index of the topmost visible item with
/// [`scroll_offset`](Self::scroll_offset) each frame. The widget paints exactly what it is
/// told and never adjusts the offset, so whatever owns it — your app, or the
/// [`List`] component — is the only scroll policy in play.
///
/// # Sizing and row heights
///
/// There is no measurement method, because there is nothing to measure: the
/// widget is area-driven. It paints into the area it is given, top to bottom,
/// stopping when the area runs out. How much room a list deserves is a layout
/// question the caller answers with a ratatui `Constraint`, not something the
/// list can answer from its items.
///
/// Rows may be any height — each item is a [`Text`], so one item may be one
/// line and the next three, and the widget paints each at its own height.
/// Keeping them uniform is the caller's job whenever anything maps a screen row
/// back to an item, because the offset arithmetic counts *items*, not lines:
/// [`scroll_offset`](Self::scroll_offset) skips a number of items, so mixed
/// heights make the row a click lands on no longer correspond to the item that
/// arithmetic names. The [`List`] component takes that job on — it normalizes
/// every item to its [`row_height`](List::row_height) with
/// [`fit_to_height`](crate::list_core::fit_to_height), padding short rows and
/// truncating tall ones — which is why clicking, paging, and wheel scrolling
/// are exact there.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ListWidget<'a> {
    items: &'a [Text<'static>],
    scroll_offset: usize,
    focused_row: Option<usize>,
    selected_rows: &'a [usize],
    disabled_rows: &'a [bool],
    focused: bool,
    hovered: bool,
    disabled: bool,
    style: ListStyle,
    focus_symbol: &'a str,
}

impl<'a> ListWidget<'a> {
    /// A list of `items`, nothing focused or selected, using
    /// [`ListStyle::fallback`].
    #[must_use]
    pub const fn new(items: &'a [Text<'static>]) -> Self {
        Self {
            items,
            scroll_offset: 0,
            focused_row: None,
            selected_rows: &[],
            disabled_rows: &[],
            focused: false,
            hovered: false,
            disabled: false,
            style: ListStyle::fallback(),
            focus_symbol: "",
        }
    }

    /// Take colors from `theme`.
    #[must_use]
    pub const fn themed(mut self, theme: &Theme) -> Self {
        self.style = ListStyle::from_theme(theme);
        self
    }

    /// Use these exact colors, ignoring any theme.
    #[must_use]
    pub const fn style(mut self, style: ListStyle) -> Self {
        self.style = style;
        self
    }

    /// Index of the topmost visible item. Defaults to 0. Matches
    /// [`SelectWidget::scroll_offset`](crate::SelectWidget::scroll_offset).
    ///
    /// Items before it are skipped, items after it paint top to bottom until
    /// the area runs out. The widget never adjusts this value — keep-visible
    /// and clamping policy belong to the caller (see
    /// [`linear_nav`](crate::linear_nav) for the arithmetic [`List`] uses).
    #[must_use]
    pub const fn scroll_offset(mut self, scroll_offset: usize) -> Self {
        self.scroll_offset = scroll_offset;
        self
    }

    /// Which row the cursor is on, by index.
    ///
    /// Only highlighted while the list is also [`focused`](Self::focused) — an
    /// unfocused list shows no cursor, so two lists side by side cannot both
    /// look active.
    #[must_use]
    pub const fn focused_row(mut self, focused_row: Option<usize>) -> Self {
        self.focused_row = focused_row;
        self
    }

    /// Indices of the selected rows. Pass one index for single selection, or
    /// several for multi-selection; the widget does not care which you mean.
    ///
    /// This is an index list, not a mask: selection is sparse — usually zero or
    /// one row, any number under multi-selection — so you name the selected
    /// rows rather than flag every row. Contrast
    /// [`disabled_rows`](Self::disabled_rows), which describes every row and is
    /// therefore a positional mask.
    #[must_use]
    pub const fn selected_rows(mut self, selected_rows: &'a [usize]) -> Self {
        self.selected_rows = selected_rows;
        self
    }

    /// A disabled flag per row, positionally matched to the items. Entries past
    /// the end of the slice read as enabled, so a short slice is fine.
    ///
    /// This is a positional mask, not an index list: disabledness is a property
    /// of every row, usually derived straight from the items, so one flag per
    /// item lines up without a lookup. It matches
    /// [`TabsWidget::disabled_tabs`](crate::TabsWidget::disabled_tabs), while
    /// sparse [`selected_rows`](Self::selected_rows) stays an index list.
    #[must_use]
    pub const fn disabled_rows(mut self, disabled_rows: &'a [bool]) -> Self {
        self.disabled_rows = disabled_rows;
        self
    }

    /// Paint as the focused control: the focus backdrop, the cursor row
    /// highlighted, and the focus symbol shown.
    #[must_use]
    pub const fn focused(mut self, focused: bool) -> Self {
        self.focused = focused;
        self
    }

    /// Paint the list's hovered backdrop. Hover wins when the list is also
    /// focused, while cursor-row visibility remains controlled by
    /// [`focused`](Self::focused).
    #[must_use]
    pub const fn hovered(mut self, hovered: bool) -> Self {
        self.hovered = hovered;
        self
    }

    /// Paint the whole list as disabled, overriding per-row styling.
    #[must_use]
    pub const fn disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }

    /// A marker drawn in front of the cursor row, such as `"> "`. Empty by
    /// default. Only shown while the list is focused and enabled.
    ///
    /// It occupies columns to the left of every row, so a wide symbol narrows
    /// the space available for labels.
    #[must_use]
    pub const fn focus_symbol(mut self, focus_symbol: &'a str) -> Self {
        self.focus_symbol = focus_symbol;
        self
    }
}

impl Widget for ListWidget<'_> {
    fn render(self, area: Rect, buf: &mut Buffer) {
        let area = area.intersection(buf.area);
        if area.width == 0 || area.height == 0 {
            return;
        }
        // The whole widget area first, so rows past the last item keep the
        // list backdrop.
        buf.set_style(
            area,
            Style::default()
                .fg(self.style.foreground)
                .bg(self
                    .style
                    .resolve_surface(self.focused, self.hovered, self.disabled)),
        );
        // The focus symbol occupies a column in front of every row, reserved
        // only while there is a cursor to point at — the same frames the
        // cursor row is highlighted.
        let cursor_shown = self.focused && !self.disabled && self.focused_row.is_some();
        let symbol_width = if cursor_shown {
            u16::try_from(display_width(self.focus_symbol)).unwrap_or(u16::MAX)
        } else {
            0
        };
        let text_x = area.x.saturating_add(symbol_width).min(area.right());
        let text_width = area.width.saturating_sub(symbol_width);

        let mut y = area.y;
        for (index, item) in self.items.iter().enumerate().skip(self.scroll_offset) {
            if y >= area.bottom() {
                break;
            }
            let height = u16::try_from(item.lines.len().max(1))
                .unwrap_or(u16::MAX)
                .min(area.bottom() - y);
            let row_area = Rect::new(area.x, y, area.width, height);
            // The row's colors fill its full width; the item's own spans then
            // patch over them, so explicit colors in the text are preserved
            // and everything else inherits the row style.
            buf.set_style(row_area, self.row_style(index));
            if cursor_shown && self.focused_row == Some(index) {
                Span::raw(self.focus_symbol).render(row_area, buf);
            }
            item.render(Rect::new(text_x, y, text_width, height), buf);
            y = y.saturating_add(height);
        }
    }
}

impl ListWidget<'_> {
    fn row_style(&self, index: usize) -> Style {
        self.style.resolve_row(
            self.focused && self.focused_row == Some(index),
            self.selected_rows.contains(&index),
            self.disabled || self.disabled_rows.get(index).copied().unwrap_or(false),
            self.style
                .resolve_surface(self.focused, self.hovered, self.disabled),
        )
    }
}

type ReadFn<S, T> = Box<dyn Fn(&S) -> Option<T>>;
type MultiSelectionFn<S, T> = Box<dyn Fn(&S, &T) -> bool>;
type OnChangeFn<T, M> = Box<dyn Fn(T) -> M>;
type OnFocusChangeFn<T, M> = Box<dyn Fn(T, usize) -> M>;
type ScrollFn<S> = Box<dyn Fn(&S) -> usize>;
type RenderItemFn<S, T> = Box<dyn for<'a> Fn(&S, ListItemState<'a, T>) -> Text<'static>>;
type StyleFn = Box<dyn Fn(&Theme) -> ListStyle>;

/// A scrollable list of items, declared with
/// [`render_component`](crate::runtime::RenderCtx::render_component).
///
/// # Cursor and selection are different things
///
/// The **cursor** (called *item focus* here) is where the user is looking. Arrow
/// keys, Home, End, and Page keys move it, and moving it is not a choice —
/// nothing is committed. **Selection** is the choice: Enter, Space, or a left
/// click commits the row under the cursor.
///
/// Keeping them apart is what lets a user browse a list without changing
/// anything, which is why they are two separate bindings rather than one
/// "current item".
///
/// # Bindings
///
/// Each binding is a pair — a reader for the current value and a constructor for
/// the message that changes it — passed in one call so a reader and writer
/// pointing at different fields cannot drift apart. Everything is keyed by your
/// item value, never by row index, so filtering or reordering the list keeps the
/// same item current.
///
/// Item values must be unique within each declaration. Duplicate values panic
/// during declaration because focus, selection, and pointer actions would
/// otherwise be ambiguous.
///
/// - [`item_focus`](Self::item_focus) — the cursor. Without it the list is
///   paint- and pointer-only, is not a keyboard focus stop, and ignores keys.
/// - [`selection`](Self::selection) — single selection.
/// - [`multi_selection`](Self::multi_selection) — checkbox-style selection.
///   Mutually exclusive with `selection`.
/// - [`scroll`](Self::scroll) — the scroll offset, if the app wants to own it.
///
/// Disabled items are dimmed and skipped by both keyboard and mouse.
///
/// While the list has keyboard focus, typing a printable character jumps the
/// cursor to the next enabled item whose label starts with it,
/// case-insensitively, cycling past the end — the native-select typeahead
/// convention. Matching is single-character only: a multi-character buffer
/// would need a timeout to reset, and this library never reads a clock. A
/// character matching no label is ignored, so it can bubble as an app hotkey.
///
/// ```
/// use ratcn::{List, ListItem};
///
/// # #[derive(Clone, Copy, PartialEq)]
/// # struct TaskId(u64);
/// # struct AppState { focused_task: Option<TaskId>, selected_task: Option<TaskId> }
/// # enum Msg { TaskFocused(TaskId, usize), TaskSelected(TaskId) }
/// let _list = List::new([
///     ListItem::new(TaskId(7), "Write spec"),
///     ListItem::new(TaskId(3), "Ship it").disabled(true),
/// ])
/// .item_focus(|s: &AppState| s.focused_task, Msg::TaskFocused)
/// .selection(|s: &AppState| s.selected_task, Msg::TaskSelected);
/// ```
pub struct List<T, S, M> {
    items: Vec<ListItem<T>>,
    focused_item: Option<ReadFn<S, T>>,
    on_focus_change: Option<OnFocusChangeFn<T, M>>,
    selected: Option<ReadFn<S, T>>,
    on_select: Option<OnChangeFn<T, M>>,
    selected_many: Option<MultiSelectionFn<S, T>>,
    on_toggle: Option<OnChangeFn<T, M>>,
    scroll: Option<ScrollFn<S>>,
    on_scroll_change: Option<Box<dyn Fn(usize) -> M>>,
    disabled: bool,
    render_item: Option<RenderItemFn<S, T>>,
    style: Option<StyleFn>,
    focus_symbol: String,
    /// Row height plus the painted offset — render-derived runtime state kept
    /// so hit-testing and wheel arithmetic work against what is on screen,
    /// never a second copy of app-owned scroll.
    viewport: RowViewport,
    cursor_visible: bool,
}

impl<T: fmt::Debug, S, M> fmt::Debug for List<T, S, M> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("List")
            .field("items", &self.items)
            .field("item_focus", &self.focused_item.is_some())
            .field("selection", &self.selected.is_some())
            .field("multi_selection", &self.selected_many.is_some())
            .field("style", &self.style.is_some())
            .field("disabled", &self.disabled)
            .finish_non_exhaustive()
    }
}

impl<T, S, M> List<T, S, M> {
    /// A list of `items`, with no bindings yet.
    ///
    /// Accepts anything that converts into a [`ListItem`], so `["one", "two"]`
    /// works for a quick list of strings and
    /// `[ListItem::new(id, label), ...]` for anything keyed by a real value.
    #[must_use]
    pub fn new(items: impl IntoIterator<Item = impl Into<ListItem<T>>>) -> Self {
        Self {
            items: items.into_iter().map(Into::into).collect(),
            focused_item: None,
            on_focus_change: None,
            selected: None,
            on_select: None,
            selected_many: None,
            on_toggle: None,
            scroll: None,
            on_scroll_change: None,
            disabled: false,
            render_item: None,
            style: None,
            focus_symbol: String::new(),
            viewport: RowViewport::new(1),
            cursor_visible: false,
        }
    }

    /// Bind the cursor: where to read it from, and what message moves it.
    ///
    /// `read` returns the value of the item the cursor is on, or `None` when it
    /// is nowhere yet — in which case the first arrow key moves it onto the
    /// first enabled item. `on_change` is called with the value moved to and the
    /// resulting top-item scroll offset. Store both in one update when
    /// [`scroll`](Self::scroll) is bound; an unbound list can ignore the offset.
    ///
    /// Moving the cursor commits nothing; see [`selection`](Self::selection).
    /// Without this binding the list remains available for painting, bound
    /// scrolling, and pointer selection, but is not focusable and does not
    /// consume keyboard navigation or Enter.
    #[must_use]
    pub fn item_focus(
        mut self,
        read: impl Fn(&S) -> Option<T> + 'static,
        on_change: impl Fn(T, usize) -> M + 'static,
    ) -> Self {
        self.focused_item = Some(Box::new(read));
        self.on_focus_change = Some(Box::new(on_change));
        self
    }

    /// Bind single selection: at most one item chosen at a time.
    ///
    /// `read` returns the selected value, or `None` for nothing selected.
    /// `on_select` is called with the item the user committed — Enter or Space
    /// on the cursor row, or a left click on a row.
    ///
    /// A pointer click can commit a row without a preceding pointer-move event.
    /// When [`item_focus`](Self::item_focus) is also bound, the update handling
    /// this message should store the committed value as both selection and item
    /// focus so later keyboard input continues from the clicked row.
    ///
    /// Selecting is an action, not a movement, which is why this is `on_select`
    /// and not `on_selection_change`.
    ///
    /// # Panics
    ///
    /// Rendering panics if this is combined with
    /// [`multi_selection`](Self::multi_selection). A list is one mode or the
    /// other; supporting both at once would make "what does Enter do" depend on
    /// which binding was declared last.
    #[must_use]
    pub fn selection(
        mut self,
        read: impl Fn(&S) -> Option<T> + 'static,
        on_select: impl Fn(T) -> M + 'static,
    ) -> Self {
        self.selected = Some(Box::new(read));
        self.on_select = Some(Box::new(on_select));
        self
    }

    /// Bind multi-selection: any number of items chosen, checkbox style.
    ///
    /// `read` is a predicate asked "is this one selected?" for each item, rather
    /// than a function returning a collection. That way your app can store the
    /// selection however it likes — a `HashSet`, a flag on each record, a
    /// computed rule — without converting it every frame. `on_toggle` is called
    /// with the item the user flipped; your update function decides whether that
    /// means adding or removing.
    ///
    /// When [`item_focus`](Self::item_focus) is also bound, the update handling
    /// a pointer toggle should store this value as item focus as well. A click
    /// need not be preceded by a pointer-move event.
    ///
    /// Switches the default row markers from `●`/`○` to `■`/`□`.
    ///
    /// # Panics
    ///
    /// Rendering panics if this is combined with
    /// [`selection`](Self::selection).
    #[must_use]
    pub fn multi_selection(
        mut self,
        read: impl Fn(&S, &T) -> bool + 'static,
        on_toggle: impl Fn(T) -> M + 'static,
    ) -> Self {
        self.selected_many = Some(Box::new(read));
        self.on_toggle = Some(Box::new(on_toggle));
        self
    }

    /// Bind the requested scroll offset — the index of the topmost visible item.
    ///
    /// Before paint, the list adjusts the requested value to keep the focused
    /// item visible. Focus movement computes the same resulting offset from the
    /// current app value and passes it to the [`item_focus`](Self::item_focus)
    /// message constructor, so its update can persist cursor and scroll
    /// atomically. Hit-testing and wheel input use the actual painted offset.
    ///
    /// The wheel is the exception to keeping the cursor visible: it scrolls
    /// the view and leaves the cursor where it is, so the cursor may scroll
    /// out of sight — the behavior a scrollable list has everywhere else. It
    /// emits the offset one notch away from the painted one, and consumes the
    /// event without emitting when the app already holds that value. Paint
    /// resumes scrolling the cursor into view as soon as the cursor moves
    /// again. Render-driven adjustment itself cannot emit a message.
    ///
    /// Only needed when something outside the list has to know or change where
    /// it is scrolled to, such as a scrollbar drawn alongside it. Left unbound,
    /// the list owns the offset itself — keyboard movement and the wheel both
    /// still scroll it, exactly as they do when bound; there is simply no
    /// message and no app-held value.
    #[must_use]
    pub fn scroll(
        mut self,
        read: impl Fn(&S) -> usize + 'static,
        on_change: impl Fn(usize) -> M + 'static,
    ) -> Self {
        self.scroll = Some(Box::new(read));
        self.on_scroll_change = Some(Box::new(on_change));
        self
    }

    /// Draw each row yourself instead of using the default marker-and-label
    /// line.
    ///
    /// The closure gets app state and a [`ListItemState`] describing the row,
    /// and returns what to paint. Use it for columns, secondary text, per-row
    /// icons — anything the default cannot express. The resolved [`ListStyle`]
    /// is painted beneath the returned text, so unstyled text inherits row-state
    /// colors while explicit `Text`, `Line`, and `Span` colors are preserved.
    ///
    /// Return a [`Line`] for the usual one-line row, or a [`Text`] for a taller
    /// one — a name above a subtitle, say. A multi-line row also needs
    /// [`row_height`](Self::row_height) set to match, since every item must be
    /// the same height for clicks to land on the right one.
    #[must_use]
    pub fn render_item<R: Into<Text<'static>>>(
        mut self,
        f: impl for<'a> Fn(&S, ListItemState<'a, T>) -> R + 'static,
    ) -> Self {
        self.render_item = Some(Box::new(move |state, row| f(state, row).into()));
        self
    }

    /// How many terminal rows each item occupies. Defaults to 1.
    ///
    /// Raise it when [`render_item`](Self::render_item) returns more than one
    /// line — a name above a subtitle, say. Every item gets the same height,
    /// which is what keeps clicking, paging, and scrolling exact: a returned
    /// [`Text`] is padded with blank lines or truncated to fit, so the row the
    /// user clicks is always the item the runtime thinks it is.
    ///
    /// A height of 0 is treated as 1.
    #[must_use]
    pub const fn row_height(mut self, rows: u16) -> Self {
        self.viewport = RowViewport::new(rows);
        self
    }

    /// A marker drawn in front of the cursor row, such as `"> "`. Empty by
    /// default, and only shown while the list has keyboard focus or hover.
    #[must_use]
    pub fn focus_symbol(mut self, symbol: impl Into<String>) -> Self {
        self.focus_symbol = symbol.into();
        self
    }

    /// Replace the theme-derived [`ListStyle`].
    ///
    /// The closure receives the active theme each render, so a style built from
    /// its argument follows theme switches. Ignore the argument (`|_| STYLE`)
    /// for colors that should stay fixed.
    #[must_use]
    pub fn style(mut self, style: impl Fn(&Theme) -> ListStyle + 'static) -> Self {
        self.style = Some(Box::new(style));
        self
    }

    /// Dim the whole list and stop it responding.
    ///
    /// A disabled list is not focusable, so Tab skips it — as does a list that
    /// is empty or has every row disabled, since there would be nothing for the
    /// cursor to land on. Disable individual rows with [`ListItem::disabled`].
    #[must_use]
    pub const fn disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }
}

impl<T: Clone + PartialEq, S, M> List<T, S, M> {
    fn disabled_at(&self, index: usize) -> bool {
        list_core::disabled_at(&self.items, index)
    }

    fn focused_index(&self, state: &S) -> Option<usize> {
        list_core::index_of(&self.items, &(self.focused_item.as_ref()?)(state)?)
    }

    fn selected_index(&self, state: &S) -> Option<usize> {
        list_core::index_of(&self.items, &(self.selected.as_ref()?)(state)?)
    }

    fn selected_rows(&self, state: &S) -> Vec<usize> {
        if let Some(selected_many) = &self.selected_many {
            return self
                .items
                .iter()
                .enumerate()
                .filter_map(|(index, item)| selected_many(state, item.value()).then_some(index))
                .collect();
        }
        self.selected_index(state).into_iter().collect()
    }

    fn move_focus(&self, index: usize, state: &S, area: Rect) -> EventResult<M> {
        match &self.on_focus_change {
            Some(on_change) => EventResult::Emit(on_change(
                self.items[index].value().clone(),
                self.offset_for_focus(state, area, index),
            )),
            None => EventResult::Ignored,
        }
    }

    fn offset_for_focus(&self, state: &S, area: Rect, index: usize) -> usize {
        let current = self
            .scroll
            .as_ref()
            .map_or(self.viewport.painted_offset(), |read| read(state));
        self.viewport
            .cursor_visible_offset(area, self.items.len(), current, Some(index))
    }

    fn select(&self, index: usize) -> EventResult<M> {
        if let Some(on_select) = &self.on_select {
            return EventResult::Emit(on_select(self.items[index].value().clone()));
        }
        if let Some(on_toggle) = &self.on_toggle {
            return EventResult::Emit(on_toggle(self.items[index].value().clone()));
        }
        EventResult::Ignored
    }

    fn scroll_view(
        &mut self,
        direction: ScrollDirection,
        state: &S,
        area: Rect,
        ctx: &mut EventCtx<'_>,
    ) -> EventResult<M> {
        let step = match direction {
            ScrollDirection::Up => ScrollStep::Up,
            ScrollDirection::Down => ScrollStep::Down,
            ScrollDirection::Left | ScrollDirection::Right => return EventResult::Ignored,
        };
        let painted = self.viewport.painted_offset();
        // The wheel moves the view, never the cursor: the offset is clamped
        // to the item range only, so the cursor may scroll out of sight.
        let next = linear_nav::wheel_offset(
            self.items.len(),
            self.viewport.visible_items(area),
            painted,
            step,
            SCROLL_STEP,
        );
        // Park the view and the cursor it left behind, so the next render
        // honors this offset instead of scrolling the cursor back into view.
        // The park lives on the list's identity and outlives this instance,
        // which is what lets an unbound list scroll at all.
        ctx.transient::<WheelPark>()
            .park(next, self.focused_index(state));
        // Keep this retained instance's hit-testing aligned with the offset
        // the next paint will use.
        self.viewport.record_painted_offset(next);
        let Some(on_change) = &self.on_scroll_change else {
            return EventResult::Consumed;
        };
        let current = self.scroll.as_ref().map_or(painted, |read| read(state));
        if current == next {
            EventResult::Consumed
        } else {
            EventResult::Emit(on_change(next))
        }
    }

    fn handle_key(&self, key: KeyEvent, state: &S, area: Rect) -> EventResult<M> {
        if self.focused_item.is_none()
            || linear_nav::first_enabled(self.items.len(), |i| self.disabled_at(i)).is_none()
        {
            return EventResult::Ignored;
        }
        let cursor = self.focused_index(state);
        // Navigation is asked first because it owns the Ctrl chords that the
        // modifier gate below rejects.
        if let Some(outcome) = linear_nav::nav_key_target(
            key,
            self.items.len(),
            cursor,
            self.viewport.visible_items(area).max(1),
            |i| self.disabled_at(i),
        ) {
            return match outcome {
                NavOutcome::Move(target) => self.move_focus(target, state, area),
                NavOutcome::Stay => EventResult::Consumed,
            };
        }
        if linear_nav::has_reserved_modifier(key) {
            return EventResult::Ignored;
        }
        if matches!(key.code, KeyCode::Enter | KeyCode::Char(' ')) {
            return match cursor {
                Some(index) if !self.disabled_at(index) => self.select(index),
                _ => EventResult::Ignored,
            };
        }
        // Anything else — including every letter but `j` and `k` — bubbles, so
        // the app keeps its single-key hotkeys while a list has focus.
        EventResult::Ignored
    }
}

impl<T: Clone + PartialEq, S, M> Component<S, M> for List<T, S, M> {
    fn prepare(&mut self, _state: &S) {
        list_core::assert_unique_values(self.items.iter().map(ListItem::value), "List");
        assert!(
            !(self.selected.is_some() && self.selected_many.is_some()),
            "List::selection(...) and List::multi_selection(...) cannot be used together; choose one selection mode"
        );
    }

    fn render(&mut self, ctx: &mut RenderCtx<'_, '_, S, M>) {
        let area = ctx.area();
        let state = ctx.state();
        let focused_row = self.focused_index(state);
        let selected_rows = self.selected_rows(state);
        let disabled_rows: Vec<bool> = self.items.iter().map(ListItem::is_disabled).collect();
        let style = self.style.as_ref().map_or_else(
            || ListStyle::from_theme(ctx.theme),
            |style| style(ctx.theme),
        );
        self.cursor_visible = ctx.focused || ctx.hovered;
        let selection_mode = if self.selected_many.is_some() {
            Some(true)
        } else if self.selected.is_some() {
            Some(false)
        } else {
            None
        };
        let rows_per_item = self.viewport.rows_per_item();
        let items: Vec<Text<'static>> = self
            .items
            .iter()
            .enumerate()
            .map(|(index, item)| {
                let row = ListItemState {
                    index,
                    value: item.value(),
                    label: item.label(),
                    focused: self.cursor_visible && focused_row == Some(index),
                    selected: selected_rows.contains(&index),
                    disabled: self.disabled || item.is_disabled(),
                };
                let text = match &self.render_item {
                    Some(render_item) => render_item(state, row),
                    None => default_item_line(&row, selection_mode, &style),
                };
                fit_to_height(text, rows_per_item)
            })
            .collect();
        // The wheel parks the view against the cursor it left behind. While
        // that cursor has not moved, the parked offset is painted as it is —
        // the wheel may leave the cursor off-screen. Once the cursor moves
        // again (keys, hover, the app), it is scrolled back into view. A
        // bound scroll offset always wins over the park: the app owns it.
        let mut park = ctx
            .transient_mut::<WheelPark>()
            .map_or_else(WheelPark::default, |park| {
                park.settle(focused_row);
                *park
            });
        let requested_offset = self
            .scroll
            .as_ref()
            .map_or_else(|| park.offset(), |scroll| scroll(state));
        let offset = self.viewport.cursor_visible_offset(
            area,
            self.items.len(),
            requested_offset,
            park.cursor_to_show(focused_row),
        );
        park.record(offset);
        if let Some(stored) = ctx.transient_mut::<WheelPark>() {
            *stored = park;
        }
        self.viewport.record_painted_offset(offset);
        ctx.render_widget(
            ListWidget::new(&items)
                .scroll_offset(offset)
                .focused_row(focused_row)
                .selected_rows(&selected_rows)
                .disabled_rows(&disabled_rows)
                .style(style)
                .focused(self.cursor_visible)
                .hovered(ctx.hovered)
                .disabled(self.disabled)
                .focus_symbol(&self.focus_symbol),
            area,
        );
    }

    fn handle_event(&mut self, event: &Event, state: &S, ctx: &mut EventCtx<'_>) -> EventResult<M> {
        if self.disabled || self.items.is_empty() {
            return EventResult::Ignored;
        }
        let area = ctx.area();
        match event {
            Event::Mouse(mouse) => match mouse.kind {
                // The runtime focuses an unhandled primary down on the hit
                // component. Consume disabled rows so that fallback cannot
                // focus the list when its disabled content was clicked.
                MouseKind::Down(MouseButton::Left) => {
                    match self
                        .viewport
                        .row_at(area, self.items.len(), mouse.column, mouse.row)
                    {
                        Some(index) if self.disabled_at(index) => EventResult::Consumed,
                        _ => EventResult::Ignored,
                    }
                }
                // Hover moves the cursor from the first motion over a row, as
                // in `Select`. `row_at` already rejects anything outside the
                // list, so no paint-state gate is needed here; whether the
                // cursor is *shown* stays a paint decision.
                MouseKind::Moved => {
                    match self
                        .viewport
                        .row_at(area, self.items.len(), mouse.column, mouse.row)
                    {
                        Some(index) if self.disabled_at(index) => EventResult::Ignored,
                        Some(index) if Some(index) != self.focused_index(state) => {
                            self.move_focus(index, state, area)
                        }
                        Some(_) => EventResult::Consumed,
                        None => EventResult::Ignored,
                    }
                }
                MouseKind::Click(MouseButton::Left) => {
                    match self
                        .viewport
                        .row_at(area, self.items.len(), mouse.column, mouse.row)
                    {
                        Some(index) if self.disabled_at(index) => EventResult::Ignored,
                        Some(index) if self.selected.is_some() || self.selected_many.is_some() => {
                            self.select(index)
                        }
                        Some(index) => self.move_focus(index, state, area),
                        None => EventResult::Ignored,
                    }
                }
                MouseKind::Scroll(direction) => self.scroll_view(direction, state, area, ctx),
                _ => EventResult::Ignored,
            },
            Event::Key(key) => self.handle_key(*key, state, area),
            _ => EventResult::Ignored,
        }
    }

    fn is_focusable(&self, _state: &S) -> bool {
        self.focused_item.is_some()
            && !self.disabled
            && linear_nav::first_enabled(self.items.len(), |i| self.disabled_at(i)).is_some()
    }
}

fn default_item_line<T>(
    row: &ListItemState<'_, T>,
    selection_mode: Option<bool>,
    style: &ListStyle,
) -> Text<'static> {
    let Some(multiple) = selection_mode else {
        return Text::from(row.label.to_string());
    };
    let marker = selection_indicator::marker(row.selected, multiple);
    let marker_color = selection_indicator::color(
        row.disabled,
        row.selected,
        selection_indicator::MarkerColors {
            disabled: style.disabled_foreground,
            selected: style.selected_marker,
            unselected: style.unselected_marker,
        },
    );
    Text::from(Line::from(vec![
        Span::styled(format!(" {marker}"), Style::default().fg(marker_color)),
        Span::raw(" "),
        Span::raw(row.label.to_string()),
    ]))
}

#[cfg(test)]
mod tests {
    use std::panic::{AssertUnwindSafe, catch_unwind};

    use ratatui::{Terminal, backend::TestBackend, style::Modifier};

    use super::*;
    use crate::runtime::{ChildId, MouseEvent, Ratcn};

    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    enum Task {
        A,
        B,
        C,
        D,
        E,
        F,
    }

    #[derive(Debug, PartialEq)]
    enum Msg {
        Focused(Task, usize),
        Selected(Task),
        Toggled(Task),
        Scrolled(usize),
        ComponentFocus(crate::runtime::FocusState),
        Hover(crate::runtime::HoverState),
        Pressed,
    }

    #[derive(Default)]
    struct State {
        focused: Option<Task>,
        selected: Option<Task>,
        toggled: Vec<Task>,
        scroll: usize,
        component_focus: crate::runtime::FocusState,
        hover: crate::runtime::HoverState,
    }

    /// Drives a retained `Ratcn` surface through a `TestBackend`.
    struct TestBackendDriver {
        terminal: Terminal<TestBackend>,
        ratcn: Ratcn<State, Msg>,
    }

    impl TestBackendDriver {
        fn new(width: u16, height: u16) -> Self {
            Self {
                terminal: Terminal::new(TestBackend::new(width, height)).expect("terminal"),
                ratcn: Ratcn::new(),
            }
        }

        fn render(&mut self, state: &State, items: impl IntoIterator<Item = ListItem<Task>>) {
            let items: Vec<_> = items.into_iter().collect();
            let theme = Theme::default_dark();
            self.terminal
                .draw(|frame| {
                    let area = frame.area();
                    self.ratcn.render(frame, state, &theme, |ctx| {
                        ctx.render_component(
                            ChildId::Static("list"),
                            List::new(items.clone())
                                .item_focus(|state: &State| state.focused, Msg::Focused)
                                .selection(|state: &State| state.selected, Msg::Selected)
                                .scroll(|state: &State| state.scroll, Msg::Scrolled)
                                .focus_symbol(">"),
                            area,
                        );
                    });
                })
                .expect("draw");
        }

        fn event(&mut self, event: Event, state: &State) -> EventResult<Msg> {
            self.ratcn.handle_event(event, state)
        }

        fn row(&self, row: u16) -> String {
            let buffer = self.terminal.backend().buffer();
            let width = usize::from(buffer.area.width);
            buffer.content[usize::from(row) * width..]
                .iter()
                .take(width)
                .map(ratatui::buffer::Cell::symbol)
                .collect()
        }

        fn cell(&self, column: u16, row: u16) -> &ratatui::buffer::Cell {
            self.terminal
                .backend()
                .buffer()
                .cell((column, row))
                .expect("cell")
        }
    }

    fn item(value: Task, label: &str) -> ListItem<Task> {
        ListItem::new(value, label)
    }

    /// Renders a two-row-per-item list, so a click's screen row and its item
    /// index deliberately disagree.
    struct TallListDriver {
        terminal: Terminal<TestBackend>,
        ratcn: Ratcn<State, Msg>,
    }

    impl TallListDriver {
        const ROW_HEIGHT: u16 = 2;

        fn new(width: u16, height: u16) -> Self {
            Self {
                terminal: Terminal::new(TestBackend::new(width, height)).expect("terminal"),
                ratcn: Ratcn::new(),
            }
        }

        fn render(&mut self, state: &State, items: &[ListItem<Task>]) {
            let theme = Theme::default_dark();
            self.terminal
                .draw(|frame| {
                    let area = frame.area();
                    self.ratcn.render(frame, state, &theme, |ctx| {
                        ctx.render_component(
                            ChildId::Static("list"),
                            List::new(items.to_vec())
                                .item_focus(|state: &State| state.focused, Msg::Focused)
                                .selection(|state: &State| state.selected, Msg::Selected)
                                .row_height(Self::ROW_HEIGHT)
                                .render_item(|_state: &State, row| {
                                    Text::from(vec![
                                        Line::from(row.label.to_string()),
                                        Line::from("  subtitle"),
                                    ])
                                }),
                            area,
                        );
                    });
                })
                .expect("draw");
        }

        fn event(&mut self, event: Event, state: &State) -> EventResult<Msg> {
            self.ratcn.handle_event(event, state)
        }
    }

    // A two-line row means screen row 1 still belongs to item 0. Dividing by the
    // row height is what keeps a click on a subtitle from selecting its
    // neighbour.
    #[test]
    fn clicking_a_second_line_selects_the_item_that_owns_it() {
        let state = State::default();
        let items = vec![item(Task::A, "Alpha"), item(Task::B, "Bravo")];
        let mut driver = TallListDriver::new(20, 6);
        driver.render(&state, &items);

        assert_eq!(
            driver.event(mouse(MouseKind::Click(MouseButton::Left), 2, 1), &state),
            EventResult::Emit(Msg::Selected(Task::A)),
            "the subtitle line belongs to the first item"
        );
        assert_eq!(
            driver.event(mouse(MouseKind::Click(MouseButton::Left), 2, 2), &state),
            EventResult::Emit(Msg::Selected(Task::B)),
            "the second item starts two rows down"
        );
    }

    #[test]
    fn trailing_partial_row_does_not_target_an_invisible_item() {
        let state = State::default();
        let items = vec![
            item(Task::A, "Alpha"),
            item(Task::B, "Bravo"),
            item(Task::C, "Charlie"),
        ];
        let mut driver = TallListDriver::new(20, 5);
        driver.render(&state, &items);

        assert_eq!(
            driver.event(mouse(MouseKind::Click(MouseButton::Left), 2, 4), &state),
            EventResult::Ignored,
            "a trailing row that cannot fit a complete item is not interactive"
        );
    }

    // Paging counts items that fit, not screen rows: a 6-row area holds three
    // two-row items, so PageDown from the first lands on the third.
    #[test]
    fn paging_counts_items_that_fit_not_screen_rows() {
        let state = State {
            focused: Some(Task::A),
            ..State::default()
        };
        let items = vec![
            item(Task::A, "Alpha"),
            item(Task::B, "Bravo"),
            item(Task::C, "Charlie"),
            item(Task::D, "Delta"),
            item(Task::E, "Echo"),
        ];
        let mut driver = TallListDriver::new(20, 6);
        driver.render(&state, &items);

        assert_eq!(
            driver.event(key(KeyCode::PageDown), &state),
            EventResult::Emit(Msg::Focused(Task::D, 1)),
            "three items fit, so a page is three items"
        );
    }

    // A render_item closure returning the wrong line count must not shift later
    // items; padding and truncation keep every item exactly row_height tall.
    #[test]
    fn rows_are_padded_and_truncated_to_the_declared_height() {
        let short = fit_to_height(Text::from("one"), 3);
        assert_eq!(short.lines.len(), 3);
        assert_eq!(short.lines[0].to_string(), "one");
        assert_eq!(short.lines[2].to_string(), "");

        let long = fit_to_height(
            Text::from(vec![Line::from("a"), Line::from("b"), Line::from("c")]),
            2,
        );
        assert_eq!(long.lines.len(), 2);
        assert_eq!(long.lines[1].to_string(), "b");
    }

    // Zero would divide by zero in hit-testing, so it is clamped to one row.
    #[test]
    fn zero_row_height_is_treated_as_one() {
        let list: List<Task, State, Msg> = List::new([item(Task::A, "Alpha")]).row_height(0);
        assert_eq!(list.viewport.rows_per_item(), 1);
    }
    fn key(code: KeyCode) -> Event {
        Event::Key(KeyEvent::new(code))
    }
    fn ctrl_key(ch: char) -> Event {
        Event::Key(KeyEvent {
            code: KeyCode::Char(ch),
            modifiers: crate::runtime::Modifiers {
                ctrl: true,
                ..crate::runtime::Modifiers::NONE
            },
        })
    }
    fn mouse(kind: MouseKind, column: u16, row: u16) -> Event {
        Event::Mouse(MouseEvent {
            kind,
            column,
            row,
            modifiers: crate::runtime::Modifiers::NONE,
        })
    }

    // A fixed selected fill used to match the resting backdrop but not the
    // focused one, so focusing the list left the selected row a dark band.
    #[test]
    fn a_selected_row_keeps_the_rest_focus_or_hover_backdrop() {
        let items = [Text::from("selected"), Text::from("other")];
        let mut style = ListStyle::fallback();
        style.background = Color::Blue;
        style.focused_background = Color::Green;
        style.hovered_background = Color::Magenta;
        style.selected_foreground = Color::Yellow;
        let area = Rect::new(0, 0, 10, 2);

        for (focused, hovered, backdrop) in [
            (false, false, Color::Blue),
            (true, false, Color::Green),
            (false, true, Color::Magenta),
            (true, true, Color::Magenta),
        ] {
            let mut buffer = Buffer::empty(area);
            Widget::render(
                ListWidget::new(&items)
                    .selected_rows(&[0])
                    // Row 1 is the cursor, so row 0 is selected but not focused.
                    .focused_row(Some(1))
                    .focused(focused)
                    .hovered(hovered)
                    .style(style),
                area,
                &mut buffer,
            );

            let selected = buffer.cell((0, 0)).expect("selected cell");
            assert_eq!(
                selected.bg, backdrop,
                "selected row should match the list backdrop (focused: {focused}, hovered: {hovered})"
            );
            assert_eq!(selected.fg, Color::Yellow, "selection shows in the label");
        }
    }

    #[test]
    fn list_widget_preserves_explicit_text_colors_and_modifiers() {
        let items = [
            Text::from(Span::styled(
                "selected",
                Style::default()
                    .fg(Color::Magenta)
                    .bg(Color::Green)
                    .add_modifier(Modifier::BOLD),
            )),
            Text::from(Span::styled(
                "disabled",
                Style::default()
                    .fg(Color::Cyan)
                    .bg(Color::White)
                    .add_modifier(Modifier::ITALIC),
            )),
        ];
        let mut style = ListStyle::fallback();
        style.selected_foreground = Color::Yellow;
        style.background = Color::Blue;
        style.disabled_foreground = Color::DarkGray;
        style.disabled_background = Color::Red;
        let area = Rect::new(0, 0, 10, 2);
        let mut buffer = Buffer::empty(area);

        Widget::render(
            ListWidget::new(&items)
                .selected_rows(&[0])
                .disabled_rows(&[false, true])
                .style(style),
            area,
            &mut buffer,
        );

        let selected = buffer.cell((0, 0)).expect("selected custom span");
        assert_eq!(selected.fg, Color::Magenta);
        assert_eq!(selected.bg, Color::Green);
        assert!(selected.modifier.contains(Modifier::BOLD));
        let disabled = buffer.cell((0, 1)).expect("disabled custom span");
        assert_eq!(disabled.fg, Color::Cyan);
        assert_eq!(disabled.bg, Color::White);
        assert!(disabled.modifier.contains(Modifier::ITALIC));
    }

    #[test]
    fn default_markers_preserve_selected_and_unselected_colors() {
        let state = State {
            selected: Some(Task::A),
            ..State::default()
        };
        let mut style = ListStyle::fallback();
        style.selected_marker = Color::Yellow;
        style.unselected_marker = Color::Magenta;
        style.selected_foreground = Color::Red;
        style.foreground = Color::Cyan;
        let mut ratcn = Ratcn::new();
        let mut terminal = Terminal::new(TestBackend::new(10, 2)).expect("terminal");
        let theme = Theme::default_dark();

        terminal
            .draw(|frame| {
                let area = frame.area();
                ratcn.render(frame, &state, &theme, |ctx| {
                    ctx.render_component(
                        "list",
                        List::new([item(Task::A, "Alpha"), item(Task::B, "Bravo")])
                            .selection(|state: &State| state.selected, Msg::Selected)
                            .style(move |_| style),
                        area,
                    );
                });
            })
            .expect("draw");

        let buffer = terminal.backend().buffer();
        assert_eq!(
            buffer.cell((1, 0)).expect("selected marker").fg,
            Color::Yellow
        );
        assert_eq!(
            buffer.cell((1, 1)).expect("unselected marker").fg,
            Color::Magenta
        );
    }

    #[test]
    fn interactive_custom_row_colors_preserve_explicit_span_colors() {
        let state = State {
            selected: Some(Task::A),
            ..State::default()
        };
        let mut style = ListStyle::fallback();
        style.selected_foreground = Color::Yellow;
        style.background = Color::Blue;
        style.disabled_foreground = Color::DarkGray;
        style.disabled_background = Color::Red;
        let mut ratcn = Ratcn::new();
        let mut terminal = Terminal::new(TestBackend::new(10, 2)).expect("terminal");
        let theme = Theme::default_dark();

        terminal
            .draw(|frame| {
                let area = frame.area();
                ratcn.render(frame, &state, &theme, |ctx| {
                    ctx.render_component(
                        "list",
                        List::new([
                            item(Task::A, "selected"),
                            item(Task::B, "disabled").disabled(true),
                        ])
                        .selection(|state: &State| state.selected, Msg::Selected)
                        .render_item(|_: &State, row| {
                            let modifier = if row.selected {
                                Modifier::BOLD
                            } else {
                                Modifier::ITALIC
                            };
                            Text::from(Span::styled(
                                row.label.to_string(),
                                Style::default()
                                    .fg(Color::Magenta)
                                    .bg(Color::Green)
                                    .add_modifier(modifier),
                            ))
                        })
                        .style(move |_| style),
                        area,
                    );
                });
            })
            .expect("draw");

        let buffer = terminal.backend().buffer();
        let selected = buffer.cell((0, 0)).expect("selected custom span");
        assert_eq!(selected.fg, Color::Magenta);
        assert_eq!(selected.bg, Color::Green);
        assert!(selected.modifier.contains(Modifier::BOLD));
        let disabled = buffer.cell((0, 1)).expect("disabled custom span");
        assert_eq!(disabled.fg, Color::Magenta);
        assert_eq!(disabled.bg, Color::Green);
        assert!(disabled.modifier.contains(Modifier::ITALIC));
    }

    #[test]
    fn hidden_cursor_paints_the_caller_owned_scroll_offset() {
        let items = [
            Text::from("Alpha"),
            Text::from("Bravo"),
            Text::from("Charlie"),
            Text::from("Delta"),
        ];
        let area = Rect::new(0, 0, 10, 2);

        // An unfocused or disabled list shows no cursor and reserves no focus
        // symbol column, but still paints from the offset it was given.
        for (focused, disabled) in [(false, false), (true, true)] {
            let mut buffer = Buffer::empty(area);

            ListWidget::new(&items)
                .scroll_offset(2)
                .focused_row(Some(3))
                .focused(focused)
                .disabled(disabled)
                .focus_symbol("> ")
                .render(area, &mut buffer);

            assert_eq!(
                buffer.cell((0, 0)).expect("first visible cell").symbol(),
                "C"
            );
        }
    }

    #[test]
    fn string_sugar_keys_items_by_their_labels() {
        let list = List::<String, State, Msg>::new(["Inbox", "Archive"]);
        assert_eq!(list.items[0].value(), "Inbox");
        assert_eq!(list.items[0].label(), "Inbox");
    }

    #[test]
    fn reorder_preserves_focused_and_selected_values() {
        let mut driver = TestBackendDriver::new(20, 3);
        let state = State {
            focused: Some(Task::B),
            selected: Some(Task::B),
            ..State::default()
        };
        driver.render(
            &state,
            [
                item(Task::A, "Alpha"),
                item(Task::B, "Bravo"),
                item(Task::C, "Charlie"),
            ],
        );
        driver.render(
            &state,
            [
                item(Task::C, "Charlie"),
                item(Task::A, "Alpha"),
                item(Task::B, "Bravo"),
            ],
        );

        assert!(driver.row(2).contains("> ● Bravo"));
        assert_eq!(
            driver.event(key(KeyCode::Enter), &state),
            EventResult::Emit(Msg::Selected(Task::B))
        );
    }

    #[test]
    fn filtering_a_focused_value_parks_without_highlighting_or_emitting() {
        let mut driver = TestBackendDriver::new(20, 2);
        let state = State {
            focused: Some(Task::B),
            selected: Some(Task::B),
            ..State::default()
        };
        driver.render(&state, [item(Task::A, "Alpha"), item(Task::B, "Bravo")]);
        driver.render(
            &state,
            [
                item(Task::A, "Alpha").disabled(true),
                item(Task::C, "Charlie"),
            ],
        );

        assert!(!driver.row(0).contains('>'));
        assert!(!driver.row(0).contains(''));
        assert_eq!(
            driver.event(key(KeyCode::Down), &state),
            EventResult::Emit(Msg::Focused(Task::C, 0))
        );
        assert_eq!(
            driver.event(key(KeyCode::End), &state),
            EventResult::Emit(Msg::Focused(Task::C, 0))
        );
    }

    /// A disabled list is one flat backdrop: the rows and the empty space past
    /// the last item agree, so a short list shows no seam.
    #[test]
    fn a_disabled_list_paints_one_backdrop_past_its_last_item() {
        let mut terminal = Terminal::new(TestBackend::new(20, 4)).expect("terminal");
        let mut ratcn = Ratcn::<State, Msg>::new();
        let state = State::default();
        let theme = Theme::default_dark();
        terminal
            .draw(|frame| {
                let area = frame.area();
                ratcn.render(frame, &state, &theme, |ctx| {
                    ctx.render_component(
                        ChildId::Static("list"),
                        List::new([item(Task::A, "Alpha"), item(Task::B, "Bravo")])
                            .item_focus(|state: &State| state.focused, Msg::Focused)
                            .disabled(true),
                        area,
                    );
                });
            })
            .expect("draw");

        let disabled = ListStyle::from_theme(&theme).disabled_background;
        let buffer = terminal.backend().buffer();
        for row in 0..4 {
            assert_eq!(
                buffer.cell((3, row)).expect("cell").bg,
                disabled,
                "row {row} must use the disabled backdrop, item row or not"
            );
        }
    }

    #[test]
    fn disabled_items_are_dimmed_and_ignore_primary_clicks() {
        let mut driver = TestBackendDriver::new(20, 2);
        let state = State::default();
        driver.render(
            &state,
            [
                item(Task::A, "Alpha"),
                item(Task::B, "Bravo").disabled(true),
            ],
        );

        assert_eq!(
            driver.cell(3, 1).bg,
            ListStyle::from_theme(&Theme::default_dark()).disabled_background
        );
        assert_eq!(
            driver.event(mouse(MouseKind::Down(MouseButton::Left), 2, 1), &state),
            EventResult::Consumed
        );
        assert_eq!(
            driver.event(mouse(MouseKind::Up(MouseButton::Left), 2, 1), &state),
            EventResult::Ignored
        );
    }

    #[test]
    fn disabled_rows_consume_pointer_down_and_cursorless_lists_do_not_take_focus() {
        #[derive(Default)]
        struct RoutedState {
            focus: crate::runtime::FocusState,
            selected: Option<Task>,
        }

        #[derive(Debug, PartialEq)]
        enum RoutedMsg {
            Focus(crate::runtime::FocusState),
            Selected(Task),
        }

        let theme = Theme::default_dark();
        let state = RoutedState {
            focus: crate::runtime::FocusState::intent([ChildId::Static("other")]),
            ..RoutedState::default()
        };
        let mut ratcn = Ratcn::new().focus(|state: &RoutedState| &state.focus, RoutedMsg::Focus);
        let mut terminal = Terminal::new(TestBackend::new(20, 3)).expect("terminal");
        terminal
            .draw(|frame| {
                ratcn.render(frame, &state, &theme, |ctx| {
                    ctx.render_component(
                        ChildId::Static("other"),
                        crate::Button::<RoutedMsg>::new("Other"),
                        Rect::new(0, 0, 20, 1),
                    );
                    ctx.render_component(
                        ChildId::Static("list"),
                        List::new([
                            item(Task::A, "Alpha"),
                            item(Task::B, "Bravo").disabled(true),
                        ])
                        .selection(|state: &RoutedState| state.selected, RoutedMsg::Selected),
                        Rect::new(0, 1, 20, 2),
                    );
                });
            })
            .expect("draw");

        assert_eq!(
            ratcn.handle_event(mouse(MouseKind::Down(MouseButton::Left), 1, 2), &state),
            EventResult::Consumed
        );
        assert_eq!(
            state.focus,
            crate::runtime::FocusState::intent([ChildId::Static("other")])
        );
        assert_eq!(
            ratcn.handle_event(mouse(MouseKind::Up(MouseButton::Left), 1, 2), &state),
            EventResult::Ignored
        );

        assert_eq!(
            ratcn.handle_event(mouse(MouseKind::Down(MouseButton::Left), 1, 1), &state),
            EventResult::Ignored
        );
        assert_eq!(
            state.focus,
            crate::runtime::FocusState::intent([ChildId::Static("other")])
        );
        assert_eq!(
            ratcn.handle_event(mouse(MouseKind::Up(MouseButton::Left), 1, 1), &state),
            EventResult::Emit(RoutedMsg::Selected(Task::A))
        );
    }

    fn six_items() -> [ListItem<Task>; 6] {
        [
            item(Task::A, "Alpha"),
            item(Task::B, "Bravo"),
            item(Task::C, "Charlie"),
            item(Task::D, "Delta"),
            item(Task::E, "Echo"),
            item(Task::F, "Foxtrot"),
        ]
    }

    #[test]
    fn the_wheel_scrolls_the_view_and_leaves_the_cursor_behind() {
        let mut driver = TestBackendDriver::new(20, 3);
        let mut state = State {
            focused: Some(Task::A),
            ..State::default()
        };
        driver.render(&state, six_items());
        assert!(driver.row(0).contains("Alpha"), "{}", driver.row(0));

        // One notch scrolls the view by the wheel step. The cursor stays on
        // Alpha, which the wheel is free to scroll out of sight.
        assert_eq!(
            driver.event(
                mouse(MouseKind::Scroll(ScrollDirection::Down), 2, 0),
                &state
            ),
            EventResult::Emit(Msg::Scrolled(3))
        );
        state.scroll = 3;
        driver.render(&state, six_items());
        assert!(
            driver.row(0).contains("Delta"),
            "the wheeled offset survives the redraw: {}",
            driver.row(0)
        );
        assert_eq!(state.focused, Some(Task::A), "the wheel never moves it");

        // Moving the cursor again brings it back into view, and the move
        // carries the resulting offset so one message persists both.
        assert_eq!(
            driver.event(key(KeyCode::Down), &state),
            EventResult::Emit(Msg::Focused(Task::B, 1))
        );
        state.focused = Some(Task::B);
        state.scroll = 1;
        driver.render(&state, six_items());
        assert!(driver.row(0).contains("Bravo"), "{}", driver.row(0));
    }

    #[test]
    fn wheeling_against_a_stale_app_offset_synchronizes_it() {
        let mut driver = TestBackendDriver::new(20, 3);
        let state = State {
            // Render must scroll Foxtrot into view, so the painted offset is
            // 3 while the app still holds 0.
            focused: Some(Task::F),
            ..State::default()
        };
        driver.render(&state, six_items());
        assert!(driver.row(0).contains("Delta"), "{}", driver.row(0));

        // Wheeling up lands on the offset the app already holds, so there is
        // nothing to persist; the next render paints it.
        assert_eq!(
            driver.event(mouse(MouseKind::Scroll(ScrollDirection::Up), 2, 0), &state),
            EventResult::Consumed
        );
        driver.render(&state, six_items());
        assert!(
            driver.row(0).contains("Alpha"),
            "the parked view is painted even though the cursor is off-screen: {}",
            driver.row(0)
        );

        // Wheeling back down computes from the painted offset and emits the
        // value the app is missing.
        assert_eq!(
            driver.event(
                mouse(MouseKind::Scroll(ScrollDirection::Down), 2, 0),
                &state
            ),
            EventResult::Emit(Msg::Scrolled(3))
        );
    }

    #[test]
    fn focus_and_scroll_move_atomically_across_the_viewport_without_redraw() {
        let mut driver = TestBackendDriver::new(20, 3);
        let mut state = State {
            focused: Some(Task::C),
            ..State::default()
        };
        driver.render(
            &state,
            [
                item(Task::A, "Alpha"),
                item(Task::B, "Bravo"),
                item(Task::C, "Charlie"),
                item(Task::D, "Delta"),
                item(Task::E, "Echo"),
                item(Task::F, "Foxtrot"),
            ],
        );

        assert_eq!(
            driver.event(key(KeyCode::Down), &state),
            EventResult::Emit(Msg::Focused(Task::D, 1))
        );
        state.focused = Some(Task::D);
        state.scroll = 1;

        assert_eq!(
            driver.event(key(KeyCode::Down), &state),
            EventResult::Emit(Msg::Focused(Task::E, 2)),
            "the retained component reads focus and scroll from current app state"
        );
        state.focused = Some(Task::E);
        state.scroll = 2;

        assert_eq!(
            driver.event(key(KeyCode::Home), &state),
            EventResult::Emit(Msg::Focused(Task::A, 0))
        );
    }

    /// An unbound list owns its scroll offset the same way `Select`'s panel
    /// does, so the wheel works without any app-held offset.
    #[test]
    fn an_unbound_list_still_scrolls_on_the_wheel() {
        let state = State {
            focused: Some(Task::A),
            ..State::default()
        };
        let theme = Theme::default_dark();
        let mut ratcn = Ratcn::new();
        let mut terminal = Terminal::new(TestBackend::new(20, 3)).expect("terminal");
        let draw = |terminal: &mut Terminal<TestBackend>, ratcn: &mut Ratcn<State, Msg>| {
            terminal
                .draw(|frame| {
                    let area = frame.area();
                    ratcn.render(frame, &state, &theme, |ctx| {
                        ctx.render_component(
                            ChildId::Static("list"),
                            List::new(six_items())
                                .item_focus(|state: &State| state.focused, Msg::Focused),
                            area,
                        );
                    });
                })
                .expect("draw");
        };
        let row = |terminal: &Terminal<TestBackend>, row: u16| -> String {
            let buffer = terminal.backend().buffer();
            (0..buffer.area.width)
                .map(|column| buffer.cell((column, row)).expect("cell").symbol())
                .collect()
        };

        draw(&mut terminal, &mut ratcn);
        assert!(row(&terminal, 0).contains("Alpha"), "{}", row(&terminal, 0));

        assert_eq!(
            ratcn.handle_event(
                mouse(MouseKind::Scroll(ScrollDirection::Down), 2, 0),
                &state
            ),
            EventResult::Consumed,
            "there is no scroll binding, so nothing is emitted"
        );
        draw(&mut terminal, &mut ratcn);
        assert!(
            row(&terminal, 0).contains("Delta"),
            "the wheel scrolled the view and the offset survived the redraw: {}",
            row(&terminal, 0)
        );
    }

    /// Returning the cursor to where the wheel left it must not revive the
    /// parked view: the cursor the user just moved has to stay on screen.
    #[test]
    fn a_released_wheel_park_never_revives() {
        let mut state = State {
            focused: Some(Task::A),
            ..State::default()
        };
        let theme = Theme::default_dark();
        let mut ratcn = Ratcn::new();
        let mut terminal = Terminal::new(TestBackend::new(20, 3)).expect("terminal");
        let draw =
            |terminal: &mut Terminal<TestBackend>, ratcn: &mut Ratcn<State, Msg>, state: &State| {
                terminal
                    .draw(|frame| {
                        let area = frame.area();
                        ratcn.render(frame, state, &theme, |ctx| {
                            ctx.render_component(
                                ChildId::Static("list"),
                                List::new(six_items())
                                    .item_focus(|state: &State| state.focused, Msg::Focused),
                                area,
                            );
                        });
                    })
                    .expect("draw");
            };
        let row = |terminal: &Terminal<TestBackend>, row: u16| -> String {
            let buffer = terminal.backend().buffer();
            (0..buffer.area.width)
                .map(|column| buffer.cell((column, row)).expect("cell").symbol())
                .collect()
        };

        draw(&mut terminal, &mut ratcn, &state);
        ratcn.handle_event(
            mouse(MouseKind::Scroll(ScrollDirection::Down), 2, 0),
            &state,
        );
        draw(&mut terminal, &mut ratcn, &state);
        assert!(row(&terminal, 0).contains("Delta"), "{}", row(&terminal, 0));

        // Move the cursor off the anchor: the view follows it back.
        assert_eq!(
            ratcn.handle_event(key(KeyCode::Down), &state),
            EventResult::Emit(Msg::Focused(Task::B, 1))
        );
        state.focused = Some(Task::B);
        draw(&mut terminal, &mut ratcn, &state);
        assert!(row(&terminal, 0).contains("Bravo"), "{}", row(&terminal, 0));

        // Move it back onto the anchor. The park is spent, so the cursor
        // stays visible instead of the stale parked view returning.
        assert_eq!(
            ratcn.handle_event(key(KeyCode::Up), &state),
            EventResult::Emit(Msg::Focused(Task::A, 0))
        );
        state.focused = Some(Task::A);
        draw(&mut terminal, &mut ratcn, &state);
        assert!(
            row(&terminal, 0).contains("Alpha"),
            "returning to the wheel anchor must not re-park the view: {}",
            row(&terminal, 0)
        );
    }

    /// Hover moves the cursor from the very first pointer motion, with no
    /// paint round-trip first, exactly as it does over a `Select` panel.
    #[test]
    fn the_first_hover_motion_moves_the_cursor() {
        let mut driver = TestBackendDriver::new(20, 3);
        let state = State {
            focused: Some(Task::A),
            ..State::default()
        };
        driver.render(&state, six_items());

        assert_eq!(
            driver.event(mouse(MouseKind::Moved, 2, 1), &state),
            EventResult::Emit(Msg::Focused(Task::B, 0)),
            "an unfocused, not-yet-hovered list still tracks the pointer"
        );
    }

    #[test]
    fn horizontal_wheel_directions_are_ignored() {
        let mut list =
            List::new([item(Task::A, "Alpha")]).scroll(|state: &State| state.scroll, Msg::Scrolled);
        let state = State::default();

        for direction in [ScrollDirection::Left, ScrollDirection::Right] {
            assert_eq!(
                list.handle_event(
                    &mouse(MouseKind::Scroll(direction), 0, 0),
                    &state,
                    &mut EventCtx::default(),
                ),
                EventResult::Ignored
            );
        }
    }

    #[test]
    fn cursorless_list_is_not_a_keyboard_stop_and_ignores_keys() {
        let theme = Theme::default_dark();
        let state = State::default();
        let mut ratcn = Ratcn::new();
        let mut terminal = Terminal::new(TestBackend::new(20, 2)).expect("terminal");
        terminal
            .draw(|frame| {
                ratcn.render(frame, &state, &theme, |ctx| {
                    ctx.render_component(
                        "list",
                        List::new([item(Task::A, "Alpha")])
                            .selection(|state: &State| state.selected, Msg::Selected),
                        Rect::new(0, 0, 20, 1),
                    );
                    ctx.render_component(
                        "button",
                        crate::Button::new("Next").on_press(|| Msg::Pressed),
                        Rect::new(0, 1, 20, 1),
                    );
                });
            })
            .expect("draw");

        assert_eq!(ratcn.focus_path(&[ChildId::Static("list")]), None);
        assert_eq!(
            ratcn.handle_event(key(KeyCode::Enter), &state),
            EventResult::Emit(Msg::Pressed)
        );
    }

    #[test]
    fn no_selection_mode_draws_neutral_rows_and_reports_unselected_custom_state() {
        let theme = Theme::default_dark();
        let state = State {
            focused: Some(Task::A),
            ..State::default()
        };
        let mut ratcn = Ratcn::new();
        let mut terminal = Terminal::new(TestBackend::new(20, 2)).expect("terminal");
        terminal
            .draw(|frame| {
                ratcn.render(frame, &state, &theme, |ctx| {
                    ctx.render_component(
                        "plain",
                        List::new([item(Task::A, "Alpha")])
                            .item_focus(|state: &State| state.focused, Msg::Focused),
                        Rect::new(0, 0, 20, 1),
                    );
                    ctx.render_component(
                        "custom",
                        List::new([item(Task::B, "Bravo")]).render_item(|_, row| {
                            Line::from(format!("{} selected={}", row.label, row.selected))
                        }),
                        Rect::new(0, 1, 20, 1),
                    );
                });
            })
            .expect("draw");

        let buffer = terminal.backend().buffer();
        let row = |y: usize| {
            buffer.content[y * 20..(y + 1) * 20]
                .iter()
                .map(ratatui::buffer::Cell::symbol)
                .collect::<String>()
        };
        assert!(row(0).starts_with("Alpha"));
        assert!(!row(0).contains(['', '', '', '']));
        assert!(row(1).starts_with("Bravo selected=false"));
    }

    #[test]
    fn hovered_list_paints_pointer_moved_item_focus_without_keyboard_focus() {
        let theme = Theme::default_dark();
        let mut state = State {
            focused: Some(Task::A),
            component_focus: crate::runtime::FocusState::intent(["other"]),
            ..State::default()
        };
        let mut ratcn = Ratcn::new()
            .focus(|state: &State| &state.component_focus, Msg::ComponentFocus)
            .hover(|state: &State| &state.hover, Msg::Hover);
        let mut terminal = Terminal::new(TestBackend::new(20, 3)).expect("terminal");
        let render =
            |terminal: &mut Terminal<TestBackend>, ratcn: &mut Ratcn<State, Msg>, state: &State| {
                terminal
                    .draw(|frame| {
                        ratcn.render(frame, state, &theme, |ctx| {
                            ctx.render_component(
                                "other",
                                crate::Button::<Msg>::new("Other"),
                                Rect::new(0, 0, 20, 1),
                            );
                            ctx.render_component(
                                "list",
                                List::new([item(Task::A, "Alpha"), item(Task::B, "Bravo")])
                                    .item_focus(|state: &State| state.focused, Msg::Focused)
                                    .render_item(|_, row| {
                                        Line::from(format!(
                                            "{} {}",
                                            if row.focused { "focused" } else { "idle" },
                                            row.label
                                        ))
                                    })
                                    .focus_symbol(">"),
                                Rect::new(0, 1, 20, 2),
                            );
                        });
                    })
                    .expect("draw");
            };

        render(&mut terminal, &mut ratcn, &state);
        let EventResult::Emit(Msg::Hover(hover)) =
            ratcn.handle_event(mouse(MouseKind::Moved, 2, 2), &state)
        else {
            panic!("entering the list should update hover first");
        };
        state.hover = hover;
        render(&mut terminal, &mut ratcn, &state);
        assert_eq!(
            ratcn.handle_event(mouse(MouseKind::Moved, 2, 2), &state),
            EventResult::Emit(Msg::Focused(Task::B, 0))
        );
        state.focused = Some(Task::B);
        render(&mut terminal, &mut ratcn, &state);

        assert!(
            terminal
                .backend()
                .buffer()
                .cell((0, 2))
                .is_some_and(|cell| cell.symbol() == ">")
        );
        let buffer = terminal.backend().buffer();
        let painted_row: String = buffer.content[40..60]
            .iter()
            .map(ratatui::buffer::Cell::symbol)
            .collect();
        assert!(painted_row.contains("focused Bravo"));
        assert_eq!(
            state.component_focus,
            crate::runtime::FocusState::intent(["other"])
        );
    }

    #[test]
    fn home_end_and_page_keys_skip_disabled_items_using_rendered_height() {
        let mut driver = TestBackendDriver::new(20, 3);
        let state = State {
            focused: Some(Task::C),
            ..State::default()
        };
        let items = [
            item(Task::A, "A").disabled(true),
            item(Task::B, "B"),
            item(Task::C, "C"),
            item(Task::D, "D"),
            item(Task::E, "E").disabled(true),
            item(Task::F, "F"),
        ];
        driver.render(&state, items.clone());

        assert_eq!(
            driver.event(key(KeyCode::Home), &state),
            EventResult::Emit(Msg::Focused(Task::B, 0))
        );
        assert_eq!(
            driver.event(key(KeyCode::End), &state),
            EventResult::Emit(Msg::Focused(Task::F, 3))
        );
        assert_eq!(
            driver.event(key(KeyCode::PageDown), &state),
            EventResult::Emit(Msg::Focused(Task::F, 3))
        );
        assert_eq!(
            driver.event(key(KeyCode::PageUp), &state),
            EventResult::Emit(Msg::Focused(Task::B, 0))
        );

        let leap_items = [
            item(Task::A, "A"),
            item(Task::B, "B"),
            item(Task::C, "C"),
            item(Task::D, "D").disabled(true),
            item(Task::E, "E").disabled(true),
            item(Task::F, "F"),
        ];
        driver.render(&state, leap_items);
        assert_eq!(
            driver.event(key(KeyCode::Down), &state),
            EventResult::Emit(Msg::Focused(Task::F, 3)),
            "a disabled leap scrolls far enough to expose its enabled target"
        );
    }

    #[test]
    fn multi_selection_toggles_the_clicked_value() {
        let mut list = List::new([item(Task::A, "Alpha")]).multi_selection(
            |state: &State, value| state.toggled.contains(value),
            Msg::Toggled,
        );
        assert_eq!(
            list.handle_event(
                &mouse(MouseKind::Click(MouseButton::Left), 1, 0),
                &State::default(),
                &mut EventCtx::default().with_area(Rect::new(0, 0, 10, 1))
            ),
            EventResult::Emit(Msg::Toggled(Task::A))
        );
    }

    #[test]
    fn a_list_without_selection_bubbles_enter_and_clicks_move_focus() {
        let mut list = List::new([item(Task::A, "Alpha"), item(Task::B, "Bravo")])
            .item_focus(|state: &State| state.focused, Msg::Focused);
        let state = State {
            focused: Some(Task::A),
            ..State::default()
        };
        let area = Rect::new(0, 0, 10, 2);

        assert_eq!(
            list.handle_event(
                &key(KeyCode::Enter),
                &state,
                &mut EventCtx::default().with_area(area)
            ),
            EventResult::Ignored
        );
        assert_eq!(
            list.handle_event(
                &mouse(MouseKind::Click(MouseButton::Left), 1, 1),
                &state,
                &mut EventCtx::default().with_area(area)
            ),
            EventResult::Emit(Msg::Focused(Task::B, 0))
        );
    }

    #[test]
    fn conflicting_selection_modes_fail_during_declaration() {
        let mut driver = TestBackendDriver::new(20, 1);
        let state = State::default();
        let panic = catch_unwind(AssertUnwindSafe(|| {
            let theme = Theme::default_dark();
            driver
                .terminal
                .draw(|frame| {
                    let area = frame.area();
                    driver.ratcn.render(frame, &state, &theme, |ctx| {
                        ctx.render_component(
                            "list",
                            List::new([item(Task::A, "Alpha")])
                                .selection(|_: &State| None, Msg::Selected)
                                .multi_selection(|_, _| false, Msg::Toggled),
                            area,
                        );
                    });
                })
                .expect("draw");
        }))
        .expect_err("conflicting modes must panic");
        let message = panic.downcast_ref::<String>().map_or_else(
            || {
                panic
                    .downcast_ref::<&str>()
                    .copied()
                    .unwrap_or_default()
                    .to_owned()
            },
            Clone::clone,
        );
        assert!(message.contains("List::selection(...)"));
        assert!(message.contains("List::multi_selection(...)"));
    }

    #[test]
    fn duplicate_item_values_fail_declaration_with_the_documented_panic() {
        let mut list: List<Task, State, Msg> =
            List::new([item(Task::A, "First"), item(Task::A, "Second")]);

        let panic = catch_unwind(AssertUnwindSafe(|| {
            Component::prepare(&mut list, &State::default());
        }))
        .expect_err("duplicate item values must panic");
        let message = panic.downcast_ref::<String>().map_or_else(
            || {
                panic
                    .downcast_ref::<&str>()
                    .copied()
                    .unwrap_or_default()
                    .to_owned()
            },
            Clone::clone,
        );

        assert_eq!(
            message,
            "List item values must be unique within a List declaration"
        );
    }

    // `j`/`k` and the Ctrl chords are the same navigation gesture as the arrow
    // keys, and go out through the same item-focus message.
    #[test]
    fn vim_and_readline_keys_step_the_cursor_like_the_arrows() {
        let mut driver = TestBackendDriver::new(20, 6);
        let state = State {
            focused: Some(Task::B),
            ..State::default()
        };
        let items = || {
            [
                item(Task::A, "Alpha"),
                item(Task::B, "Bravo"),
                item(Task::C, "Charlie"),
            ]
        };
        driver.render(&state, items());

        for down in [key(KeyCode::Char('j')), ctrl_key('n')] {
            assert_eq!(
                driver.event(down, &state),
                EventResult::Emit(Msg::Focused(Task::C, 0)),
                "j and Ctrl+N step forward like Down"
            );
        }
        for up in [key(KeyCode::Char('k')), ctrl_key('p')] {
            assert_eq!(
                driver.event(up, &state),
                EventResult::Emit(Msg::Focused(Task::A, 0)),
                "k and Ctrl+P step backward like Up"
            );
        }
    }

    #[test]
    fn a_letter_that_is_not_a_navigation_key_bubbles_as_an_app_hotkey() {
        let mut driver = TestBackendDriver::new(20, 6);
        let state = State {
            focused: Some(Task::A),
            ..State::default()
        };
        driver.render(&state, [item(Task::A, "Alpha"), item(Task::B, "Bravo")]);

        assert_eq!(
            driver.event(key(KeyCode::Char('a')), &state),
            EventResult::Ignored,
            "there is no typeahead: plain letters belong to the app"
        );
        assert_eq!(
            driver.event(key(KeyCode::Char('J')), &state),
            EventResult::Ignored,
            "Shift+j is not j, so it is not navigation either"
        );
    }

    #[test]
    fn space_commits_single_selection_before_typeahead() {
        let mut list = List::new([item(Task::A, "Alpha"), item(Task::B, " Bravo")])
            .item_focus(|state: &State| state.focused, Msg::Focused)
            .selection(|state: &State| state.selected, Msg::Selected);
        let state = State {
            focused: Some(Task::A),
            ..State::default()
        };

        assert_eq!(
            list.handle_event(
                &key(KeyCode::Char(' ')),
                &state,
                &mut EventCtx::default().with_area(Rect::new(0, 0, 20, 2)),
            ),
            EventResult::Emit(Msg::Selected(Task::A)),
            "Space commits the cursor instead of typeahead-moving to the space-prefixed label"
        );
    }

    #[test]
    fn space_commits_multi_selection_before_typeahead() {
        let mut list = List::new([item(Task::A, "Alpha"), item(Task::B, " Bravo")])
            .item_focus(|state: &State| state.focused, Msg::Focused)
            .multi_selection(
                |state: &State, value| state.toggled.contains(value),
                Msg::Toggled,
            );
        let state = State {
            focused: Some(Task::A),
            ..State::default()
        };

        assert_eq!(
            list.handle_event(
                &key(KeyCode::Char(' ')),
                &state,
                &mut EventCtx::default().with_area(Rect::new(0, 0, 20, 2)),
            ),
            EventResult::Emit(Msg::Toggled(Task::A)),
            "Space toggles the cursor instead of typeahead-moving to the space-prefixed label"
        );
    }

    #[test]
    fn events_before_the_first_render_are_ignored() {
        let mut driver = TestBackendDriver::new(20, 2);
        assert_eq!(
            driver.event(key(KeyCode::PageDown), &State::default()),
            EventResult::Ignored
        );
    }
}