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
//! A trigger and popup panel for choosing one value.
//!
//! This module uses three related nouns consistently:
//!
//! - An **item** is the value-keyed [`ListItem`] shared with [`List`](crate::List).
//!   Item values provide stable identity across filtering and reordering.
//! - An **option** is one semantic Select entry that the user can choose.
//! - A **row** is terminal geometry: the one or more screen rows used to paint
//!   an option.
//!
//! For example, [`SelectWidget::option_rows`] accepts pre-rendered screen rows
//! for the widget's semantic options, while [`Select::render_item`] receives the
//! shared item state used by List.

use std::{fmt, rc::Rc};

use ratatui::{
    buffer::Buffer,
    layout::Rect,
    style::{Color, Style},
    text::{Line, Span, Text},
    widgets::{Block, BorderType, Borders, 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, MouseEvent, MouseKind,
    PopupOptions, RenderCtx, ScrollDirection,
};
use crate::selection_indicator;

const ROW_FOCUS_LIGHTEN: u16 = 15;
const INDICATOR_CLOSED: &str = "∨";
const INDICATOR_OPEN: &str = "∧";

/// Every color a select can paint.
///
/// A select has two parts, and the names keep them apart:
///
/// - **The trigger** — the one-row control showing the chosen value (or the
///   placeholder). Its fill responds to the control's interaction state:
///   `focused_trigger_background` while the select has focus,
///   `hovered_trigger_background` while it is hovered (hover wins over
///   focus), `trigger_background` at rest.
/// - **The panel** — the popup listing the options, filled with
///   `panel_background` inside a `border`. Option rows are then colored by
///   two independent facts, whether the cursor is on the option and whether
///   it is the chosen one, giving four combinations
///   (`option_foreground` → `focused_option_*` → `selected_*` →
///   `selected_focused_*`). Disabled overrides all of them, with
///   `selected_disabled_*` keeping a previously chosen option recognizable.
///
/// There is one cursor: keys and pointer hover move the same focused option,
/// and Enter commits it.
///
/// [`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
/// [`Select::style`] or [`SelectWidget::style`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SelectStyle {
    /// Text color of the chosen value on the trigger.
    pub value_foreground: Color,
    /// Text color of the placeholder shown while nothing is chosen.
    pub placeholder_foreground: Color,
    /// Trigger fill at rest.
    pub trigger_background: Color,
    /// Trigger fill while focused.
    pub focused_trigger_background: Color,
    /// Trigger fill while hovered.
    pub hovered_trigger_background: Color,
    /// Trigger indicator color.
    pub indicator: Color,
    /// Panel border color.
    pub border: Color,
    /// Panel fill.
    pub panel_background: Color,
    /// Ordinary option text color.
    pub option_foreground: Color,
    /// Cursor option text color.
    pub focused_option_foreground: Color,
    /// Cursor option fill.
    pub focused_option_background: Color,
    /// Chosen option text color.
    pub selected_foreground: Color,
    /// Chosen option text color while it is also the cursor option.
    pub selected_focused_foreground: Color,
    /// Chosen option fill while it is also the cursor option.
    pub selected_focused_background: Color,
    /// Chosen option marker color.
    pub selected_marker: Color,
    /// Unchosen option marker color.
    pub unselected_marker: Color,
    /// Disabled text and marker color.
    pub disabled_foreground: Color,
    /// Disabled trigger and option fill.
    pub disabled_background: Color,
    /// Chosen, disabled option text color.
    pub selected_disabled_foreground: Color,
    /// Chosen, disabled option fill.
    pub selected_disabled_background: Color,
}

impl SelectStyle {
    /// A neutral style using plain ANSI colors.
    #[must_use]
    pub const fn fallback() -> Self {
        Self {
            value_foreground: Color::White,
            placeholder_foreground: Color::DarkGray,
            trigger_background: Color::Reset,
            focused_trigger_background: Color::Reset,
            hovered_trigger_background: Color::DarkGray,
            indicator: Color::DarkGray,
            border: Color::DarkGray,
            panel_background: Color::Reset,
            option_foreground: Color::Reset,
            focused_option_foreground: Color::Black,
            focused_option_background: Color::Cyan,
            selected_foreground: Color::White,
            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,
            selected_disabled_foreground: Color::DarkGray,
            selected_disabled_background: Color::Reset,
        }
    }

    /// Derive every select color from `theme`.
    #[must_use]
    pub const fn from_theme(theme: &Theme) -> Self {
        let panel_background = lighten(theme.field, FIELD_FOCUS_LIGHTEN);
        Self {
            value_foreground: theme.foreground,
            placeholder_foreground: theme.muted_foreground,
            trigger_background: theme.field,
            focused_trigger_background: panel_background,
            hovered_trigger_background: lighten(theme.field, FIELD_HOVER_LIGHTEN),
            indicator: theme.muted_foreground,
            border: theme.border,
            panel_background,
            option_foreground: theme.muted_foreground,
            focused_option_foreground: theme.foreground,
            focused_option_background: lighten(panel_background, ROW_FOCUS_LIGHTEN),
            selected_foreground: theme.foreground,
            selected_focused_foreground: theme.foreground,
            selected_focused_background: lighten(panel_background, ROW_FOCUS_LIGHTEN),
            selected_marker: theme.primary,
            unselected_marker: theme.muted_foreground,
            disabled_foreground: theme.muted_foreground,
            disabled_background: dim(theme.field, theme.surface, DISABLED_DIM),
            selected_disabled_foreground: theme.muted_foreground,
            selected_disabled_background: dim(theme.field, theme.surface, DISABLED_DIM),
        }
    }

    const fn resolve_surface(self, focused: bool, hovered: bool, disabled: bool) -> Color {
        if disabled {
            self.disabled_background
        } else if hovered {
            self.hovered_trigger_background
        } else if focused {
            self.focused_trigger_background
        } else {
            self.trigger_background
        }
    }

    const fn resolve_row(self, focused: bool, selected: bool, disabled: bool) -> Style {
        let (foreground, background) = if selected && disabled {
            (
                self.selected_disabled_foreground,
                self.selected_disabled_background,
            )
        } else if disabled {
            (self.disabled_foreground, self.disabled_background)
        } else if selected && focused {
            (
                self.selected_focused_foreground,
                self.selected_focused_background,
            )
        } else if focused {
            (
                self.focused_option_foreground,
                self.focused_option_background,
            )
        } else if selected {
            (self.selected_foreground, self.panel_background)
        } else {
            (self.option_foreground, self.panel_background)
        };
        Style::new().fg(foreground).bg(background)
    }
}

/// A select that only draws, with no focus, events, or app state.
///
/// **Usable in any ratatui app.** Nothing here depends on
/// [`Ratcn`](crate::runtime::Ratcn) or the component layer: render it directly
/// and keep driving the open state, cursor, and selection however you already
/// do.
///
/// It paints a one-row trigger and, when opened, a bordered panel immediately
/// below it within the supplied area. The interactive [`Select`] paints the
/// same parts separately so its panel can live in a popup layer.
#[expect(clippy::struct_excessive_bools, reason = "independent paint states")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SelectWidget<'a> {
    value: Option<&'a str>,
    placeholder: &'a str,
    open: bool,
    options: &'a [&'a str],
    option_rows: Option<&'a [Text<'static>]>,
    row_height: u16,
    focused_option: Option<usize>,
    selected_option: Option<usize>,
    disabled_options: &'a [bool],
    scroll_offset: usize,
    focused: bool,
    hovered: bool,
    disabled: bool,
    style: SelectStyle,
}

impl<'a> SelectWidget<'a> {
    /// The trigger height in terminal rows.
    pub const TRIGGER_HEIGHT: u16 = 1;

    /// Construct a closed select showing `value`, or an empty placeholder.
    #[must_use]
    pub const fn new(value: Option<&'a str>) -> Self {
        Self {
            value,
            placeholder: "",
            open: false,
            options: &[],
            option_rows: None,
            row_height: 1,
            focused_option: None,
            selected_option: None,
            disabled_options: &[],
            scroll_offset: 0,
            focused: false,
            hovered: false,
            disabled: false,
            style: SelectStyle::fallback(),
        }
    }

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

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

    /// Set the text shown while no value is chosen.
    #[must_use]
    pub const fn placeholder(mut self, placeholder: &'a str) -> Self {
        self.placeholder = placeholder;
        self
    }

    /// Open the panel and show `options`.
    #[must_use]
    pub const fn open(mut self, options: &'a [&'a str]) -> Self {
        self.open = true;
        self.options = options;
        self
    }

    /// Pre-rendered screen rows to paint instead of each option's default
    /// marker-and-label line, positionally matched to the semantic options.
    ///
    /// Each `Text` may span several lines; pair this with
    /// [`row_height`](Self::row_height) so every option occupies the same
    /// number of rows. The [`SelectStyle`] option-state colors are painted
    /// beneath the supplied text, so unstyled text inherits them while
    /// explicit colors remain intact.
    #[must_use]
    pub const fn option_rows(mut self, option_rows: &'a [Text<'static>]) -> Self {
        self.option_rows = Some(option_rows);
        self
    }

    /// How many terminal rows each option occupies. Defaults to 1; 0 is
    /// treated as 1.
    ///
    /// Every option gets the same height, which is what keeps the panel's
    /// height math and a caller's hit-testing exact.
    #[must_use]
    pub const fn row_height(mut self, rows: u16) -> Self {
        self.row_height = if rows == 0 { 1 } else { rows };
        self
    }

    /// Set the cursor option by index.
    #[must_use]
    pub const fn focused_option(mut self, focused: Option<usize>) -> Self {
        self.focused_option = focused;
        self
    }

    /// Set the chosen option by index.
    #[must_use]
    pub const fn selected_option(mut self, selected: Option<usize>) -> Self {
        self.selected_option = selected;
        self
    }

    /// Set the disabled mask, positionally matched to the options.
    #[must_use]
    pub const fn disabled_options(mut self, disabled: &'a [bool]) -> Self {
        self.disabled_options = disabled;
        self
    }

    /// Set the index of the first visible option.
    #[must_use]
    pub const fn scroll_offset(mut self, offset: usize) -> Self {
        self.scroll_offset = offset;
        self
    }

    /// Paint the focused trigger state.
    #[must_use]
    pub const fn focused(mut self, focused: bool) -> Self {
        self.focused = focused;
        self
    }

    /// Paint the hovered trigger state.
    #[must_use]
    pub const fn hovered(mut self, hovered: bool) -> Self {
        self.hovered = hovered;
        self
    }

    /// Paint the disabled state.
    #[must_use]
    pub const fn disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }

    /// Total height this widget would paint inside `area_height`, capped at
    /// `max_visible` options.
    ///
    /// A closed or disabled select occupies one row. An enabled, open one adds
    /// a two-row panel border and as many options as fit, each
    /// [`row_height`](Self::row_height) rows tall. Openness, option count, and
    /// row height are read from the instance, so build the widget first and
    /// measure the same value that will paint.
    #[must_use]
    pub const fn height(&self, max_visible: u16, area_height: u16) -> u16 {
        let visible = self.visible_options(max_visible, area_height);
        if area_height == 0 {
            0
        } else if visible == 0 {
            Self::TRIGGER_HEIGHT
        } else {
            Self::TRIGGER_HEIGHT + visible * self.row_height + 2
        }
    }

    /// Number of whole options painted below the trigger inside `area_height`,
    /// capped at `max_visible`. Zero while closed or disabled. Counts options,
    /// not rows — multiply by [`row_height`](Self::row_height) for rows.
    #[must_use]
    #[expect(
        clippy::cast_possible_truncation,
        reason = "the option count is clamped before conversion"
    )]
    pub const fn visible_options(&self, max_visible: u16, area_height: u16) -> u16 {
        if !self.open || self.disabled {
            return 0;
        }
        let count = if self.options.len() > u16::MAX as usize {
            u16::MAX
        } else {
            self.options.len() as u16
        };
        min_u16(
            count,
            min_u16(
                max_visible,
                area_height.saturating_sub(Self::TRIGGER_HEIGHT + 2) / self.row_height,
            ),
        )
    }
}

const fn min_u16(left: u16, right: u16) -> u16 {
    if left < right { left } else { right }
}

impl Widget for SelectWidget<'_> {
    fn render(self, area: Rect, buf: &mut Buffer) {
        if area.is_empty() {
            return;
        }
        render_trigger(self, area, buf);
        // The standalone widget reserves one trigger row and two border rows.
        let visible = self.visible_options(u16::MAX, area.height);
        if self.open && !self.disabled && visible > 0 {
            let panel = Rect::new(
                area.x,
                area.y + 1,
                area.width,
                visible * self.row_height + 2,
            );
            render_panel(self, panel, buf);
        }
    }
}

fn render_trigger(widget: SelectWidget<'_>, area: Rect, buf: &mut Buffer) {
    let area = Rect { height: 1, ..area }.intersection(buf.area);
    let background = widget
        .style
        .resolve_surface(widget.focused, widget.hovered, widget.disabled);
    let (text, foreground) = if widget.disabled {
        (
            widget.value.unwrap_or(widget.placeholder),
            widget.style.disabled_foreground,
        )
    } else {
        widget.value.map_or(
            (widget.placeholder, widget.style.placeholder_foreground),
            |value| (value, widget.style.value_foreground),
        )
    };
    buf.set_style(area, Style::new().bg(background));
    buf.set_stringn(
        area.x.saturating_add(1),
        area.y,
        text,
        usize::from(area.width.saturating_sub(4)),
        Style::new().fg(foreground),
    );
    if area.width >= 2 {
        let indicator = if widget.open && !widget.disabled {
            INDICATOR_OPEN
        } else {
            INDICATOR_CLOSED
        };
        let color = if widget.disabled {
            widget.style.disabled_foreground
        } else {
            widget.style.indicator
        };
        buf.set_string(area.right() - 2, area.y, indicator, Style::new().fg(color));
    }
}

fn render_panel(widget: SelectWidget<'_>, area: Rect, buf: &mut Buffer) {
    let block = Block::new()
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_style(
            Style::new()
                .fg(widget.style.border)
                .bg(widget.style.panel_background),
        )
        .style(Style::new().bg(widget.style.panel_background));
    let inner = block.inner(area);
    block.render(area, buf);
    let row_height = widget.row_height.max(1);
    for (row, index) in (widget.scroll_offset..widget.options.len())
        .take(usize::from(inner.height / row_height))
        .enumerate()
    {
        let disabled = widget.disabled_options.get(index).copied().unwrap_or(false);
        let selected = widget.selected_option == Some(index);
        let row_area = Rect::new(
            inner.x,
            inner.y + u16::try_from(row).expect("visible rows fit in u16") * row_height,
            inner.width,
            row_height,
        );
        buf.set_style(
            row_area,
            widget
                .style
                .resolve_row(widget.focused_option == Some(index), selected, disabled),
        );
        if let Some(rows) = widget.option_rows {
            if let Some(text) = rows.get(index) {
                text.render(row_area, buf);
            }
            continue;
        }
        let marker = selection_indicator::marker(selected, false);
        let marker_color = selection_indicator::color(
            disabled,
            selected,
            selection_indicator::MarkerColors {
                disabled: widget.style.disabled_foreground,
                selected: widget.style.selected_marker,
                unselected: widget.style.unselected_marker,
            },
        );
        let line = Line::from(vec![
            Span::styled(format!(" {marker}"), Style::new().fg(marker_color)),
            Span::raw(" "),
            Span::raw(widget.options[index].to_owned()),
        ]);
        line.render(row_area, buf);
    }
}

struct SelectPanelWidget<'a>(SelectWidget<'a>);

impl Widget for SelectPanelWidget<'_> {
    fn render(self, area: Rect, buf: &mut Buffer) {
        render_panel(self.0, area, buf);
    }
}

type ReadFn<S, T> = Rc<dyn Fn(&S) -> Option<T>>;
type ReadOpenFn<S> = Rc<dyn Fn(&S) -> bool>;
type OnOpenChangeFn<M> = Rc<dyn Fn(bool) -> M>;
type OpenBinding<S, M> = (ReadOpenFn<S>, OnOpenChangeFn<M>);
type OnChangeFn<T, M> = Rc<dyn Fn(T) -> M>;
type RenderItemFn<S, T> = Rc<dyn for<'a> Fn(&S, ListItemState<'a, T>) -> Text<'static>>;
type StyleFn = Rc<dyn Fn(&Theme) -> SelectStyle>;

fn bound_index<T: PartialEq, S>(
    items: &[ListItem<T>],
    state: &S,
    read: Option<&ReadFn<S, T>>,
) -> Option<usize> {
    list_core::index_of(items, &(read?)(state)?)
}

fn resolved_cursor_index<T: PartialEq, S>(
    items: &[ListItem<T>],
    state: &S,
    focused: Option<&ReadFn<S, T>>,
    selected: Option<&ReadFn<S, T>>,
) -> Option<usize> {
    // A bound value is never second-guessed: a cursor parked on a disabled
    // option stays there and is painted there, exactly as in `List`, and the
    // commit path refuses it. Only an absent value falls back.
    bound_index(items, state, focused)
        .or_else(|| bound_index(items, state, selected))
        .or_else(|| linear_nav::first_enabled(items.len(), |i| list_core::disabled_at(items, i)))
}

fn emit_item<T: Clone, M>(
    handler: Option<&OnChangeFn<T, M>>,
    items: &[ListItem<T>],
    index: usize,
) -> EventResult<M> {
    handler.map_or(EventResult::Ignored, |handler| {
        EventResult::Emit(handler(items[index].value().clone()))
    })
}

/// A one-row select trigger with an option panel declared as a popup layer.
///
/// The panel is a child popup anchored at the Select's identity. It paints over
/// the trigger with its top border one row above the trigger, so the first
/// option covers the trigger row. Near a frame edge it shifts just far enough
/// to remain visible. Moving the option cursor never moves the popup itself.
/// The same placement works when the Select is inside a modal.
///
/// Vocabulary: the panel *closes* on Esc, Tab-out, or a trigger click, and is
/// *dismissed* by a primary-button press outside it (the popup layer's dismiss
/// gesture, which emits the close message without consuming the press). All of
/// these arrive through the [`open`](Self::open) binding as
/// `on_open_change(false)`.
///
/// Open state, item focus (the option cursor), and selection (the committed
/// choice) are app-owned controlled bindings. Each option is backed by a
/// value-keyed [`ListItem`]; its item value is the stable identity shared with
/// [`List`](crate::List). The update handling a selection should store the value
/// as both item focus and selection and close the panel; one message then keeps
/// all three values synchronized between redraws.
///
/// Keyboard operation requires [`open`](Self::open),
/// [`item_focus`](Self::item_focus), and [`selection`](Self::selection). Partial
/// binding combinations remain valid for paint-only or pointer-only use, but do
/// not make the Select a keyboard focus stop or consume keyboard input.
///
/// Item values must be unique. Enter, Space, Up, or Down opens a closed Select.
/// While open, navigation moves item focus, Enter or Space selects, Esc closes,
/// and the first Tab or `BackTab` closes and consumes that traversal key. A
/// following Tab can move focus after the app applies the close message. The
/// wheel scrolls the panel and leaves item focus where it is, so the cursor
/// may scroll out of sight until something moves it again — the same wheel
/// behavior as [`List`](crate::List).
/// While open, typing a printable character jumps item focus to
/// the next enabled option whose label starts with it, case-insensitively,
/// cycling past the end — the same single-character typeahead as
/// [`List`](crate::List) (clock-free, so no multi-character buffer); a
/// character matching no label bubbles through the popup as an app hotkey.
/// Other modified keys are ignored so app shortcuts can handle
/// them after they bubble through the popup. Paste events bubble for the same
/// reason; Select has no text-editing behavior.
#[expect(
    clippy::struct_field_names,
    reason = "on_select matches the public selection binding vocabulary"
)]
pub struct Select<T, S, M> {
    items: Vec<ListItem<T>>,
    placeholder: String,
    open: Option<OpenBinding<S, M>>,
    focused_item: Option<ReadFn<S, T>>,
    on_focus_change: Option<OnChangeFn<T, M>>,
    selected: Option<ReadFn<S, T>>,
    on_select: Option<OnChangeFn<T, M>>,
    max_visible: u16,
    disabled: bool,
    render_item: Option<RenderItemFn<S, T>>,
    row_height: u16,
    style: Option<StyleFn>,
    resolved_open: bool,
    page_size: usize,
}

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

impl<T, S, M> Select<T, S, M> {
    /// Default maximum number of visible options.
    pub const DEFAULT_MAX_VISIBLE_OPTIONS: u16 = 8;

    /// Construct a Select from value-keyed options.
    ///
    /// Accepts anything convertible to [`ListItem`], including plain strings.
    /// Values must be unique within this declaration.
    #[must_use]
    pub fn new(items: impl IntoIterator<Item = impl Into<ListItem<T>>>) -> Self {
        Self {
            items: items.into_iter().map(Into::into).collect(),
            placeholder: String::new(),
            open: None,
            focused_item: None,
            on_focus_change: None,
            selected: None,
            on_select: None,
            max_visible: Self::DEFAULT_MAX_VISIBLE_OPTIONS,
            disabled: false,
            render_item: None,
            row_height: 1,
            style: None,
            resolved_open: false,
            page_size: 1,
        }
    }

    /// Set the trigger placeholder.
    #[must_use]
    pub fn placeholder(mut self, placeholder: impl Into<String>) -> Self {
        self.placeholder = placeholder.into();
        self
    }

    /// Bind the panel's open state and the message that changes it.
    ///
    /// `read` runs against current app state during rendering and event
    /// handling. `on_open_change` receives each requested state — the open flag
    /// is a continuously tracked value, like a cursor, not a one-shot commit:
    /// `true` when the user opens the trigger, `false` when the panel should
    /// close. Without this binding the Select is not focusable and cannot open.
    ///
    /// This binding is also the component's dismiss channel: Esc, Tab-out, a
    /// trigger click while open, and a press outside the panel all arrive as
    /// `on_open_change(false)`. It plays the role
    /// [`Dialog::on_dismiss`](crate::Dialog::on_dismiss) and
    /// [`PopupOptions::on_dismiss`] play elsewhere — one message closes the
    /// panel no matter which gesture asked for it.
    #[must_use]
    pub fn open(
        mut self,
        read: impl Fn(&S) -> bool + 'static,
        on_open_change: impl Fn(bool) -> M + 'static,
    ) -> Self {
        self.open = Some((Rc::new(read), Rc::new(on_open_change)));
        self
    }

    /// Bind the option cursor and the message that moves it.
    ///
    /// `read` returns the focused option value. When it returns `None`, an open
    /// panel starts from the selected value or the first enabled option.
    /// `on_change` receives each value reached by keyboard or pointer movement;
    /// moving the cursor does not commit a selection.
    ///
    /// Unlike [`List::item_focus`](crate::List::item_focus), `on_change`
    /// carries no scroll-offset payload: the panel owns its scroll and keeps
    /// the cursor visible itself, so there is no app-held offset to keep in
    /// sync.
    #[must_use]
    pub fn item_focus(
        mut self,
        read: impl Fn(&S) -> Option<T> + 'static,
        on_change: impl Fn(T) -> M + 'static,
    ) -> Self {
        self.focused_item = Some(Rc::new(read));
        self.on_focus_change = Some(Rc::new(on_change));
        self
    }

    /// Bind the committed value and the message that selects it.
    ///
    /// `read` returns the value shown on the trigger. `on_select` receives the
    /// option committed by Enter, Space, or a primary-button click. Its update
    /// should also align item focus and close the panel so the complete change
    /// is atomic.
    #[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(Rc::new(read));
        self.on_select = Some(Rc::new(on_select));
        self
    }

    /// Set the maximum visible option count. Additional options scroll.
    ///
    /// Defaults to [`DEFAULT_MAX_VISIBLE_OPTIONS`](Self::DEFAULT_MAX_VISIBLE_OPTIONS).
    /// Zero is treated as one.
    #[must_use]
    pub const fn max_visible_options(mut self, max_visible: u16) -> Self {
        self.max_visible = if max_visible == 0 { 1 } else { max_visible };
        self
    }

    /// Draw each option yourself instead of using the default marker-and-label
    /// line.
    ///
    /// The closure gets app state and a [`ListItemState`] describing the
    /// option, and returns what to paint — the same contract as
    /// [`List::render_item`](crate::List::render_item). Use it for columns,
    /// secondary text, per-option icons — anything the default cannot express.
    /// The resolved [`SelectStyle`] is painted beneath the returned text, so
    /// unstyled text inherits option-state colors while explicit `Text`, `Line`,
    /// and `Span` colors remain intact.
    ///
    /// Return a [`Line`] for the usual one-row option, or a [`Text`] for a
    /// taller one — a name above a subtitle, say. A multi-line option also
    /// needs [`row_height`](Self::row_height) set to match, since every option
    /// 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(Rc::new(move |state, row| f(state, row).into()));
        self
    }

    /// How many terminal rows each option occupies. Defaults to 1.
    ///
    /// Raise it when [`render_item`](Self::render_item) returns more than one
    /// line. Every option 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 option the user clicks is always the
    /// one the runtime thinks it is. The panel's height grows accordingly:
    /// each visible option costs this many rows inside the panel border.
    ///
    /// A height of 0 is treated as 1.
    #[must_use]
    pub const fn row_height(mut self, rows: u16) -> Self {
        self.row_height = if rows == 0 { 1 } else { rows };
        self
    }

    /// The rows this Select needs: always one, open or closed.
    ///
    /// The trigger is a single row and the panel is a popup layer floating
    /// above the rest of the frame, so a layout reserves one row and never
    /// has to leave space for the options. Width is the caller's: the trigger
    /// fills whatever area it is given, and the panel matches it.
    ///
    /// [`SelectWidget::height`] is the other half's answer, and differs on
    /// purpose: a paint-only Select draws its panel *inside* the area it is
    /// given, so there the options do count.
    #[must_use]
    pub const fn height(&self) -> u16 {
        SelectWidget::TRIGGER_HEIGHT
    }

    /// Replace the theme-derived style.
    ///
    /// The closure receives the active theme each render, so its result follows
    /// runtime theme changes.
    #[must_use]
    pub fn style(mut self, style: impl Fn(&Theme) -> SelectStyle + 'static) -> Self {
        self.style = Some(Rc::new(style));
        self
    }

    /// Dim the whole Select and disable all interaction.
    ///
    /// A disabled Select, an empty Select, or one whose options are all disabled
    /// is excluded from focus traversal. Disable one option with
    /// [`ListItem::disabled`].
    #[must_use]
    pub const fn disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }
}

/// Tab or `BackTab`: the keys that move focus out of the Select entirely. Ctrl
/// and Alt variants belong to the app, so they are not traversal here.
fn is_traversal(key: KeyEvent) -> bool {
    match key.code {
        KeyCode::Tab => !key.modifiers.any(),
        KeyCode::BackTab => !key.modifiers.ctrl && !key.modifiers.alt,
        _ => false,
    }
}

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

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

    fn cursor_index(&self, state: &S) -> Option<usize> {
        resolved_cursor_index(
            &self.items,
            state,
            self.focused_item.as_ref(),
            self.selected.as_ref(),
        )
    }

    fn is_open(&self, state: &S) -> bool {
        self.open.as_ref().is_some_and(|(read, _)| read(state))
    }

    fn toggle(&self, open: bool) -> EventResult<M> {
        self.open
            .as_ref()
            .map_or(EventResult::Ignored, |(_, toggle)| {
                EventResult::Emit(toggle(open))
            })
    }

    fn move_cursor(&self, index: usize) -> EventResult<M> {
        emit_item(self.on_focus_change.as_ref(), &self.items, index)
    }

    fn select(&self, index: usize) -> EventResult<M> {
        emit_item(self.on_select.as_ref(), &self.items, index)
    }

    fn keyboard_enabled(&self) -> bool {
        self.open.is_some() && self.focused_item.is_some() && self.selected.is_some()
    }

    /// Is there any option a cursor could land on? A panel of nothing but
    /// disabled options is not worth opening and cannot be navigated.
    fn has_enabled_item(&self) -> bool {
        linear_nav::first_enabled(self.items.len(), |i| self.disabled_at(i)).is_some()
    }

    /// Route a key to whichever of the two key maps is in force. A closed
    /// Select and an open one answer to almost disjoint sets of keys, so they
    /// are separate functions rather than one sequence of `open` tests.
    ///
    /// Only the two checks here span both, and their order is load-bearing.
    /// Traversal comes first because an open panel must not travel with the
    /// focus that is leaving — and it has to precede the modifier rejection,
    /// since `BackTab` carries Shift and would be rejected by it.
    fn handle_key(&self, key: KeyEvent, state: &S, page_size: usize) -> EventResult<M> {
        if !self.keyboard_enabled() {
            return EventResult::Ignored;
        }
        let open = self.is_open(state);
        if open && is_traversal(key) {
            return self.toggle(false);
        }
        if open {
            self.handle_open_key(key, state, page_size)
        } else {
            self.handle_closed_key(key)
        }
    }

    /// The keys a closed Select answers: the ones that open it, and nothing
    /// else. Everything unrecognized bubbles so the app keeps its hotkeys.
    fn handle_closed_key(&self, key: KeyEvent) -> EventResult<M> {
        if !self.has_enabled_item() {
            return EventResult::Ignored;
        }
        // A key that would move the cursor reveals the cursor instead. Asking
        // the shared key map keeps that true of the Ctrl chords as well as the
        // arrows.
        if linear_nav::is_step_key(key) {
            return self.toggle(true);
        }
        if linear_nav::has_reserved_modifier(key) {
            return EventResult::Ignored;
        }
        match key.code {
            KeyCode::Enter | KeyCode::Char(' ') => self.toggle(true),
            _ => EventResult::Ignored,
        }
    }

    /// The keys an open panel answers: dismiss, navigation, commit, typeahead.
    fn handle_open_key(&self, key: KeyEvent, state: &S, page_size: usize) -> EventResult<M> {
        // Closing comes before the emptiness check: a panel with nothing to
        // operate must still be dismissable.
        if key.code == KeyCode::Esc && !linear_nav::has_reserved_modifier(key) {
            return self.toggle(false);
        }
        if !self.has_enabled_item() {
            return EventResult::Ignored;
        }
        let cursor = self.cursor_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, page_size.max(1), |i| {
                self.disabled_at(i)
            })
        {
            return match outcome {
                NavOutcome::Move(index) => self.move_cursor(index),
                NavOutcome::Stay => EventResult::Consumed,
            };
        }
        if linear_nav::has_reserved_modifier(key) {
            return EventResult::Ignored;
        }
        if matches!(key.code, KeyCode::Enter | KeyCode::Char(' ')) {
            // A cursor parked on a disabled option commits nothing, as in
            // `List`, and the key bubbles rather than vanishing.
            return match cursor {
                Some(index) if !self.disabled_at(index) => self.select(index),
                _ => EventResult::Ignored,
            };
        }
        // Anything else bubbles through to the app: the popup is not modal, so
        // an unhandled key is not the panel's to swallow.
        EventResult::Ignored
    }
}

impl<T: Clone + PartialEq + 'static, S: 'static, M: 'static> Component<S, M> for Select<T, S, M> {
    fn prepare(&mut self, state: &S) {
        list_core::assert_unique_values(self.items.iter().map(ListItem::value), "Select");
        self.resolved_open = !self.disabled && self.is_open(state);
    }

    fn render(&mut self, ctx: &mut RenderCtx<'_, '_, S, M>) {
        let area = Rect {
            height: ctx.area().height.min(1),
            ..ctx.area()
        };
        let state = ctx.state();
        let style = self.style.as_ref().map_or_else(
            || SelectStyle::from_theme(ctx.theme),
            |style| style(ctx.theme),
        );
        let selected = self.selected_index(state);
        let value = selected.map(|index| self.items[index].label());
        let labels: Vec<&str> = self.items.iter().map(ListItem::label).collect();
        let mut trigger = SelectWidget::new(value)
            .placeholder(&self.placeholder)
            .focused(ctx.focused)
            .hovered(ctx.hovered)
            .disabled(self.disabled)
            .style(style);
        if self.resolved_open {
            trigger = trigger.open(&labels);
        }
        ctx.render_widget(trigger, area);

        let Some((panel_area, viewport)) = self
            .resolved_open
            .then(|| {
                panel_layout(
                    area,
                    ctx.frame_area(),
                    self.items.len(),
                    self.max_visible,
                    self.row_height,
                )
            })
            .flatten()
        else {
            return;
        };
        let inner = Block::new().borders(Borders::ALL).inner(panel_area);
        self.page_size = viewport.visible_items(inner).max(1);
        let Some((open, on_open_change)) = &self.open else {
            return;
        };
        let panel = SelectPanel {
            items: self.items.clone(),
            open: Rc::clone(open),
            focused_item: self.focused_item.clone(),
            on_focus_change: self.on_focus_change.clone(),
            selected: self.selected.clone(),
            on_select: self.on_select.clone(),
            render_item: self.render_item.clone(),
            style,
            panel_area,
            viewport,
        };
        let on_open_change = Rc::clone(on_open_change);
        ctx.popup(
            "panel",
            PopupOptions::default().on_dismiss(move || on_open_change(false)),
            panel_area,
            move |ctx| ctx.render_component("options", panel, panel_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;
        }
        match event {
            Event::Mouse(mouse) => match mouse.kind {
                MouseKind::Click(MouseButton::Left) => self.toggle(!self.is_open(state)),
                _ => EventResult::Ignored,
            },
            Event::Key(key) => self.handle_key(*key, state, self.page_size),
            _ => EventResult::Ignored,
        }
    }

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

    fn interaction_area(&self, area: Rect) -> Rect {
        Rect {
            height: area.height.min(1),
            ..area
        }
    }
}

struct SelectPanel<T, S, M> {
    items: Vec<ListItem<T>>,
    open: ReadOpenFn<S>,
    focused_item: Option<ReadFn<S, T>>,
    on_focus_change: Option<OnChangeFn<T, M>>,
    selected: Option<ReadFn<S, T>>,
    on_select: Option<OnChangeFn<T, M>>,
    render_item: Option<RenderItemFn<S, T>>,
    style: SelectStyle,
    panel_area: Rect,
    viewport: RowViewport,
}

impl<T: Clone + PartialEq, S, M> SelectPanel<T, S, M> {
    fn cursor(&self, state: &S) -> Option<usize> {
        resolved_cursor_index(
            &self.items,
            state,
            self.focused_item.as_ref(),
            self.selected.as_ref(),
        )
    }

    fn option_at(&self, mouse: &MouseEvent) -> Option<usize> {
        let inner = Block::new().borders(Borders::ALL).inner(self.panel_area);
        self.viewport
            .row_at(inner, self.items.len(), mouse.column, mouse.row)
    }
}

impl<T: Clone + PartialEq, S, M> Component<S, M> for SelectPanel<T, S, M> {
    fn render(&mut self, ctx: &mut RenderCtx<'_, '_, S, M>) {
        let state = ctx.state();
        let labels: Vec<&str> = self.items.iter().map(ListItem::label).collect();
        let disabled: Vec<bool> = self.items.iter().map(ListItem::is_disabled).collect();
        let cursor = self.cursor(state);
        let inner = Block::new().borders(Borders::ALL).inner(self.panel_area);
        let len = self.items.len();
        // The panel owns its scrolling, so the park supplies the offset: the
        // view stays where the wheel left it — cursor visible or not — until
        // the cursor moves, and the park dies with the popup.
        let mut park = ctx
            .transient_mut::<WheelPark>()
            .map_or_else(WheelPark::default, |park| {
                park.settle(cursor);
                *park
            });
        let offset = self.viewport.cursor_visible_offset(
            inner,
            len,
            park.offset(),
            park.cursor_to_show(cursor),
        );
        park.record(offset);
        if let Some(stored) = ctx.transient_mut::<WheelPark>() {
            *stored = park;
        }
        self.viewport.record_painted_offset(offset);
        let selected = bound_index(&self.items, state, self.selected.as_ref());
        let rows_per_item = self.viewport.rows_per_item();
        let rows: Option<Vec<Text<'static>>> = self.render_item.as_ref().map(|render_item| {
            self.items
                .iter()
                .enumerate()
                .map(|(index, item)| {
                    let row = ListItemState {
                        index,
                        value: item.value(),
                        label: item.label(),
                        focused: cursor == Some(index),
                        selected: selected == Some(index),
                        disabled: item.is_disabled(),
                    };
                    fit_to_height(render_item(state, row), rows_per_item)
                })
                .collect()
        });
        let mut widget = SelectWidget::new(None)
            .open(&labels)
            .row_height(rows_per_item)
            .focused_option(cursor)
            .selected_option(selected)
            .disabled_options(&disabled)
            .scroll_offset(self.viewport.painted_offset())
            .style(self.style);
        if let Some(rows) = &rows {
            widget = widget.option_rows(rows);
        }
        ctx.render_widget(SelectPanelWidget(widget), self.panel_area);
    }

    fn handle_event(&mut self, event: &Event, state: &S, ctx: &mut EventCtx<'_>) -> EventResult<M> {
        if !(self.open)(state) {
            return EventResult::Ignored;
        }
        let Event::Mouse(mouse) = event else {
            return EventResult::Ignored;
        };
        let cursor = self.cursor(state);
        let option = self.option_at(mouse);
        match mouse.kind {
            MouseKind::Down(MouseButton::Left)
                if option.is_some_and(|i| list_core::disabled_at(&self.items, i)) =>
            {
                EventResult::Consumed
            }
            MouseKind::Click(MouseButton::Left) => match option {
                Some(index) if list_core::disabled_at(&self.items, index) => EventResult::Ignored,
                // With nothing to commit to, the click still moves the
                // cursor, as it does over a `List`.
                Some(index) if self.on_select.is_none() => {
                    emit_item(self.on_focus_change.as_ref(), &self.items, index)
                }
                Some(index) => emit_item(self.on_select.as_ref(), &self.items, index),
                None => EventResult::Consumed,
            },
            // Hover moves the cursor, as in `List`: one highlight, moved by
            // keys and pointer alike, and Enter commits what it shows.
            MouseKind::Moved => match option {
                _ if self.focused_item.is_none() => EventResult::Ignored,
                Some(index) if list_core::disabled_at(&self.items, index) => EventResult::Ignored,
                Some(index) if Some(index) != cursor => {
                    emit_item(self.on_focus_change.as_ref(), &self.items, index)
                }
                Some(_) => EventResult::Consumed,
                None => EventResult::Ignored,
            },
            MouseKind::Scroll(direction) => {
                let step = match direction {
                    ScrollDirection::Up => ScrollStep::Up,
                    ScrollDirection::Down => ScrollStep::Down,
                    ScrollDirection::Left | ScrollDirection::Right => {
                        return EventResult::Ignored;
                    }
                };
                let inner = Block::new().borders(Borders::ALL).inner(self.panel_area);
                let offset = linear_nav::wheel_offset(
                    self.items.len(),
                    self.viewport.visible_items(inner),
                    self.viewport.painted_offset(),
                    step,
                    SCROLL_STEP,
                );
                // Park the view in the transient store: render honors it
                // until the cursor moves, and it survives redraws because it
                // lives on the panel's identity, not on this per-frame
                // instance. The cursor itself never moves on wheel.
                ctx.transient::<WheelPark>().park(offset, cursor);
                // Keep this retained instance's hit-testing aligned with the
                // offset the next paint will use.
                self.viewport.record_painted_offset(offset);
                EventResult::Consumed
            }
            _ => EventResult::Ignored,
        }
    }
}

fn visible_count(len: usize, max_visible: u16, available: u16) -> u16 {
    u16::try_from(len)
        .unwrap_or(u16::MAX)
        .min(max_visible)
        .min(available)
}

fn panel_layout(
    trigger: Rect,
    bounds: Rect,
    len: usize,
    max_visible: u16,
    row_height: u16,
) -> Option<(Rect, RowViewport)> {
    let row_height = row_height.max(1);
    // Popup bounds contain only the bordered panel; the trigger paints elsewhere.
    let visible = visible_count(
        len,
        max_visible,
        bounds.height.saturating_sub(2) / row_height,
    );
    if visible == 0 || trigger.width == 0 {
        return None;
    }
    let height = visible.saturating_mul(row_height).saturating_add(2);
    let desired_y = trigger.y.saturating_sub(1);
    let max_y = bounds.bottom().saturating_sub(height);
    let y = desired_y.clamp(bounds.y, max_y);
    // The scroll offset is not decided here: the panel resolves it each frame
    // from the wheel-parked transient and the cursor, then records it.
    Some((
        Rect::new(trigger.x, y, trigger.width, height),
        RowViewport::new(row_height),
    ))
}

#[cfg(test)]
const fn frame_area() -> Rect {
    Rect::new(0, 0, 20, 8)
}

#[cfg(test)]
mod tests {
    use ratatui::{Terminal, backend::TestBackend};

    use super::*;
    use crate::{
        ListStyle,
        runtime::{FocusState, Modifiers, Ratcn, ScopeOptions},
    };

    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    enum Fruit {
        Mango,
        Papaya,
        Lychee,
        Durian,
    }

    #[derive(Debug, PartialEq)]
    enum Msg {
        Open(bool),
        Focused(Fruit),
        Selected(Fruit),
        Focus(FocusState),
    }

    #[derive(Default)]
    struct State {
        open: bool,
        cursor: Option<Fruit>,
        selected: Option<Fruit>,
        focus: FocusState,
    }

    fn items() -> Vec<ListItem<Fruit>> {
        [
            (Fruit::Mango, "Mango"),
            (Fruit::Papaya, "Papaya"),
            (Fruit::Lychee, "Lychee"),
            (Fruit::Durian, "Durian"),
        ]
        .into_iter()
        .map(|(value, label)| ListItem::new(value, label))
        .collect()
    }

    #[test]
    fn list_and_select_share_themed_control_surfaces() {
        for theme in Theme::presets() {
            let list = ListStyle::from_theme(theme);
            let select = SelectStyle::from_theme(theme);
            assert_eq!(
                select.trigger_background, list.background,
                "{} base",
                theme.name
            );
            assert_eq!(
                select.focused_trigger_background, list.focused_background,
                "{} focus",
                theme.name
            );
            assert_eq!(
                select.hovered_trigger_background, list.hovered_background,
                "{} hover",
                theme.name
            );
            assert_eq!(
                select.panel_background, list.focused_background,
                "{} panel",
                theme.name
            );
            assert_eq!(
                select.focused_option_background, list.focused_row_background,
                "{} row",
                theme.name
            );
            assert_eq!(
                select.selected_focused_foreground, list.selected_focused_foreground,
                "{} selected focused foreground",
                theme.name
            );
            assert_eq!(
                select.selected_focused_background, list.selected_focused_background,
                "{} selected focused background",
                theme.name
            );
            assert_eq!(
                select.disabled_background, list.disabled_background,
                "{} disabled",
                theme.name
            );
            assert_eq!(
                select.selected_disabled_foreground, list.disabled_foreground,
                "{} selected disabled foreground",
                theme.name
            );
            assert_eq!(
                select.selected_disabled_background, list.disabled_background,
                "{} selected disabled background",
                theme.name
            );
            assert_ne!(
                list.background, list.focused_background,
                "{} focus",
                theme.name
            );
            assert_ne!(
                list.focused_background, list.hovered_background,
                "{} hover",
                theme.name
            );
            assert_ne!(
                list.focused_background, list.focused_row_background,
                "{} focused row",
                theme.name
            );
            assert_ne!(
                list.foreground, list.selected_foreground,
                "{} selected text",
                theme.name
            );
            assert_ne!(
                list.unselected_marker, list.selected_marker,
                "{} selected marker",
                theme.name
            );
        }
    }

    #[test]
    fn compound_option_states_use_their_exact_style_fields() {
        let mut style = SelectStyle::fallback();
        style.selected_focused_foreground = Color::Yellow;
        style.selected_focused_background = Color::Blue;
        style.selected_disabled_foreground = Color::Magenta;
        style.selected_disabled_background = Color::Green;

        assert_eq!(
            style.resolve_row(true, true, false),
            Style::new().fg(Color::Yellow).bg(Color::Blue)
        );
        assert_eq!(
            style.resolve_row(true, true, true),
            Style::new().fg(Color::Magenta).bg(Color::Green),
            "disabled wins over focus while preserving selected identity"
        );
    }

    #[test]
    fn disabled_open_widget_measures_and_paints_only_the_closed_trigger() {
        let options = ["Mango", "Papaya"];
        let widget = SelectWidget::new(None).open(&options).disabled(true);
        let area = Rect::new(0, 0, 12, 5);
        let mut buffer = Buffer::empty(area);

        assert_eq!(widget.visible_options(8, area.height), 0);
        assert_eq!(widget.height(8, area.height), SelectWidget::TRIGGER_HEIGHT);
        widget.render(area, &mut buffer);

        assert_eq!(
            buffer.cell((10, 0)).expect("indicator").symbol(),
            INDICATOR_CLOSED
        );
        assert!(
            (1..area.height).all(|row| buffer
                .cell((0, row))
                .is_some_and(|cell| cell.symbol() == " ")),
            "a disabled open widget must not paint panel rows"
        );
    }

    fn select(items: Vec<ListItem<Fruit>>) -> Select<Fruit, State, Msg> {
        Select::new(items)
            .placeholder("Pick a fruit")
            .open(|state: &State| state.open, Msg::Open)
            .item_focus(|state: &State| state.cursor, Msg::Focused)
            .selection(|state: &State| state.selected, Msg::Selected)
    }

    struct Driver {
        terminal: Terminal<TestBackend>,
        ratcn: Ratcn<State, Msg>,
    }

    impl Driver {
        fn new(width: u16, height: u16) -> Self {
            Self {
                terminal: Terminal::new(TestBackend::new(width, height)).expect("terminal"),
                ratcn: Ratcn::new().focus(|state: &State| &state.focus, Msg::Focus),
            }
        }

        fn render(&mut self, state: &State, area: Rect, items: &[ListItem<Fruit>]) {
            let theme = Theme::default_dark();
            self.terminal
                .draw(|frame| {
                    self.ratcn.render(frame, state, &theme, |ctx| {
                        ctx.render_component("fruit", select(items.to_vec()), area);
                        ctx.render_widget(Line::from("later sibling"), Rect::new(0, 4, 20, 1));
                    });
                })
                .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();
            (0..buffer.area.width)
                .map(|column| buffer.cell((column, row)).expect("cell").symbol())
                .collect()
        }
    }

    fn mouse(kind: MouseKind, column: u16, row: u16) -> Event {
        Event::Mouse(MouseEvent {
            kind,
            column,
            row,
            modifiers: Modifiers::NONE,
        })
    }

    #[test]
    fn popup_starts_above_the_trigger_and_layers_above_later_paint() {
        let mut driver = Driver::new(20, 10);
        let state = State {
            open: true,
            selected: Some(Fruit::Papaya),
            ..State::default()
        };
        driver.render(&state, Rect::new(0, 4, 20, 1), &items());
        assert!(driver.row(3).contains("â•­"), "{}", driver.row(3));
        assert!(driver.row(4).contains("Mango"), "{}", driver.row(4));
        assert!(!driver.row(4).contains("later sibling"));
        assert!(driver.row(5).contains("Papaya"));
    }

    #[test]
    fn popup_composites_only_the_panel_area() {
        let mut terminal = Terminal::new(TestBackend::new(20, 8)).expect("terminal");
        let mut ratcn = Ratcn::<State, Msg>::new();
        let state = State {
            open: true,
            ..State::default()
        };
        let theme = Theme::default_dark();
        terminal
            .draw(|frame| {
                ratcn.render(frame, &state, &theme, |ctx| {
                    ctx.render_component("fruit", select(items()), Rect::new(0, 0, 20, 1));
                    ctx.render_widget(Line::from("outside panel"), Rect::new(0, 7, 20, 1));
                });
            })
            .expect("draw");
        let row: String = (0..20)
            .map(|column| {
                terminal
                    .backend()
                    .buffer()
                    .cell((column, 7))
                    .expect("cell")
                    .symbol()
            })
            .collect();
        assert!(row.contains("outside panel"), "{row}");
    }

    #[test]
    fn panel_shifts_inside_the_frame_when_default_position_does_not_fit() {
        let mut driver = Driver::new(20, 8);
        let state = State {
            open: true,
            ..State::default()
        };
        driver.render(&state, Rect::new(0, 7, 20, 1), &items());
        assert!(driver.row(3).contains("Mango"), "{}", driver.row(3));
        assert!(driver.row(7).contains("╯"), "{}", driver.row(7));
    }

    #[test]
    fn panel_position_depends_only_on_geometry() {
        let trigger = Rect::new(0, 4, 20, 1);
        let bounds = Rect::new(0, 0, 20, 10);
        // The cursor is not an input: neither moving it nor scrolling can
        // move the popup.
        let (panel, viewport) = panel_layout(trigger, bounds, 10, 4, 1).expect("panel");
        assert_eq!(panel.y, trigger.y - 1);
        assert_eq!(viewport.painted_offset(), 0, "the panel resolves scrolling");
    }

    #[test]
    fn keys_navigate_select_and_first_tab_closes() {
        let mut driver = Driver::new(20, 8);
        let state = State {
            open: true,
            cursor: Some(Fruit::Mango),
            ..State::default()
        };
        driver.render(&state, Rect::new(0, 0, 20, 1), &items());
        assert_eq!(
            driver.event(Event::Key(KeyEvent::new(KeyCode::Down)), &state),
            EventResult::Emit(Msg::Focused(Fruit::Papaya))
        );
        assert_eq!(
            driver.event(Event::Key(KeyEvent::new(KeyCode::Tab)), &state),
            EventResult::Emit(Msg::Open(false))
        );
    }

    #[test]
    fn open_close_commit_and_modified_key_contracts_are_explicit() {
        let closed = State::default();
        for code in [
            KeyCode::Enter,
            KeyCode::Char(' '),
            KeyCode::Up,
            KeyCode::Down,
        ] {
            let mut component = select(items());
            component.prepare(&closed);
            assert_eq!(
                component.handle_event(
                    &Event::Key(KeyEvent::new(code)),
                    &closed,
                    &mut EventCtx::default(),
                ),
                EventResult::Emit(Msg::Open(true)),
                "{code:?} opens a closed Select"
            );
        }

        let open = State {
            open: true,
            cursor: Some(Fruit::Papaya),
            ..State::default()
        };
        let mut component = select(items());
        component.prepare(&open);
        assert_eq!(
            component.handle_event(
                &Event::Key(KeyEvent::new(KeyCode::Esc)),
                &open,
                &mut EventCtx::default(),
            ),
            EventResult::Emit(Msg::Open(false))
        );
        assert_eq!(
            component.handle_event(
                &Event::Key(KeyEvent::new(KeyCode::Char(' '))),
                &open,
                &mut EventCtx::default(),
            ),
            EventResult::Emit(Msg::Selected(Fruit::Papaya))
        );
        assert_eq!(
            component.handle_event(
                &Event::Key(KeyEvent {
                    code: KeyCode::Char('k'),
                    modifiers: Modifiers {
                        ctrl: true,
                        ..Modifiers::NONE
                    },
                }),
                &open,
                &mut EventCtx::default(),
            ),
            EventResult::Ignored
        );
        assert_eq!(
            component.handle_event(
                &Event::Paste("fruit".to_owned()),
                &open,
                &mut EventCtx::default(),
            ),
            EventResult::Ignored
        );
        assert_eq!(
            component.handle_event(
                &mouse(MouseKind::Click(MouseButton::Left), 0, 0),
                &closed,
                &mut EventCtx::default(),
            ),
            EventResult::Emit(Msg::Open(true))
        );
    }

    #[test]
    fn paging_moves_the_cursor_by_the_painted_viewport() {
        let mut driver = Driver::new(20, 4);
        let state = State {
            open: true,
            cursor: Some(Fruit::Mango),
            ..State::default()
        };
        driver.render(&state, Rect::new(0, 0, 20, 1), &items());

        assert_eq!(
            driver.event(Event::Key(KeyEvent::new(KeyCode::PageDown)), &state),
            EventResult::Emit(Msg::Focused(Fruit::Lychee)),
            "only two option rows fit in the painted panel"
        );
    }

    #[test]
    fn wheel_scrolls_the_view_and_the_offset_survives_redraw() {
        let mut driver = Driver::new(20, 4);
        let mut state = State {
            open: true,
            cursor: Some(Fruit::Mango),
            ..State::default()
        };
        driver.render(&state, Rect::new(0, 0, 20, 1), &items());
        assert!(driver.row(1).contains("Mango"), "{}", driver.row(1));

        assert_eq!(
            driver.event(
                mouse(MouseKind::Scroll(ScrollDirection::Down), 3, 1),
                &state
            ),
            EventResult::Consumed,
            "the wheel scrolls the view without emitting a cursor move"
        );
        driver.render(&state, Rect::new(0, 0, 20, 1), &items());
        assert!(
            driver.row(1).contains("Lychee") && driver.row(2).contains("Durian"),
            "the wheeled offset survives the redraw, cursor off-screen: {} / {}",
            driver.row(1),
            driver.row(2)
        );

        // Keyboard navigation still starts from the cursor, and the next
        // redraw scrolls it back into view from the wheeled offset.
        assert_eq!(
            driver.event(Event::Key(KeyEvent::new(KeyCode::Down)), &state),
            EventResult::Emit(Msg::Focused(Fruit::Papaya))
        );
        state.cursor = Some(Fruit::Papaya);
        driver.render(&state, Rect::new(0, 0, 20, 1), &items());
        assert!(
            driver.row(1).contains("Papaya"),
            "the cursor scrolls back into view: {}",
            driver.row(1)
        );
    }

    #[test]
    fn hover_moves_the_cursor_and_reopening_reanchors_the_view() {
        let mut driver = Driver::new(20, 4);
        let mut state = State {
            open: true,
            cursor: Some(Fruit::Mango),
            ..State::default()
        };
        let area = Rect::new(0, 0, 20, 1);
        driver.render(&state, area, &items());

        assert_eq!(
            driver.event(mouse(MouseKind::Moved, 3, 2), &state),
            EventResult::Emit(Msg::Focused(Fruit::Papaya)),
            "hover moves the one cursor, as in List"
        );

        // Park the view away from the cursor, then close and reopen: the
        // parked offset dies with the panel's identity and the view anchors
        // to the cursor again.
        assert_eq!(
            driver.event(
                mouse(MouseKind::Scroll(ScrollDirection::Down), 3, 1),
                &state
            ),
            EventResult::Consumed
        );
        driver.render(&state, area, &items());
        assert!(driver.row(1).contains("Lychee"), "{}", driver.row(1));
        state.open = false;
        driver.render(&state, area, &items());
        state.open = true;
        driver.render(&state, area, &items());
        assert!(
            driver.row(1).contains("Mango"),
            "a reopened panel anchors to the cursor: {}",
            driver.row(1)
        );
    }

    #[test]
    fn custom_option_rows_preserve_explicit_span_colors() {
        let mut terminal = Terminal::new(TestBackend::new(20, 6)).expect("terminal");
        let mut ratcn = Ratcn::<State, Msg>::new();
        let state = State {
            open: true,
            selected: Some(Fruit::Mango),
            ..State::default()
        };
        let theme = Theme::default_dark();
        let mut style = SelectStyle::fallback();
        style.option_foreground = Color::Yellow;
        style.panel_background = Color::Blue;

        terminal
            .draw(|frame| {
                ratcn.render(frame, &state, &theme, |ctx| {
                    ctx.render_component(
                        "fruit",
                        select(items())
                            .render_item(|_: &State, row| {
                                if row.selected {
                                    Text::from(Span::styled(
                                        row.label.to_string(),
                                        Style::new().fg(Color::Magenta).bg(Color::Green),
                                    ))
                                } else {
                                    Text::from(row.label.to_string())
                                }
                            })
                            .style(move |_| style),
                        Rect::new(0, 0, 20, 1),
                    );
                });
            })
            .expect("draw");

        let buffer = terminal.backend().buffer();
        let explicit = buffer.cell((1, 1)).expect("explicitly colored span");
        assert_eq!(explicit.fg, Color::Magenta, "explicit colors win");
        assert_eq!(explicit.bg, Color::Green);
        let inherited = buffer.cell((1, 2)).expect("unstyled span");
        assert_eq!(
            inherited.fg,
            Color::Yellow,
            "unstyled text inherits the option-state colors"
        );
        assert_eq!(inherited.bg, Color::Blue);
    }

    /// Returning the cursor to where the wheel left it must not revive the
    /// parked view — the same rule `List` follows.
    #[test]
    fn a_released_wheel_park_never_revives() {
        let mut driver = Driver::new(20, 4);
        let mut state = State {
            open: true,
            cursor: Some(Fruit::Mango),
            ..State::default()
        };
        let area = Rect::new(0, 0, 20, 1);
        driver.render(&state, area, &items());
        driver.event(
            mouse(MouseKind::Scroll(ScrollDirection::Down), 3, 1),
            &state,
        );
        driver.render(&state, area, &items());
        assert!(driver.row(1).contains("Lychee"), "{}", driver.row(1));

        assert_eq!(
            driver.event(Event::Key(KeyEvent::new(KeyCode::Down)), &state),
            EventResult::Emit(Msg::Focused(Fruit::Papaya))
        );
        state.cursor = Some(Fruit::Papaya);
        driver.render(&state, area, &items());
        assert!(driver.row(1).contains("Papaya"), "{}", driver.row(1));

        assert_eq!(
            driver.event(Event::Key(KeyEvent::new(KeyCode::Up)), &state),
            EventResult::Emit(Msg::Focused(Fruit::Mango))
        );
        state.cursor = Some(Fruit::Mango);
        driver.render(&state, area, &items());
        assert!(
            driver.row(1).contains("Mango"),
            "returning to the wheel anchor must not re-park the view: {}",
            driver.row(1)
        );
    }

    /// A bound cursor on a disabled option is never silently moved elsewhere,
    /// and committing it is refused — `List`'s contract.
    #[test]
    fn a_disabled_cursor_is_neither_retargeted_nor_committed() {
        let mut items = items();
        items[1] = ListItem::new(Fruit::Papaya, "Papaya").disabled(true);
        let state = State {
            open: true,
            cursor: Some(Fruit::Papaya),
            ..State::default()
        };
        let mut component = select(items);
        component.prepare(&state);

        // The cursor really is on the disabled option: moving up from it
        // reaches Mango. A retargeted cursor would already be on Mango and
        // would have nowhere to go.
        assert_eq!(
            component.handle_event(
                &Event::Key(KeyEvent::new(KeyCode::Up)),
                &state,
                &mut EventCtx::default(),
            ),
            EventResult::Emit(Msg::Focused(Fruit::Mango))
        );
        for code in [KeyCode::Enter, KeyCode::Char(' ')] {
            assert_eq!(
                component.handle_event(
                    &Event::Key(KeyEvent::new(code)),
                    &state,
                    &mut EventCtx::default(),
                ),
                EventResult::Ignored,
                "{code:?} must not commit a disabled option"
            );
        }
    }

    /// An all-disabled Select is inert from the keyboard, as a `List` is: it
    /// does not even open onto a panel nothing can be chosen from.
    #[test]
    fn an_all_disabled_select_ignores_keys_instead_of_opening() {
        let items: Vec<ListItem<Fruit>> = items()
            .into_iter()
            .map(|item| {
                let value = *item.value();
                ListItem::new(value, item.label()).disabled(true)
            })
            .collect();
        let closed = State::default();
        let mut component = select(items);
        component.prepare(&closed);

        for code in [
            KeyCode::Enter,
            KeyCode::Char(' '),
            KeyCode::Up,
            KeyCode::Down,
        ] {
            assert_eq!(
                component.handle_event(
                    &Event::Key(KeyEvent::new(code)),
                    &closed,
                    &mut EventCtx::default(),
                ),
                EventResult::Ignored,
                "{code:?} must not open a Select with nothing to choose"
            );
        }
    }

    /// With nothing to commit to, a click still moves the cursor — `List`'s
    /// behavior for the same binding combination.
    #[test]
    fn clicking_without_a_selection_binding_moves_the_cursor() {
        let mut driver = Driver::new(20, 6);
        let state = State {
            open: true,
            cursor: Some(Fruit::Mango),
            ..State::default()
        };
        let theme = Theme::default_dark();
        let area = Rect::new(0, 0, 20, 1);
        driver
            .terminal
            .draw(|frame| {
                driver.ratcn.render(frame, &state, &theme, |ctx| {
                    ctx.render_component(
                        "fruit",
                        Select::new(items())
                            .open(|state: &State| state.open, Msg::Open)
                            .item_focus(|state: &State| state.cursor, Msg::Focused),
                        area,
                    );
                });
            })
            .expect("draw");

        assert_eq!(
            driver.event(mouse(MouseKind::Click(MouseButton::Left), 3, 2), &state),
            EventResult::Emit(Msg::Focused(Fruit::Papaya))
        );
    }

    /// The popup is not modal, so a key it has no use for reaches the app,
    /// exactly as it would over a `List`.
    #[test]
    fn an_open_select_does_not_swallow_app_hotkeys() {
        let state = State {
            open: true,
            cursor: Some(Fruit::Mango),
            ..State::default()
        };
        let mut component = select(items());
        component.prepare(&state);

        for code in [KeyCode::Delete, KeyCode::Backspace, KeyCode::F(5)] {
            assert_eq!(
                component.handle_event(
                    &Event::Key(KeyEvent::new(code)),
                    &state,
                    &mut EventCtx::default(),
                ),
                EventResult::Ignored,
                "{code:?} must bubble to the app"
            );
        }
    }

    #[test]
    fn panel_pointer_hit_testing_uses_painted_viewport() {
        let mut driver = Driver::new(20, 6);
        let state = State {
            open: true,
            cursor: Some(Fruit::Durian),
            ..State::default()
        };
        driver.render(&state, Rect::new(0, 0, 20, 1), &items());
        assert!(driver.row(2).contains("Papaya"), "{}", driver.row(2));
        assert_eq!(
            driver.event(mouse(MouseKind::Click(MouseButton::Left), 3, 2), &state),
            EventResult::Emit(Msg::Selected(Fruit::Papaya))
        );
    }

    #[test]
    fn outside_press_uses_the_open_bindings_close_message() {
        let mut driver = Driver::new(20, 8);
        let state = State {
            open: true,
            ..State::default()
        };
        driver.render(&state, Rect::new(0, 0, 20, 1), &items());
        assert_eq!(
            driver.event(mouse(MouseKind::Down(MouseButton::Left), 19, 7), &state),
            EventResult::Emit(Msg::Open(false))
        );
    }

    #[test]
    fn clicking_the_first_option_selects_it_where_the_panel_overlays_the_trigger() {
        let mut driver = Driver::new(20, 12);
        let state = State {
            open: true,
            ..State::default()
        };
        driver.render(&state, Rect::new(0, 4, 20, 1), &items());

        assert_eq!(
            driver.event(mouse(MouseKind::Down(MouseButton::Left), 3, 4), &state),
            EventResult::Consumed,
            "pressing the overlaid option must not dismiss the popup"
        );
        assert_eq!(
            driver.event(mouse(MouseKind::Click(MouseButton::Left), 3, 4), &state),
            EventResult::Emit(Msg::Selected(Fruit::Mango))
        );
    }

    #[test]
    fn closing_selection_cannot_commit_twice_before_redraw() {
        let mut driver = Driver::new(20, 12);
        let mut state = State {
            open: true,
            ..State::default()
        };
        driver.render(&state, Rect::new(0, 4, 20, 1), &items());
        let click = mouse(MouseKind::Click(MouseButton::Left), 3, 4);

        assert_eq!(
            driver.event(click.clone(), &state),
            EventResult::Emit(Msg::Selected(Fruit::Mango))
        );
        state.open = false;
        assert_eq!(
            driver.event(click, &state),
            EventResult::Consumed,
            "the retained popup reads current open state before handling the second click"
        );
    }

    #[test]
    fn popup_layers_above_content_inside_a_modal() {
        let mut terminal = Terminal::new(TestBackend::new(20, 8)).expect("terminal");
        let mut ratcn = Ratcn::<State, Msg>::new();
        let state = State {
            open: true,
            ..State::default()
        };
        let theme = Theme::default_dark();
        terminal
            .draw(|frame| {
                ratcn.render(frame, &state, &theme, |ctx| {
                    ctx.modal_scope("modal", frame_area(), ScopeOptions::default(), |ctx| {
                        ctx.render_component("fruit", select(items()), Rect::new(0, 0, 20, 1));
                        ctx.render_widget(Line::from("modal sibling"), Rect::new(0, 2, 20, 1));
                    });
                });
            })
            .expect("draw");
        let row: String = (0..20)
            .map(|column| {
                terminal
                    .backend()
                    .buffer()
                    .cell((column, 2))
                    .expect("cell")
                    .symbol()
            })
            .collect();
        assert!(row.contains("Papaya"), "{row}");
        assert!(!row.contains("modal sibling"));
    }

    #[test]
    fn vim_and_readline_keys_move_item_focus_only_while_open() {
        let open = State {
            open: true,
            cursor: Some(Fruit::Mango),
            ..State::default()
        };
        let mut component = select(items());
        component.prepare(&open);
        for down in [
            Event::Key(KeyEvent::new(KeyCode::Char('j'))),
            Event::Key(KeyEvent {
                code: KeyCode::Char('n'),
                modifiers: Modifiers {
                    ctrl: true,
                    ..Modifiers::NONE
                },
            }),
        ] {
            assert_eq!(
                component.handle_event(&down, &open, &mut EventCtx::default()),
                component.handle_event(
                    &Event::Key(KeyEvent::new(KeyCode::Down)),
                    &open,
                    &mut EventCtx::default(),
                ),
                "j and Ctrl+N do exactly what Down does"
            );
        }

        let closed = State {
            cursor: Some(Fruit::Mango),
            ..State::default()
        };
        let mut component = select(items());
        component.prepare(&closed);
        assert_eq!(
            component.handle_event(
                &Event::Key(KeyEvent::new(KeyCode::Char('j'))),
                &closed,
                &mut EventCtx::default(),
            ),
            EventResult::Emit(Msg::Open(true)),
            "a step key on a closed Select opens it, as Down does"
        );
        assert_eq!(
            component.handle_event(
                &Event::Key(KeyEvent::new(KeyCode::Char('x'))),
                &closed,
                &mut EventCtx::default(),
            ),
            EventResult::Ignored,
            "any other letter bubbles: there is no typeahead"
        );
    }

    #[test]
    fn open_selection_without_item_focus_is_pointer_only() {
        let state = State::default();
        let mut component = Select::new(items())
            .open(|state: &State| state.open, Msg::Open)
            .selection(|state: &State| state.selected, Msg::Selected);
        component.prepare(&state);

        assert!(!component.is_focusable(&state));
        assert_eq!(
            component.handle_event(
                &Event::Key(KeyEvent::new(KeyCode::Down)),
                &state,
                &mut EventCtx::default(),
            ),
            EventResult::Ignored
        );
        assert_eq!(
            component.handle_event(
                &mouse(MouseKind::Click(MouseButton::Left), 0, 0),
                &state,
                &mut EventCtx::default(),
            ),
            EventResult::Emit(Msg::Open(true))
        );
    }

    #[test]
    fn incomplete_binding_combinations_never_claim_keyboard_focus() {
        let state = State::default();
        let mut component = Select::new(items())
            .open(|state: &State| state.open, Msg::Open)
            .item_focus(|state: &State| state.cursor, Msg::Focused);
        component.prepare(&state);

        assert!(!component.is_focusable(&state));
        assert_eq!(
            component.handle_event(
                &Event::Key(KeyEvent::new(KeyCode::Down)),
                &state,
                &mut EventCtx::default(),
            ),
            EventResult::Ignored,
            "a Select without a selection commit channel must not consume keyboard navigation"
        );
    }

    fn tall_select(items: Vec<ListItem<Fruit>>) -> Select<Fruit, State, Msg> {
        select(items)
            .render_item(|_state: &State, row| {
                Text::from(vec![
                    Line::from(row.label.to_string()),
                    Line::from(format!("  focused={}", row.focused)),
                ])
            })
            .row_height(2)
    }

    #[test]
    fn custom_multi_row_options_render_at_the_declared_row_height() {
        let mut terminal = Terminal::new(TestBackend::new(20, 12)).expect("terminal");
        let mut ratcn = Ratcn::<State, Msg>::new();
        let state = State {
            open: true,
            cursor: Some(Fruit::Mango),
            ..State::default()
        };
        let theme = Theme::default_dark();
        terminal
            .draw(|frame| {
                ratcn.render(frame, &state, &theme, |ctx| {
                    ctx.render_component("fruit", tall_select(items()), Rect::new(0, 4, 20, 1));
                });
            })
            .expect("draw");

        let row = |y: u16| -> String {
            let buffer = terminal.backend().buffer();
            (0..20)
                .map(|x| buffer.cell((x, y)).expect("cell").symbol())
                .collect()
        };
        // Panel: border, then two rows per option.
        assert!(row(3).contains("Mango"), "{}", row(3));
        assert!(row(4).contains("focused=true"), "{}", row(4));
        assert!(row(5).contains("Papaya"), "{}", row(5));
        assert!(row(6).contains("focused=false"), "{}", row(6));
    }

    #[test]
    fn multi_row_click_hit_testing_divides_by_row_height() {
        let mut terminal = Terminal::new(TestBackend::new(20, 12)).expect("terminal");
        let mut ratcn = Ratcn::<State, Msg>::new();
        let state = State {
            open: true,
            cursor: Some(Fruit::Mango),
            ..State::default()
        };
        let theme = Theme::default_dark();
        terminal
            .draw(|frame| {
                ratcn.render(frame, &state, &theme, |ctx| {
                    ctx.render_component("fruit", tall_select(items()), Rect::new(0, 4, 20, 1));
                });
            })
            .expect("draw");

        // The first option occupies two rows; a click on its second row still
        // selects it, and the next option starts two rows down.
        assert_eq!(
            ratcn.handle_event(mouse(MouseKind::Click(MouseButton::Left), 3, 4), &state),
            EventResult::Emit(Msg::Selected(Fruit::Mango)),
            "the second line belongs to the first option"
        );
        assert_eq!(
            ratcn.handle_event(mouse(MouseKind::Click(MouseButton::Left), 3, 5), &state),
            EventResult::Emit(Msg::Selected(Fruit::Papaya))
        );
    }

    #[test]
    fn disabled_and_duplicate_item_behavior_is_preserved() {
        let state = State::default();
        let mut disabled = select(items()).disabled(true);
        disabled.prepare(&state);
        assert!(!disabled.is_focusable(&state));
        assert_eq!(
            disabled.handle_event(
                &Event::Key(KeyEvent::new(KeyCode::Enter)),
                &state,
                &mut EventCtx::default()
            ),
            EventResult::Ignored
        );

        let mut duplicate = select(vec![
            ListItem::new(Fruit::Mango, "Mango"),
            ListItem::new(Fruit::Mango, "Again"),
        ]);
        assert!(
            std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| duplicate.prepare(&state)))
                .is_err()
        );
    }
}