herogpui-components 0.12.0

HeroUI-style component library for GPUI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
//! ComboBox — port of `@heroui/combo-box` (v3).
//!
//! A text input combined with a selectable list. Unlike
//! [`Select`](crate::select::Select) the value is typed, and unlike
//! [`Autocomplete`](crate::autocomplete::Autocomplete) the list can be opened
//! without typing and `allowsCustomValue` decides whether input outside the
//! collection is accepted.
//!
//! Pinned v3.2.4 / React Aria Components 1.20.0 keep a stable `Key` separate
//! from each item's `textValue`: `selectedKey` / `defaultValue` /
//! `disabledKeys`, the selection callbacks and the form value address items
//! by key, while filtering and the visible text use the label. Items are
//! therefore [`crate::PickerItem`]s; using a label as the key made duplicate
//! labels alias each other's selection, disabled state and row identity.
//! Pinned HeroUI's ComboBox composition adds only slots, trigger and popover
//! chrome on the RAC primitive, so it overrides none of this.
//!
//! The input text is the query and the selected item's label, never the key:
//! picking a row fills the field with that row's label, and the cursor and
//! row identities ride the key so duplicate labels stay distinct. A committed
//! custom value carries a null selected key — pinned react-stately 3.49.0's
//! `commitCustomValue` sets the value to `null` and keeps the typed text —
//! which the [`ComboBox::on_selection_change_all`] slice reports as an empty
//! selection, and only when a selection actually existed; the single-key
//! [`ComboBox::on_selection_change`] cannot spell `null` and stays silent there.
//!
//! `formValue` (pinned React Aria Components 1.20.0) defaults to `"key"`: a
//! named field submits the selected key(s). `allowsCustomValue` forces
//! `"text"`, submitting the typed text instead.

use std::{
    cell::{Cell, RefCell},
    collections::HashMap,
    rc::{Rc, Weak},
    sync::Arc,
};

use gpui::{
    div, prelude::*, px, App, Entity, InteractiveElement, IntoElement, Pixels, RenderOnce,
    SharedString, Styled, Window,
};
use herogpui_core::{element_id, FieldVariant, Placement, SelectionMode};
use herogpui_theme::ActiveTheme;

use crate::{
    a11y::{self, A11y as _},
    icons,
    input::{Input, InputState},
    matches::{empty_matches, MatchesCache},
    picker_item::PickerItem,
    selection::{normalize_selection, toggle_key},
    util,
};

/// The port's local floor on the root field stack when `fullWidth` is off:
/// without a placeholder the inner input has no intrinsic width and the
/// trigger would collapse to just its chevron.
const TRIGGER_MIN_WIDTH: Pixels = px(180.);

/// When the suggestion list opens.
///
/// v3's table reads `"focus" | "input" | "manual"` with **`"focus"`** as the
/// default, so a v3 ComboBox shows its list as soon as the field is focused.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum MenuTrigger {
    /// Open as soon as the field gains focus. v3's default.
    #[default]
    Focus,
    /// Open on input, and when the trigger button is pressed.
    Input,
    /// Open only when the trigger button is pressed.
    Manual,
}

/// `formValue` — what a `name`d ComboBox submits.
///
/// Pinned React Aria Components 1.20.0 defaults to key and forces text when
/// `allowsCustomValue` is set: an input that accepts values outside the
/// collection always submits what was typed.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ComboBoxFormValue {
    /// The selected item key(s). The pinned default.
    #[default]
    Key,
    /// The typed input text.
    Text,
}

type OnSelectionChange = Arc<dyn Fn(&SharedString, &mut Window, &mut App) + 'static>;
type OnOpenChange = Arc<dyn Fn(&bool, &mut Window, &mut App) + 'static>;
type ComboBoxFormState = Rc<RefCell<crate::form::LiveFormFieldState>>;

thread_local! {
    static COMBO_BOX_FORM_STATES: RefCell<HashMap<u64, Weak<RefCell<crate::form::LiveFormFieldState>>>> =
        RefCell::new(HashMap::new());
}

fn combo_box_form_state(entity_id: u64) -> ComboBoxFormState {
    COMBO_BOX_FORM_STATES.with(|states| {
        let mut states = states.borrow_mut();
        if let Some(state) = states.get(&entity_id).and_then(|state| state.upgrade()) {
            return state;
        }
        let state = Rc::new(RefCell::new(crate::form::LiveFormFieldState {
            value: crate::form::FormValue::Keys(Vec::new()),
            is_invalid: false,
            is_successful: true,
            focus: None,
            restore: None,
        }));
        states.insert(entity_id, Rc::downgrade(&state));
        state
    })
}

/// Whether the pinned `formValue` serialization submits the input text:
/// `formValue="text"` explicitly, or `allowsCustomValue`, which pinned React
/// Aria Components 1.20.0 turns into text regardless of the prop.
fn form_submits_text(form_value: Option<ComboBoxFormValue>, allows_custom_value: bool) -> bool {
    allows_custom_value || form_value == Some(ComboBoxFormValue::Text)
}

/// The one-shot that keeps `MenuTrigger::Focus` from reopening a panel the
/// user dismissed while the field still has the focus.
///
/// `can_open` is true while a fresh focus session may open the list; opening
/// consumes it. `was_open` remembers the flag from the last frame, so a panel
/// that closes while the field stays focused (Escape, a pick, the chevron, a
/// press outside) reads as a dismissal rather than as a new focus to answer.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct FocusOpen {
    can_open: bool,
    was_open: bool,
}

/// Which suggestion the keyboard is on, held as the item's *key* so the
/// cursor stays on the same item when the query filters the list or the
/// caller reorders the collection. `hidden_query` retains the cursor across a
/// multiple-mode pick, which clears the query before the next frame can
/// re-derive the row: while the query equals the retained value the cursor
/// stays alive even when the capped or filtered list no longer renders its
/// item.
#[derive(Clone, Debug, PartialEq, Eq)]
struct ComboCursor {
    key: SharedString,
    hidden_query: Option<String>,
}

fn cursor_for(rows: &[PickerItem], index: usize, hidden_query: Option<String>) -> ComboCursor {
    ComboCursor {
        key: rows[index].key().clone(),
        hidden_query,
    }
}

fn cursor_position(rows: &[PickerItem], cursor: &ComboCursor) -> Option<usize> {
    rows.iter().position(|item| item.key() == &cursor.key)
}

/// The label an item key resolves to, or `None` when the key has no item in
/// the collection (still loading, or already removed).
fn label_of_key<'a>(items: &'a [PickerItem], key: &SharedString) -> Option<&'a SharedString> {
    items
        .iter()
        .find(|item| item.key() == key)
        .map(|item| item.label())
}

/// The rows the panel shows for `query`: the full collection under the
/// full-collection flag (which owns the frame, so no filter runs), otherwise
/// the custom `defaultFilter`'s decision — including what an empty query
/// means — or the default case-insensitive substring match. Filtering reads
/// the items' labels, never their keys.
fn compute_matches(
    items: &[PickerItem],
    query: &str,
    max_items: usize,
    full: bool,
    filter: Option<&Arc<dyn Fn(&str, &str) -> bool + 'static>>,
) -> Vec<PickerItem> {
    if full {
        return items.iter().take(max_items).cloned().collect();
    }
    if let Some(filter) = filter {
        return items
            .iter()
            .filter(|item| filter(item.label(), query))
            .take(max_items)
            .cloned()
            .collect();
    }
    if query.is_empty() {
        return items.iter().take(max_items).cloned().collect();
    }
    let lowered = query.to_lowercase();
    items
        .iter()
        .filter(|item| item.label().to_lowercase().contains(&lowered))
        .take(max_items)
        .cloned()
        .collect()
}

/// HeroUI ComboBox (controlled open state).
#[derive(IntoElement)]
pub struct ComboBox {
    state: Entity<InputState>,
    items: Vec<PickerItem>,
    /// `isOpen` — `None` leaves the component holding the flag, seeded from
    /// `defaultOpen`.
    is_open: Option<bool>,
    default_open: bool,
    placement: Placement,
    label: Option<SharedString>,
    placeholder: Option<SharedString>,
    description: Option<SharedString>,
    error_message: Option<SharedString>,
    variant: FieldVariant,
    menu_trigger: MenuTrigger,
    /// `defaultFilter` — decides whether an item matches the query. Receives
    /// the item's label; the key never reaches it.
    filter: Option<Arc<dyn Fn(&str, &str) -> bool + 'static>>,
    allows_custom_value: bool,
    max_items: usize,
    full_width: bool,
    /// Optional trigger geometry/chrome overrides; defaults are the stock box.
    field: util::FieldBox,
    is_disabled: bool,
    is_invalid: bool,
    is_required: bool,
    is_read_only: bool,
    /// `autoFocus` — take focus on the first render.
    auto_focus: bool,
    /// `ListLayout`'s `rowHeight`, which virtualizes the popover list.
    row_height: Option<Pixels>,
    /// Replaces the list rows' `px-2` horizontal padding.
    row_padding_x: Option<Pixels>,
    /// Replaces the list rows' `py-1.5` vertical padding.
    row_padding_y: Option<Pixels>,
    /// The fill a hovered row takes, in place of `--default`.
    row_hover_bg: Option<gpui::Hsla>,
    /// The family the option rows are drawn with; unset keeps the
    /// inherited family. A detached popover does not inherit the trigger's
    /// font.
    row_font_family: Option<SharedString>,
    /// The corner radius of the detached panel, in place of the owning
    /// `container_radius` helper.
    radius: Option<Pixels>,
    /// `validate` — run by the component, not the caller.
    validate: Option<crate::validation::Validator<str>>,
    /// `validationBehavior` — carried on the inner field.
    validation_behavior: Option<crate::form::ValidationBehavior>,
    /// `allowsEmptyCollection` — keeps the panel up with no matches.
    allows_empty_collection: bool,
    /// `name` — the name this field submits under.
    name: Option<SharedString>,
    /// `formValue` — `None` is the pinned `"key"` default; `allowsCustomValue`
    /// forces text whatever this says.
    form_value: Option<ComboBoxFormValue>,
    /// `shouldFocusWrap` — whether the arrow keys wrap at the ends of the list.
    should_focus_wrap: bool,
    /// `ListBox.Section` — a heading above the item with this key.
    sections: Vec<(SharedString, SharedString)>,
    /// `ListBox.ItemIndicator` — draws the tick. The closure is handed whether
    /// the row is the selected one.
    indicator: Option<Box<dyn Fn(bool) -> gpui::AnyElement + 'static>>,
    disabled_keys: std::collections::HashSet<SharedString>,
    selection_mode: SelectionMode,
    /// The selection as ordered unique item keys — pinned react-stately
    /// 3.49.0's `selectedKeys` is a JS `Set`, which iterates in insertion
    /// order, so the callbacks, the form value and `ComboBox.Value` follow
    /// the order the keys were picked (or the owner listed) in.
    selected_keys: Vec<SharedString>,
    /// Whether the caller drives the selection. An unset `selected_keys` is not
    /// an empty controlled selection: without this flag every plain ComboBox
    /// would hand its own picks back to a set nobody owns, and
    /// `ComboBox.Value` would never see them.
    is_controlled: bool,
    /// Whether `selected_key` owns the controlled single key. Only then does
    /// the render sync the input text to the key's label — and only when the
    /// key changes, never on the owner's other re-renders.
    selected_key_sync: bool,
    /// `ComboBox.Value` — draws the chosen item under the field.
    value_content: Option<Box<dyn Fn(util::SelectionValue<'_>) -> gpui::AnyElement + 'static>>,
    /// `defaultValue` — set it to hand this component its own selection.
    default_value: Option<Vec<SharedString>>,
    /// `defaultInputValue` — seeds the text state on the first render only.
    default_input_value: Option<SharedString>,
    /// `value` — the v3 alias of the controlled input text, stored for the
    /// first render only and winning over `defaultInputValue`.
    value: Option<SharedString>,
    on_selection_change_all: Option<Arc<dyn Fn(&[SharedString], &mut Window, &mut App) + 'static>>,
    on_input_change: Option<Arc<dyn Fn(&str, &mut Window, &mut App) + 'static>>,
    on_selection_change: Option<OnSelectionChange>,
    on_open_change: Option<OnOpenChange>,
    form_state: ComboBoxFormState,
    /// The `sx` slot, refined over the root style at the end of render.
    sx: Option<Box<gpui::StyleRefinement>>,
}

impl ComboBox {
    /// `selectionMode`
    pub fn selection_mode(mut self, mode: SelectionMode) -> Self {
        self.selection_mode = mode;
        self
    }

    /// `defaultValue` — the uncontrolled initial selection, as item keys.
    ///
    /// Supplying it hands the component its own selection set, seeded once;
    /// [`Self::selected_keys`] is the controlled spelling. The listed order is
    /// the selection's order, exactly as the owner listed it.
    /// `defaultInputValue` — the uncontrolled initial text.
    ///
    /// Written into the state on the first render only; [`Self::input_value`]
    /// is the controlled spelling.
    pub fn default_input_value(mut self, text: impl Into<SharedString>) -> Self {
        self.default_input_value = Some(text.into());
        self
    }

    pub fn default_value(
        mut self,
        keys: impl IntoIterator<Item = impl Into<SharedString>>,
    ) -> Self {
        self.default_value = Some(keys.into_iter().map(Into::into).collect());
        self
    }

    /// `selectedKeys` — the controlled selection, as item keys. The listed
    /// order is the owner's order and is preserved everywhere the selection
    /// is read.
    pub fn selected_keys(mut self, keys: impl IntoIterator<Item = SharedString>) -> Self {
        self.selected_keys = keys.into_iter().collect();
        self.is_controlled = true;
        self
    }

    /// Reports the whole selection: one key for a changed single pick by
    /// pointer, Enter or Tab, and all keys in multiple mode. Re-picking the
    /// current single key does not report a value change. A cleared input or
    /// committed custom value reports an empty slice only when a selection
    /// existed, matching React Stately 3.50.0's `onChange`/`null` contract.
    pub fn on_selection_change_all(
        mut self,
        handler: impl Fn(&[SharedString], &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_selection_change_all = Some(Arc::new(handler));
        self
    }

    /// `selectedKey` — the controlled single-selection key, or `null` spelled
    /// as the empty string. The selection rides the key; the input text is
    /// synced to the key's label only when that key actually changes, so an
    /// owner that passes the same key every render never clobbers the text
    /// being typed — pinned react-stately resets the input value when the
    /// selected key changes and leaves the input alone otherwise.
    pub fn selected_key(mut self, key: impl Into<String>) -> Self {
        let key = SharedString::from(key.into());
        self.selected_keys = if key.is_empty() {
            Vec::new()
        } else {
            vec![key]
        };
        self.is_controlled = true;
        self.selected_key_sync = true;
        self
    }

    /// `value` — the v3 alias of [`ComboBox::input_value`], the controlled
    /// input text, as a pure builder.
    pub fn value(self, value: impl Into<String>) -> Self {
        self.input_value(value)
    }

    /// `disabledKeys` — keys of the items that render but cannot be chosen.
    /// Disabled state is per key, so one of two same-label items can be
    /// disabled alone.
    pub fn disabled_keys(mut self, keys: impl IntoIterator<Item = SharedString>) -> Self {
        self.disabled_keys = keys.into_iter().collect();
        self
    }

    /// `autoFocus` — take focus on the first render.
    /// `ListLayout`'s `rowHeight` -- and what virtualizes the popover list.
    ///
    /// v3 wraps the list in `<Virtualizer layout={ListLayout}>` inside the
    /// popover; gpui's `uniform_list` builds only the rows in view, and it can do
    /// that because every row is this tall.
    pub fn row_height(mut self, h: impl Into<Pixels>) -> Self {
        self.row_height = Some(h.into());
        self
    }

    pub fn auto_focus(mut self, v: bool) -> Self {
        self.auto_focus = v;
        self
    }

    /// `validate` — returns the message to show, or `None` when the text is
    /// fine. The component runs it and surfaces the result.
    pub fn validate(mut self, f: impl Fn(&str) -> Option<SharedString> + 'static) -> Self {
        self.validate = Some(Arc::new(f));
        self
    }

    /// `validationBehavior` — `Allow` shows the message without blocking a
    /// form submission.
    pub fn validation_behavior(mut self, behavior: crate::form::ValidationBehavior) -> Self {
        self.validation_behavior = Some(behavior);
        self
    }

    /// `allowsEmptyCollection` — keeps the panel open when nothing matches.
    pub fn allows_empty_collection(mut self, v: bool) -> Self {
        self.allows_empty_collection = v;
        self
    }

    /// `shouldFocusWrap` — whether the arrow keys wrap at the ends of the list.
    pub fn should_focus_wrap(mut self, v: bool) -> Self {
        self.should_focus_wrap = v;
        self
    }

    /// `ListBox.Section` — a heading rendered above the item with this key.
    pub fn section_before(
        mut self,
        item: impl Into<SharedString>,
        label: impl Into<SharedString>,
    ) -> Self {
        self.sections.push((item.into(), label.into()));
        self
    }

    /// `ListBox.ItemIndicator` — draw the selected tick yourself.
    pub fn indicator(mut self, render: impl Fn(bool) -> gpui::AnyElement + 'static) -> Self {
        self.indicator = Some(Box::new(render));
        self
    }

    /// `ComboBox.Value` — draw the chosen item under the field.
    ///
    /// v3's `.combo-box__value` is an optional part (`text-sm
    /// text-field-foreground empty:hidden`), and the closure is handed the same
    /// render props the component passes down: `selectedItems` reaches
    /// `selected_items`, and `defaultChildren` is the row this port would draw.
    pub fn value_content(
        mut self,
        render: impl Fn(util::SelectionValue<'_>) -> gpui::AnyElement + 'static,
    ) -> Self {
        self.value_content = Some(Box::new(render));
        self
    }

    /// `name` — the name this field submits under.
    pub fn name(mut self, name: impl Into<SharedString>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// `formValue` — whether a `name`d field submits the selected key(s) or
    /// the typed text. `allowsCustomValue` forces the text whatever this says,
    /// as pinned React Aria Components 1.20.0 does.
    pub fn form_value(mut self, form_value: ComboBoxFormValue) -> Self {
        self.form_value = Some(form_value);
        self
    }

    /// The `Form` field this control submits, when it has a `name`.
    ///
    /// v3 discovers a field through the DOM; gpui gives a child no way to
    /// reach its ancestor, so the control hands the pair over instead. The
    /// live value follows the pinned `formValue` serialization — the selected
    /// key(s) by default, the typed text under `allowsCustomValue` — and the
    /// input keeps the implicit-Enter submission of the text control it is.
    /// A disabled control stays registered and is omitted from FormData.
    pub fn form_field(&self) -> Option<crate::form::FormField> {
        let name = self.name.clone()?;
        Some(
            crate::form::FormField::live_text(name, self.form_state.clone(), self.state.clone())
                .is_required(self.is_required),
        )
    }

    pub fn is_read_only(mut self, v: bool) -> Self {
        self.is_read_only = v;
        self
    }

    /// `inputValue` — the controlled input text, as a pure builder.
    ///
    /// The bound [`crate::InputState`] owns the text once the field renders,
    /// so this seeds the state on the first render only, winning over
    /// [`ComboBox::default_input_value`] the way v3's controlled prop outranks
    /// the uncontrolled seed; calling `.input_value(..)` twice keeps the last
    /// call, like every other builder here. [`ComboBox::value`] is v3's alias
    /// and writes the same slot. A later value is an imperative update rather
    /// than a builder: `state.update(cx, |s, _| s.set_value(..))`.
    pub fn input_value(mut self, value: impl Into<String>) -> Self {
        self.value = Some(SharedString::from(value.into()));
        self
    }

    /// `onInputChange` — fires as the text changes, where
    /// [`ComboBox::on_selection_change`] fires only on a pick.
    pub fn on_input_change(
        mut self,
        handler: impl Fn(&str, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_input_change = Some(Arc::new(handler));
        self
    }

    /// Single-key convenience alias for [`ComboBox::on_selection_change`].
    /// Use [`Self::on_selection_change_all`] for the complete `onChange` value,
    /// including an empty selection and multiple keys.
    pub fn on_change(
        self,
        handler: impl Fn(&SharedString, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_selection_change(handler)
    }

    pub fn new(state: Entity<InputState>, items: Vec<PickerItem>) -> Self {
        let form_state = combo_box_form_state(state.entity_id().as_u64());
        Self {
            state,
            items,
            is_open: None,
            default_open: false,
            placement: Placement::BottomStart,
            label: None,
            placeholder: None,
            description: None,
            error_message: None,
            variant: FieldVariant::Primary,
            menu_trigger: MenuTrigger::Focus,
            filter: None,
            allows_custom_value: false,
            max_items: 8,
            full_width: false,
            is_disabled: false,
            is_invalid: false,
            is_required: false,
            is_read_only: false,
            auto_focus: false,
            row_height: None,
            row_padding_x: None,
            row_padding_y: None,
            row_hover_bg: None,
            row_font_family: None,
            radius: None,
            field: util::FieldBox::default(),
            validate: None,
            validation_behavior: None,
            allows_empty_collection: false,
            name: None,
            form_value: None,
            should_focus_wrap: false,
            sections: Vec::new(),
            indicator: None,
            disabled_keys: std::collections::HashSet::new(),
            selection_mode: SelectionMode::Single,
            selected_keys: Vec::new(),
            is_controlled: false,
            selected_key_sync: false,
            value_content: None,
            default_value: None,
            default_input_value: None,
            value: None,
            on_selection_change_all: None,
            on_input_change: None,
            on_selection_change: None,
            on_open_change: None,
            form_state,
            sx: None,
        }
    }

    /// `placement` on `ComboBox.Popover`.
    pub fn placement(mut self, placement: Placement) -> Self {
        self.placement = placement;
        self
    }

    pub fn is_open(mut self, v: bool) -> Self {
        self.is_open = Some(v);
        self
    }
    /// `defaultOpen` — the uncontrolled initial state.
    ///
    /// Only consulted when `is_open` is not supplied; the component then owns
    /// the flag and its trigger toggles it.
    pub fn default_open(mut self, v: bool) -> Self {
        self.default_open = v;
        self
    }

    pub fn label(mut self, text: impl Into<SharedString>) -> Self {
        self.label = Some(text.into());
        self
    }

    pub fn placeholder(mut self, text: impl Into<SharedString>) -> Self {
        self.placeholder = Some(text.into());
        self
    }

    pub fn description(mut self, text: impl Into<SharedString>) -> Self {
        self.description = Some(text.into());
        self
    }

    pub fn error_message(mut self, text: impl Into<SharedString>) -> Self {
        self.error_message = Some(text.into());
        self
    }

    pub fn variant(mut self, variant: FieldVariant) -> Self {
        self.variant = variant;
        self
    }

    pub fn menu_trigger(mut self, trigger: MenuTrigger) -> Self {
        self.menu_trigger = trigger;
        self
    }

    /// `defaultFilter` — replaces the default case-insensitive substring
    /// match.
    ///
    /// Called as `filter(item_label, input)`: v3 filters on the item's
    /// `textValue`, never on its key, and owns the whole decision —
    /// including what an empty query means.
    pub fn filter(mut self, f: impl Fn(&str, &str) -> bool + 'static) -> Self {
        self.filter = Some(Arc::new(f));
        self
    }

    /// `allowsCustomValue` — accept text that matches no item. A committed
    /// custom value keeps the typed text and carries a null selected key.
    pub fn allows_custom_value(mut self, v: bool) -> Self {
        self.allows_custom_value = v;
        self
    }

    pub fn max_items(mut self, n: usize) -> Self {
        self.max_items = n.max(1);
        self
    }

    pub fn full_width(mut self, v: bool) -> Self {
        self.full_width = v;
        self
    }

    /// Replaces the trigger's 36px box height (forwarded to the inner field).
    pub fn height(mut self, h: impl Into<Pixels>) -> Self {
        self.field.height = Some(h.into());
        self
    }

    /// Replaces the trigger's `px-3` horizontal padding (forwarded to the
    /// inner field).
    pub fn padding_x(mut self, p: impl Into<Pixels>) -> Self {
        self.field.padding_x = Some(p.into());
        self
    }

    /// Renders the trigger with no background, border, field shadow or focus
    /// ring, for a caller painting around it. The list still opens.
    pub fn is_bare(mut self, v: bool) -> Self {
        self.field.is_bare = v;
        self.field.is_bare_is_set = true;
        self
    }

    /// Shows or hides only the editable trigger's visual focus ring. The
    /// trigger stays focusable and the list still opens when set to `false`.
    pub fn focus_ring(mut self, v: bool) -> Self {
        self.field.focus_ring = Some(v);
        self
    }

    /// Replaces the list rows' `px-2` horizontal padding.
    pub fn row_padding_x(mut self, p: impl Into<Pixels>) -> Self {
        self.row_padding_x = Some(p.into());
        self
    }

    /// Replaces the list rows' `py-1.5` vertical padding.
    pub fn row_padding_y(mut self, p: impl Into<Pixels>) -> Self {
        self.row_padding_y = Some(p.into());
        self
    }

    /// The fill a hovered row takes, in place of `--default`.
    pub fn row_hover_bg(mut self, color: impl Into<gpui::Hsla>) -> Self {
        self.row_hover_bg = Some(color.into());
        self
    }

    /// The family the option rows are drawn with; unset keeps the inherited
    /// family. A detached popover does not inherit the trigger's font.
    pub fn row_font_family(mut self, family: impl Into<SharedString>) -> Self {
        self.row_font_family = Some(family.into());
        self
    }

    /// The corner radius of the detached panel, in place of the owning
    /// `container_radius` helper. The panel's entry zoom interpolates the same
    /// value, so both follow the override. Not a v3 prop; the removed v2
    /// `radius` prop is prohibited and this is a per-component repository
    /// extension.
    ///
    /// The trigger is an inner [`crate::Input`] whose box the shared field
    /// chrome paints — `--field-radius`, not this value.
    pub fn radius(mut self, radius: impl Into<Pixels>) -> Self {
        self.radius = Some(radius.into());
        self
    }

    /// The one slot for caller-owned low-level styling: GPUI's styling methods
    /// (`bg`, `text_color`, `w`, `h`, `p`, `rounded`, `border_color`, …)
    /// applied to the combo box's root element after every value the variant
    /// and the active theme chose, so they win. The field paints its own
    /// chrome, so this reaches the box that chrome sits in, not the chrome.
    pub fn sx(mut self, style: impl FnOnce(gpui::Div) -> gpui::Div) -> Self {
        self.sx = Some(util::capture_sx(style));
        self
    }

    pub fn is_disabled(mut self, v: bool) -> Self {
        self.is_disabled = v;
        self
    }

    pub fn is_invalid(mut self, v: bool) -> Self {
        self.is_invalid = v;
        self
    }

    pub fn is_required(mut self, v: bool) -> Self {
        self.is_required = v;
        self
    }

    /// Pick-only single-key convenience callback.
    ///
    /// Use [`Self::on_selection_change_all`] for v3's complete
    /// `onChange` domain, including multiple selection and the `null` a
    /// cleared input or a committed custom value reports.
    pub fn on_selection_change(
        mut self,
        handler: impl Fn(&SharedString, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_selection_change = Some(Arc::new(handler));
        self
    }

    pub fn on_open_change(
        mut self,
        handler: impl Fn(&bool, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_open_change = Some(Arc::new(handler));
        self
    }
}

impl RenderOnce for ComboBox {
    fn render(mut self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        // One structured base id for the whole frame: every part below hangs
        // off it, so a hyphenated part name can never fold into a sibling's
        // key. Its `Display` is `combobox-<entity id>`, the spelling the parts
        // used to build with `format!`.
        let entity_id = self.state.entity_id().as_u64();
        let base_id = gpui::ElementId::named_usize("combobox", entity_id as usize);
        // One shared collection for the frame: the `'static` panel and event
        // closures clone the `Rc`, never the rows.
        let items: Rc<[PickerItem]> = self.items.into();

        // `value` / `defaultInputValue` seed the text once, before anything
        // reads it. `value` is v3's controlled spelling, so it outranks the
        // uncontrolled seed; the state owns the text afterwards, and
        // `InputState::set_value` is the imperative update.
        let seed = self.value.clone().or(self.default_input_value.clone());
        if let Some(text) = seed {
            let state = self.state.clone();
            util::seed_once(
                window,
                cx,
                element_id::scoped(&base_id, "default-text"),
                move |cx| {
                    state.update(cx, |s, cx| {
                        s.set_value(text.to_string());
                        cx.notify();
                    });
                },
            );
        }

        // `defaultValue` opts into the component holding its own selection;
        // `controlled` takes `cx` mutably, so it precedes the theme tokens.
        // Both spellings normalize to the `Set` shape first: duplicates
        // collapse to their first insertion, and single mode keeps one key.
        // A controlled order is the owner's order — nothing is sorted.
        let multiple = self.selection_mode == SelectionMode::Multiple;
        self.selected_keys = normalize_selection(self.selected_keys.clone(), multiple);
        let default_selection =
            normalize_selection(self.default_value.clone().unwrap_or_default(), multiple);
        let (selection, selection_own) = util::controlled(
            window,
            cx,
            element_id::scoped(&base_id, "selection"),
            self.is_controlled.then(|| self.selected_keys.clone()),
            default_selection.clone(),
        );
        self.selected_keys = selection;

        // `controlled` takes `cx` mutably, so it precedes the theme tokens.
        let (open_state, open_own) = util::controlled(
            window,
            cx,
            element_id::scoped(&base_id, "open"),
            self.is_open,
            self.default_open,
        );
        let (overlay_phase, dismissal_token) = util::overlay_scope(
            window,
            cx,
            element_id::scoped(&base_id, "overlay"),
            open_state,
            true,
        );
        let overlay_active = overlay_phase != util::OverlayPhase::Closed;
        // The field positioner discovers flips during prepaint. Keep its
        // resolved physical side keyed to this ComboBox so entry motion starts
        // from the side that is actually painted.
        let requested_placement = window.use_keyed_state(
            element_id::scoped(&base_id, "requested-placement"),
            cx,
            |_, _| self.placement,
        );
        let resolved_placement = window.use_keyed_state(
            element_id::scoped(&base_id, "resolved-placement"),
            cx,
            |_, _| Rc::new(Cell::new(None::<Placement>)),
        );
        if *requested_placement.read(cx) != self.placement {
            requested_placement.update(cx, |placement, _| *placement = self.placement);
            resolved_placement.read(cx).set(None);
        }
        let resolved_placement = resolved_placement.read(cx).clone();
        let entry_placement = resolved_placement.get().unwrap_or(self.placement);

        // Owned copies: `input.render` below needs `cx` mutably.
        let anchor_bounds: Rc<Cell<Option<gpui::Bounds<Pixels>>>> = window
            .use_keyed_state(element_id::scoped(&base_id, "anchor-bounds"), cx, |_, _| {
                Rc::new(Cell::new(None))
            })
            .read(cx)
            .clone();
        let colors = cx.colors().clone();
        let layout = cx.layout().clone();
        // One binding feeds every panel surface below: the painted panel and
        // the entry zoom that animates it. The trigger's own box is the held
        // field's, and the shared field chrome paints that one.
        let container_radius = self.radius.unwrap_or_else(|| util::container_radius(cx));
        let close_open = util::shared({
            let own = open_own.clone();
            let callback = self.on_open_change.clone();
            move |window: &mut Window, cx: &mut App| {
                let is_open = own.as_ref().map_or(open_state, |held| *held.read(cx));
                if !is_open {
                    return;
                }
                if let Some(held) = &own {
                    held.update(cx, |value, cx| {
                        *value = false;
                        cx.notify();
                    });
                }
                if let Some(callback) = &callback {
                    callback(&false, window, cx);
                }
            }
        });
        let raw_query = self.state.read(cx).value().to_owned();
        let is_invalid = self.is_invalid || self.error_message.is_some();
        let focus_handle = self.state.read(cx).focus_handle.clone();

        // The live form value follows the pinned `formValue` serialization:
        // the selected key(s) by default, the typed text when
        // `allowsCustomValue` forces text mode. Success and validity are the
        // inner input's own mirrors (`live_text` reads them there), so only
        // the value and the focus handle — the handle a blocked submit must
        // reach — live in this shared state.
        let form_text = form_submits_text(self.form_value, self.allows_custom_value);
        {
            let mut form = self.form_state.borrow_mut();
            form.value = if form_text {
                crate::form::FormValue::Text(SharedString::from(raw_query.clone()))
            } else {
                crate::form::FormValue::Keys(self.selected_keys.clone())
            };
            form.focus = Some(focus_handle.clone());
        }

        // `selected_key`'s controlled sync: the owner hands the same key to
        // the builder every render, so the label may move into the input only
        // when that key actually changes — writing it every frame would
        // clobber the text being typed. The empty string is v3's `null` and
        // clears the input; a key with no item resolves to no label.
        if self.selected_key_sync {
            let applied_key =
                window.use_keyed_state(element_id::scoped(&base_id, "applied-key"), cx, |_, _| {
                    None::<SharedString>
                });
            let owned_key = self.selected_keys.first().cloned().unwrap_or_default();
            let first_apply = applied_key.read(cx).is_none();
            if applied_key.read(cx).clone() != Some(owned_key.clone()) {
                // Pinned `getDefaultInputValue` derives the text from the
                // selected key only when no `defaultInputValue` was given, so
                // the first application must leave the seeded text in place —
                // `value` seeds the same slot and is owed the same leave-alone;
                // later key changes still move their labels in.
                if !(first_apply && (self.default_input_value.is_some() || self.value.is_some())) {
                    let label = label_of_key(&items, &owned_key)
                        .cloned()
                        .unwrap_or_default();
                    self.state.update(cx, |state, cx| {
                        state.set_value(label.to_string());
                        cx.notify();
                    });
                }
                applied_key.update(cx, |v, _| *v = Some(owned_key));
            }
        }

        // A reset restores the default selection and the label it resolves
        // to, the way pinned react-stately resets `selectedKey` and lets
        // `resetInputValue` re-derive the text — reporting the restored text
        // through `onInputChange` when it actually changed, as the pinned
        // controlled input state does.
        let restore_own = selection_own.clone();
        let restore_state = Rc::downgrade(&self.form_state);
        let restore_input = self.state.clone();
        let restore_items = items.clone();
        let restore_default = default_selection;
        let restore_input_change = self.on_input_change.clone();
        let restore_all = self.on_selection_change_all.clone();
        self.form_state.borrow_mut().restore = (restore_own.is_some() || restore_all.is_some())
            .then(|| {
                util::shared(move |window: &mut Window, cx: &mut App| {
                    let default_text = restore_default
                        .first()
                        .and_then(|key| label_of_key(&restore_items, key))
                        .cloned()
                        .unwrap_or_default();
                    if let Some(state) = restore_state.upgrade() {
                        state.borrow_mut().value =
                            crate::form::FormValue::Keys(restore_default.clone());
                    }
                    let input_changed = restore_input.read(cx).value() != default_text.as_ref();
                    restore_input.update(cx, |state, cx| {
                        state.set_value(default_text.to_string());
                        cx.notify();
                    });
                    if input_changed {
                        if let Some(cb) = &restore_input_change {
                            cb(&default_text, window, cx);
                        }
                    }
                    if let Some(held) = &restore_own {
                        let keys = restore_default.clone();
                        held.update(cx, |v, cx| {
                            *v = keys;
                            cx.notify();
                        });
                    }
                    if let Some(cb) = &restore_all {
                        cb(&restore_default, window, cx);
                    }
                }) as Arc<dyn Fn(&mut Window, &mut App)>
            });

        let show_all_items = window.use_keyed_state(
            element_id::scoped(&base_id, "show-all-items"),
            cx,
            |_, _| false,
        );
        let last_query =
            window.use_keyed_state(element_id::scoped(&base_id, "last-query"), cx, |_, _| {
                raw_query.clone()
            });
        if *last_query.read(cx) != raw_query {
            last_query.update(cx, |value, _| value.clone_from(&raw_query));
            show_all_items.update(cx, |value, _| *value = false);
        }
        let display_full_collection =
            *show_all_items.read(cx) || (self.menu_trigger == MenuTrigger::Manual && !open_state);

        // Which suggestion the keyboard is on. Input edits clear it, matching
        // React Stately's focused-key reset before the filtered list changes.
        // Created ahead of the matches: the idle gate below reads it.
        let cursor = window.use_keyed_state(element_id::scoped(&base_id, "cursor"), cx, |_, _| {
            None::<ComboCursor>
        });

        // Closed and idle frames draw no rows, so they skip the match work
        // entirely; a consuming filtered frame shares one cached list until
        // the query, collection or cap changes. Full-collection and
        // empty-query frames copy their capped prefix directly: no per-row
        // matching runs for them, so the cache's element-by-element key
        // comparison would cost more than the work it saves. A custom
        // `defaultFilter` owns the whole filtering decision, including an
        // empty query, and its configuration cannot join a cache key — its
        // results are never cached and it only runs while the matches are
        // consumed.
        let matches_cache =
            window.use_keyed_state(element_id::scoped(&base_id, "matches"), cx, |_, _| {
                MatchesCache::default()
            });
        // Keep the last open collection for the retained exit frame. Closing
        // a row can update the input text in the same dispatch; React Aria
        // keeps the old rows under its fade and does not re-run a custom
        // filter for that committed label.
        let retained_matches = window.use_keyed_state(
            element_id::scoped(&base_id, "retained-matches"),
            cx,
            |_, _| empty_matches(),
        );
        let consume_matches = overlay_active
            || cursor.read(cx).is_some()
            || (self.allows_custom_value && !raw_query.is_empty());
        let matches: Rc<[PickerItem]> = if overlay_phase == util::OverlayPhase::Exiting {
            retained_matches.read(cx).clone()
        } else if !consume_matches {
            empty_matches()
        } else {
            let filter = self.filter.clone();
            match &filter {
                Some(f) => Rc::from(compute_matches(
                    &items,
                    &raw_query,
                    self.max_items,
                    display_full_collection,
                    Some(f),
                )),
                None if display_full_collection => Rc::from(compute_matches(
                    &items,
                    &raw_query,
                    self.max_items,
                    true,
                    None,
                )),
                None if raw_query.is_empty() => Rc::from(compute_matches(
                    &items,
                    &raw_query,
                    self.max_items,
                    false,
                    None,
                )),
                None => matches_cache.update(cx, |cache, _| {
                    cache.get(items.clone(), raw_query.as_str(), self.max_items, |items| {
                        compute_matches(items, &raw_query, self.max_items, false, None)
                    })
                }),
            }
        };
        if overlay_phase == util::OverlayPhase::Open {
            retained_matches.update(cx, |value, _| *value = matches.clone());
        }

        // `MenuTrigger::Focus` opens the list when the field takes focus. The
        // check reads the focus handle every frame; the keyed state is the
        // one-shot that stops the panel from reopening behind a dismissal
        // (Escape, a pick, the chevron, a press outside) while the field keeps
        // the focus -- the frame after closing would otherwise re-answer the
        // still-held focus. The focus leaving resets it, so the *next* focus
        // session opens again.
        let focus_open =
            if self.menu_trigger == MenuTrigger::Focus && !self.is_disabled && !self.is_read_only {
                Some(window.use_keyed_state(
                    element_id::scoped(&base_id, "focus-open"),
                    cx,
                    |_, _| FocusOpen {
                        can_open: true,
                        was_open: false,
                    },
                ))
            } else {
                None
            };
        if let Some(focus_open) = &focus_open {
            let focused = self.state.read(cx).focus_handle.is_focused(window);
            let mut held = *focus_open.read(cx);
            let mut now_open = open_state;
            if focused && !open_state && held.was_open {
                // The list closed while the field still has the focus: the
                // user dismissed it, so it must not come back.
                held.can_open = false;
            } else if focused && !open_state && held.can_open {
                // A fresh focus session: the field taking focus is the
                // gesture, when there is something to show -- the panel's own
                // gate of a non-empty result or an allowed empty state.
                let can_show = !items.is_empty() || self.allows_empty_collection;
                if can_show {
                    show_all_items.update(cx, |v, _| *v = true);
                    // Opening from focus writes both halves, the way the
                    // chevron's handler does: the uncontrolled flag, and the
                    // report to a controlled caller.
                    if let Some(open) = &open_own {
                        open.update(cx, |v, cx| {
                            *v = true;
                            cx.notify();
                        });
                    }
                    if let Some(cb) = &self.on_open_change {
                        cb(&true, window, cx);
                    }
                    held.can_open = false;
                    now_open = true;
                }
            }
            if !focused {
                // The focus left; the next focus session may open again.
                held.can_open = true;
            }
            held.was_open = now_open;
            focus_open.update(cx, |v, _| *v = held);
        }

        let on_open_change = self.on_open_change.clone();
        let is_open = open_state;
        // Whether the pointer went down inside the input-plus-panel subtree.
        // The panel's outside-press listener reads only the panel bounds, so
        // the input is geometrically outside it even though both belong to the
        // same ComboBox. Capture the whole subtree for one dispatch: input
        // presses keep the list open, and the chevron or a row owns its click.
        let inside_pressed = Rc::new(Cell::new(false));
        // `.combo-box__trigger` is `border-none bg-transparent
        // text-field-placeholder`, and its hover recolours the text to
        // `text-field-foreground`, filling nothing. `svg()` paints from its own
        // style rather than the inherited text color, so the hover refinement
        // goes on the glyph as well as the trigger that wraps it.
        let trigger_hover_fg = colors.field.foreground;
        let trigger_indicator = crate::anim::rotating_indicator_with_duration(
            &element_id::scoped(&base_id, "trigger-indicator"),
            is_open,
            gpui::svg()
                .size(util::FIELD_ICON)
                .path(icons::CHEVRON_DOWN)
                .text_color(colors.muted)
                .when(!self.is_disabled && !self.is_read_only, |glyph| {
                    glyph.hover(move |st| st.text_color(trigger_hover_fg))
                }),
            150,
            window,
            cx,
        );
        let mut trigger = div()
            .id(element_id::scoped(&base_id, "trigger"))
            // `combo-box/combo-box.js` composes an RAC `Button` here, whose
            // props come from `useComboBox`'s `buttonProps` — i.e.
            // `useMenuTrigger({type: 'listbox'})`, so
            // `.../overlays/useOverlayTrigger.mjs` gives it
            // `'aria-haspopup': 'listbox'`, `'aria-expanded': isOpen` and
            // `'aria-controls'`. Only the expansion flag ports; the other two
            // are recorded omissions in `crate::a11y`.
            .a11y(a11y::Role::Button)
            .a11y_expanded(is_open)
            .flex()
            .items_center()
            .justify_center()
            .flex_shrink_0()
            .size(px(20.))
            .rounded(px(6.))
            .text_color(colors.muted)
            .child(trigger_indicator);
        if !self.is_disabled && !self.is_read_only {
            trigger = trigger
                .cursor(util::interactive_cursor(cx))
                .hover(move |s| s.text_color(trigger_hover_fg));
            if on_open_change.is_some() || open_own.is_some() {
                let own = open_own.clone();
                let focus_open = focus_open.clone();
                let show_all_items = show_all_items.clone();
                let close = close_open.clone();
                trigger = trigger
                    // The chevron is a separate React Aria button. Focus the
                    // input on press start, but do not let its down bubble into
                    // the input row and also trigger the default focus-open path.
                    .on_mouse_down(gpui::MouseButton::Left, move |_, window, cx| {
                        if let Some(focus_open) = &focus_open {
                            focus_open.update(cx, |v, _| v.can_open = false);
                        }
                        window.focus(&focus_handle, cx);
                        cx.stop_propagation();
                    })
                    .on_click(move |_, window, cx| {
                        if is_open {
                            close(window, cx);
                            return;
                        }
                        show_all_items.update(cx, |v, _| *v = true);
                        if let Some(held) = &own {
                            held.update(cx, |v, cx| {
                                *v = true;
                                cx.notify();
                            });
                        }
                        if let Some(cb) = &on_open_change {
                            cb(&true, window, cx);
                        }
                    });
            }
        }

        let cursor_on_change = cursor.clone();
        let validate = self.validate.clone();
        let mut input = Input::new(self.state.clone())
            .variant(self.variant)
            .is_disabled(self.is_disabled)
            .is_invalid(is_invalid)
            .is_required(self.is_required)
            .is_read_only(self.is_read_only)
            .auto_focus(self.auto_focus)
            .when_some(self.validation_behavior, |i, b| i.validation_behavior(b))
            .when_some(validate, |i, f| i.validate(move |v| f(v)))
            .end_content(trigger);
        input = input.with_field_box(self.field);
        // Edits open Focus and Input triggers only when there is something to
        // show, and close an already-open filtered collection when it empties.
        // Manual stays closed until its trigger opens it, then edits switch it
        // from the full collection to filtered rows.
        let input_change = self.on_input_change.clone();
        let open_own_on_change = open_own.clone();
        let open_change_cb = self.on_open_change.clone();
        let focus_open_on_change = focus_open.clone();
        let show_all_items_on_change = show_all_items.clone();
        let items_on_change = items.clone();
        let filter_on_change = self.filter.clone();
        let menu_trigger_on_change = self.menu_trigger;
        let allows_empty_collection = self.allows_empty_collection;
        let was_open = open_state;
        let selection_own_on_change = selection_own.clone();
        let selected_on_change = self.selected_keys.clone();
        let selection_mode_on_change = self.selection_mode;
        let selection_change_on_input = self.on_selection_change_all.clone();
        let input_value_on_change = raw_query.clone();
        let close_on_empty = close_open.clone();
        input = input.on_change(move |text, window, cx| {
            if let Some(cb) = &input_change {
                cb(text, window, cx);
            }
            cursor_on_change.update(cx, |v, _| *v = None);

            if selection_mode_on_change == SelectionMode::Single
                && !input_value_on_change.is_empty()
                && text.is_empty()
                && !selected_on_change.is_empty()
            {
                if let Some(held) = &selection_own_on_change {
                    held.update(cx, |value, cx| {
                        value.clear();
                        cx.notify();
                    });
                }
                if let Some(cb) = &selection_change_on_input {
                    cb(&[], window, cx);
                }
            }

            let is_open = open_own_on_change
                .as_ref()
                .map_or(was_open, |held| *held.read(cx));

            // A row pick closes the uncontrolled popup before copying the
            // selected label into the input. React Aria batches those updates
            // and does not run the custom filter for the value that is being
            // committed into a now-closing field. Preserve that boundary so
            // the retained exit frame stays visual-only and the filter's
            // callback count does not change on a pick.
            let closing_after_pick = was_open && !is_open;
            let has_matches = if closing_after_pick {
                true
            } else {
                match &filter_on_change {
                    Some(f) => items_on_change.iter().any(|item| f(item.label(), text)),
                    None if text.is_empty() => !items_on_change.is_empty(),
                    None => {
                        let query = text.to_lowercase();
                        items_on_change
                            .iter()
                            .any(|item| item.label().to_lowercase().contains(&query))
                    }
                }
            };
            let can_show = has_matches || allows_empty_collection;

            if !is_open && menu_trigger_on_change != MenuTrigger::Manual && can_show {
                if let Some(focus_open) = &focus_open_on_change {
                    focus_open.update(cx, |v, _| v.can_open = false);
                }
                if let Some(held) = &open_own_on_change {
                    held.update(cx, |v, cx| {
                        *v = true;
                        cx.notify();
                    });
                }
                if let Some(cb) = &open_change_cb {
                    cb(&true, window, cx);
                }
            } else if is_open && !can_show {
                close_on_empty(window, cx);
            }

            show_all_items_on_change.update(cx, |v, cx| {
                *v = false;
                cx.notify();
            });
            if menu_trigger_on_change == MenuTrigger::Manual {
                cx.refresh_windows();
            }
        });

        if self.full_width {
            input = input.full_width();
        }
        if let Some(label) = self.label.clone() {
            input = input.label(label);
        }
        if let Some(placeholder) = self.placeholder.clone() {
            input = input.placeholder(placeholder);
        }
        if is_invalid {
            if let Some(message) = self.error_message.clone() {
                input = input.error_message(message);
            }
        } else if let Some(description) = self.description.clone() {
            input = input.description(description);
        }

        let stale_cursor = cursor.read(cx).as_ref().is_some_and(|focused| {
            let visible = cursor_position(&matches, focused).is_some();
            let retained_hidden = focused.hidden_query.as_deref() == Some(raw_query.as_str())
                && items.iter().any(|item| item.key() == &focused.key);
            self.disabled_keys.contains(&focused.key) || (!visible && !retained_hidden)
        });
        if stale_cursor {
            cursor.update(cx, |value, _| *value = None);
        }
        let cursor_at = cursor
            .read(cx)
            .as_ref()
            .and_then(|focused| cursor_position(&matches, focused));
        // React Aria keeps the focused row in view; the panel scrolls and the
        // virtual list scrolls itself. `use_keyed_state` takes `cx` mutably.
        let list_scroll =
            window.use_keyed_state(element_id::scoped(&base_id, "list-scroll"), cx, |_, _| {
                gpui::UniformListScrollHandle::new()
            });
        let panel_scroll =
            window.use_keyed_state(element_id::scoped(&base_id, "panel-scroll"), cx, |_, _| {
                gpui::ScrollHandle::new()
            });
        let list_scroll_now = list_scroll.read(cx).clone();
        let panel_scroll_now = panel_scroll.read(cx).clone();

        // ComboBox commits its text/selection when focus leaves even while the
        // list is closed. This is `useComboBoxState.setFocused(false)`, not the
        // generic popover close used by Select-family controls.
        let commit_value = util::shared({
            let state = self.state.clone();
            let selection_own = selection_own.clone();
            let selected = self.selected_keys.clone();
            let items = items.clone();
            let selection_change = self.on_selection_change_all.clone();
            let input_change = self.on_input_change.clone();
            let allows_custom = self.allows_custom_value;
            move |window: &mut Window, cx: &mut App| {
                let current = state.read(cx).value().to_owned();
                let selected_text = selected
                    .first()
                    .and_then(|key| label_of_key(&items, key))
                    .cloned()
                    .unwrap_or_default();

                if allows_custom {
                    // Pinned react-stately's commit path: text that no longer
                    // matches the selected item's label is a custom value,
                    // which carries a null selected key.
                    if !multiple && current != selected_text && !selected.is_empty() {
                        if let Some(held) = &selection_own {
                            held.update(cx, |value, cx| {
                                value.clear();
                                cx.notify();
                            });
                        }
                        if let Some(callback) = &selection_change {
                            callback(&[], window, cx);
                        }
                    }
                    return;
                }

                let committed = if multiple {
                    String::new()
                } else {
                    selected_text.to_string()
                };
                if current != committed {
                    state.update(cx, |state, cx| {
                        state.set_value(committed.clone());
                        cx.notify();
                    });
                    if let Some(callback) = &input_change {
                        callback(&committed, window, cx);
                    }
                }
            }
        });
        let blur_close = close_open.clone();
        let blur_commit = commit_value.clone();
        let blur_scope = util::on_focus_leave(
            window,
            cx,
            &base_id,
            !self.is_disabled,
            move |window, cx| {
                blur_commit(window, cx);
                blur_close(window, cx);
            },
        );
        let blur_focus = blur_scope.focus_handle();

        // `.combo-box__input-group` is the field itself (`relative
        // inline-flex items-center`). The popup anchors to the Input's 36px
        // field row — not to the label-to-value wrapper root — the way RAC's
        // `triggerRef` reads `groupRef.current || inputRef.current` (pinned
        // 1.20.0 `dist/private/ComboBox.js`). `.combo-box__value` sits below
        // the field inside the root, so a value row that appears under it
        // must not push the popover down. `scrollable_field_popover` below
        // reads these bounds to flip and cap the panel; the measure element
        // inside `Input` only records them.
        let inside_pressed_for_group = inside_pressed.clone();
        let field_selector = format!("combobox-field-{entity_id}");
        input = input.field_anchor(anchor_bounds.clone(), field_selector);
        let input_group = div()
            .id(element_id::scoped(&base_id, "field"))
            // `combo-box/combo-box.js`'s `ComboBox.InputGroup` renders RAC
            // `Group`, and `react-aria-components/dist/private/Group.mjs` is
            // `role: props.role ?? 'group'`.
            //
            // The `role="combobox"` that `useComboBox` puts on the *input*
            // does not appear anywhere in this port: the field is a
            // `crate::input::Input`, whose role is decided inside its own
            // render from its `InputType` and which has no override prop.
            // See the picker note in `crate::a11y`.
            .a11y(a11y::Role::Group)
            .relative()
            .capture_any_mouse_down(move |_, _, cx| {
                inside_pressed_for_group.set(true);
                let pressed = inside_pressed_for_group.clone();
                cx.defer(move |_| pressed.set(false));
            })
            .child(input.render(window, cx));
        let mut root = div()
            .when(!self.full_width, |e| e.min_w(TRIGGER_MIN_WIDTH))
            .relative()
            .flex()
            .flex_col()
            .gap(px(4.));

        // `ComboBox.Value` — `.combo-box__value` is `text-sm
        // text-field-foreground empty:hidden`, so it shows only once something
        // is chosen. The selection is read in its own order — pinned
        // react-stately 3.49.0's `selectedKeys` is a JS `Set`, which iterates
        // in insertion order — and each key resolves to its item wherever that
        // item now sits; a key with no item renders nothing.
        let mut value_content = None;
        if let Some(render) = self.value_content.take() {
            let mut labels: Vec<SharedString> = Vec::new();
            let mut indices: Vec<usize> = Vec::new();
            for key in &self.selected_keys {
                if let Some((index, item)) =
                    items.iter().enumerate().find(|(_, it)| it.key() == key)
                {
                    labels.push(item.label().clone());
                    indices.push(index);
                }
            }
            let text = labels
                .iter()
                .map(ToString::to_string)
                .collect::<Vec<_>>()
                .join(", ");
            let value_selector = format!("combobox-value-{entity_id}");
            let default_children = div()
                .debug_selector(move || value_selector)
                .w_full()
                .min_w_0()
                .whitespace_normal()
                .text_size(util::FIELD_TEXT)
                .line_height(px(20.))
                .text_color(colors.field.foreground)
                .child(text.clone())
                .into_any_element();
            value_content = Some(render(util::SelectionValue {
                selected_items: &labels,
                selected_indices: &indices,
                selected_keys: Some(&self.selected_keys),
                selected_text: &text,
                is_placeholder: labels.is_empty(),
                default_children,
            }));
        }

        // `allowsEmptyCollection` keeps the panel up with no matches. Without
        // it an empty result closes the list; `allowsCustomValue` only changes
        // what Enter commits while the list is closed.
        // Up, down, Home, End and Enter walk the suggestions; the inner input
        // keeps left and right for the caret.
        if !self.is_disabled && !self.is_read_only {
            let key_rows: Rc<[PickerItem]> =
                if open_state || (self.allows_custom_value && !raw_query.is_empty()) {
                    Rc::clone(&matches)
                } else {
                    items
                        .iter()
                        .take(self.max_items)
                        .cloned()
                        .collect::<Vec<_>>()
                        .into()
                };
            let stops: Vec<usize> = (0..key_rows.len())
                .filter(|i| {
                    key_rows
                        .get(*i)
                        .is_some_and(|item| !self.disabled_keys.contains(item.key()))
                })
                .collect();
            let held = cursor.clone();
            let wrap = self.should_focus_wrap;
            let virtual_rows = self.row_height.is_some();
            let key_list_scroll = list_scroll_now.clone();
            let key_panel_scroll = panel_scroll_now.clone();
            let rows = key_rows;
            let state = self.state.clone();
            let allows_custom_value = self.allows_custom_value;
            let was_open = open_state;
            let show_all_items = show_all_items.clone();
            let on_selection_change = self.on_selection_change.clone();
            let on_selection_change_all = self.on_selection_change_all.clone();
            let on_input_change = self.on_input_change.clone();
            let selected_now = self.selected_keys.clone();
            let key_query = raw_query.clone();
            let key_display_full = display_full_collection;
            let key_items = items.clone();
            let key_filter = self.filter.clone();
            let key_max_items = self.max_items;
            let key_disabled = self.disabled_keys.clone();
            let key_menu_trigger = self.menu_trigger;
            let open_own_keys = open_own.clone();
            let on_open_change = self.on_open_change.clone();
            let key_selection_own = selection_own.clone();
            let key_close = close_open.clone();
            let key_blur = blur_scope.clone();
            let key_multiple = multiple;
            root = root.on_key_down(move |event, window, cx| {
                let key = event.keystroke.key.as_str();
                let is_open = open_own_keys
                    .as_ref()
                    .map_or(was_open, |held| *held.read(cx));
                let stale_cursor = held.read(cx).as_ref().is_some_and(|focused| {
                    let current_query = state.read(cx).value().to_owned();
                    let display_full = (current_query == key_query && *show_all_items.read(cx))
                        || (key_menu_trigger == MenuTrigger::Manual && !is_open);
                    let current_rows: Rc<[PickerItem]> =
                        if !(is_open || (allows_custom_value && !current_query.is_empty())) {
                            key_items
                                .iter()
                                .take(key_max_items)
                                .cloned()
                                .collect::<Vec<_>>()
                                .into()
                        } else if current_query == key_query
                            && is_open == was_open
                            && display_full == key_display_full
                        {
                            Rc::clone(&rows)
                        } else {
                            compute_matches(
                                &key_items,
                                &current_query,
                                key_max_items,
                                display_full,
                                key_filter.as_ref(),
                            )
                            .into()
                        };
                    let visible = cursor_position(&current_rows, focused).is_some();
                    let retained_hidden = focused.hidden_query.as_deref()
                        == Some(current_query.as_str())
                        && key_items.iter().any(|item| item.key() == &focused.key);
                    key_disabled.contains(&focused.key) || (!visible && !retained_hidden)
                });
                if stale_cursor {
                    held.update(cx, |value, _| *value = None);
                }
                // `allowsCustomValue` is the promise behind the drawn hint
                // "Press Enter to use this value". A no-match query has no
                // cursor row at all (an empty stop list makes `resolve` report
                // Ignore, so the Activate arm never runs). Pinned
                // react-stately's `commitCustomValue` keeps the typed text and
                // sets the value to null: the selection clears, and the slice
                // callback reports it only when a selection actually existed.
                // Text that still matches the selected item's label is not a
                // custom value at all — pinned `commitValue` re-runs
                // `commitSelection` there, so the selection stands and the
                // callbacks stay silent. The existing single-value commit
                // remains single-mode only; React Aria keeps multiple-mode
                // custom input independent from the selected items.
                if allows_custom_value
                    && key == "enter"
                    && !state.read(cx).value().is_empty()
                    && held.read(cx).as_ref().is_none_or(|focused| {
                        stale_cursor || cursor_position(&rows, focused).is_none()
                    })
                {
                    let selected_label = selected_now
                        .first()
                        .and_then(|item| label_of_key(&key_items, item))
                        .cloned()
                        .unwrap_or_default();
                    if !key_multiple && selected_label != state.read(cx).value() {
                        let had_selection = !selected_now.is_empty();
                        if let Some(held) = &key_selection_own {
                            held.update(cx, |v, cx| {
                                v.clear();
                                cx.notify();
                            });
                        }
                        if had_selection {
                            if let Some(cb) = &on_selection_change_all {
                                cb(&[], window, cx);
                            }
                        }
                    }
                    held.update(cx, |v, _| *v = None);
                    key_close(window, cx);
                    // Pinned React Aria 3.51.0's `Enter` shortcut prevents
                    // the default only while the menu is open
                    // (`shouldPreventDefault = state.isOpen`): a commit on a
                    // closed field — custom value or not — leaves Enter to
                    // bubble into an enclosing form's implicit submission.
                    if is_open {
                        cx.stop_propagation();
                    }
                    return;
                }
                if key == "enter" && (stale_cursor || held.read(cx).is_none()) {
                    let reset_value = if key_multiple {
                        String::new()
                    } else {
                        selected_now
                            .first()
                            .and_then(|item| label_of_key(&key_items, item))
                            .cloned()
                            .unwrap_or_default()
                            .to_string()
                    };
                    let input_changed = state.read(cx).value() != reset_value;
                    state.update(cx, |value, cx| {
                        value.set_value(reset_value.clone());
                        cx.notify();
                    });
                    if input_changed {
                        if let Some(cb) = &on_input_change {
                            cb(&reset_value, window, cx);
                        }
                    }
                    key_close(window, cx);
                    // Only an Enter the list acted on is kept from an
                    // enclosing form: an open list reverted, or a typed
                    // query discarded. A closed field with nothing to revert
                    // answers Enter with nothing here, and the keystroke may
                    // still bubble into the form's implicit submission.
                    if is_open || stale_cursor || input_changed {
                        cx.stop_propagation();
                    }
                    return;
                }
                let from = held
                    .read(cx)
                    .as_ref()
                    .and_then(|focused| cursor_position(&rows, focused));
                let nav_key = if key == "tab" && is_open && held.read(cx).is_some() {
                    "enter"
                } else {
                    key
                };
                // Pinned React Aria 3.51.0 binds PageUp/PageDown through the
                // listbox's `useSelectableCollection`, which a closed field
                // never runs: the suggestion list is not mounted, so the page
                // keys must not open it and must not move a retained cursor.
                // Open, those handlers require `manager.focusedKey != null` --
                // a mouse-opened, selection-less ComboBox has a null cursor
                // and must answer nothing until an arrow establishes one.
                // With a cursor the list is non-scrollable -- HeroUI v3.2.4
                // puts the overflow scrolling on the Popover while the ListBox
                // element is `overflow-clip` -- so a page takes the enabled
                // end: `stops` already omits disabled rows, whatever the
                // list's length or scroll state.
                let page_move = match nav_key {
                    "pagedown" if is_open && from.is_some() => stops.last().copied(),
                    "pageup" if is_open && from.is_some() => stops.first().copied(),
                    _ => None,
                }
                .filter(|next| Some(*next) != from);
                match page_move.map_or_else(
                    || crate::list_nav::resolve(&stops, from, nav_key, wrap),
                    crate::list_nav::Move::To,
                ) {
                    crate::list_nav::Move::To(next) => {
                        let next_cursor = Some(cursor_for(&rows, next, None));
                        held.update(cx, |v, cx| {
                            *v = next_cursor;
                            cx.notify();
                        });
                        if virtual_rows {
                            key_list_scroll.scroll_to_item(next, gpui::ScrollStrategy::Center);
                        } else {
                            key_panel_scroll.scroll_to_item(next);
                        }
                        // Walking the list opens it, which is what typing does.
                        if let Some(held) = &open_own_keys {
                            held.update(cx, |v, cx| {
                                *v = true;
                                cx.notify();
                            });
                        }
                        if !was_open {
                            show_all_items.update(cx, |v, _| *v = true);
                            if let Some(cb) = &on_open_change {
                                cb(&true, window, cx);
                            }
                        }
                    }
                    crate::list_nav::Move::Activate => {
                        // The activation reads the held cursor's key, not the
                        // rendered row: a cursor retained across a query reset
                        // (the multiple-mode pick above) can sit on an item
                        // the capped or filtered list no longer renders, and
                        // Enter must still toggle it.
                        let Some(item_key) =
                            held.read(cx).as_ref().map(|focused| focused.key.clone())
                        else {
                            return;
                        };
                        let item_label = label_of_key(&key_items, &item_key)
                            .cloned()
                            .unwrap_or_default();
                        // An Enter that picks a row is the list's, not an
                        // enclosing form's. A Tab mapped here keeps its
                        // native motion: only Enter is stopped.
                        if key == "enter" {
                            cx.stop_propagation();
                        }
                        if key_multiple {
                            let had_query = !state.read(cx).value().is_empty();
                            state.update(cx, |st, cx| {
                                st.set_value(String::new());
                                cx.notify();
                            });
                            held.update(cx, |v, _| {
                                if let Some(focused) = v {
                                    focused.hidden_query = Some(String::new());
                                }
                            });
                            let mut next = selected_now.clone();
                            toggle_key(&mut next, &item_key);
                            if let Some(held) = &key_selection_own {
                                let next = next.clone();
                                held.update(cx, |v, cx| {
                                    *v = next;
                                    cx.notify();
                                });
                            }
                            if let Some(cb) = &on_selection_change_all {
                                cb(&next, window, cx);
                            }
                            if had_query {
                                if let Some(cb) = &on_input_change {
                                    cb("", window, cx);
                                }
                            }
                            return;
                        }
                        // Taking a suggestion fills the field with the row's
                        // label and closes the list, the way a click does.
                        // Close first so the retained exit frame does not
                        // re-run the custom filter for the value we are about
                        // to copy into the input.
                        key_close(window, cx);
                        state.update(cx, |st, cx| {
                            st.set_value(item_label.to_string());
                            cx.notify();
                        });
                        // Uncontrolled: record the pick in the selection too,
                        // or `ComboBox.Value` would never see it.
                        if let Some(held) = &key_selection_own {
                            let next = vec![item_key.clone()];
                            held.update(cx, |v, cx| {
                                *v = next;
                                cx.notify();
                            });
                        }
                        held.update(cx, |v, _| *v = None);
                        if key == "tab" {
                            key_blur.consume(cx);
                        }
                        if selected_now.first() != Some(&item_key) {
                            if let Some(cb) = &on_selection_change_all {
                                cb(std::slice::from_ref(&item_key), window, cx);
                            }
                        }
                        if let Some(cb) = &on_selection_change {
                            cb(&item_key, window, cx);
                        }
                    }
                    crate::list_nav::Move::Ignore => {}
                }
            });
        }

        let show_list = overlay_active
            && !self.is_disabled
            && (!matches.is_empty() || self.allows_empty_collection);

        let escape_close = close_open.clone();
        let mut root = root;
        root =
            util::dismiss_on_escape_with_token(root, dismissal_token.clone(), move |window, cx| {
                escape_close(window, cx);
                util::DismissResult::Handled
            });
        if overlay_active && !show_list {
            let dismiss_close = close_open.clone();
            let dismiss_commit = commit_value.clone();
            let dismiss_blur = blur_scope.clone();
            root = util::dismiss_on_press_outside_with_token(
                root,
                dismissal_token.clone(),
                move |window, cx| {
                    dismiss_blur.consume(cx);
                    dismiss_commit(window, cx);
                    dismiss_close(window, cx);
                    util::DismissResult::Handled
                },
            );
        }
        // The popup anchors to the Input's field-row bounds — not to the
        // label-to-value wrapper root — the way RAC's `triggerRef` reads
        // `groupRef.current || inputRef.current`. The field joins ahead of
        // the panel below so the positioner reads settled trigger bounds.
        root = root.child(input_group);
        if show_list {
            let panel_selector = format!("combobox-panel-{entity_id}");
            let panel = div()
                .id(element_id::scoped(&base_id, "panel"))
                // `useComboBox` hands `listBoxProps` to the popover's RAC
                // `ListBox`, which is `useListBox`'s literal `role: 'listbox'`
                // with `'aria-orientation'` defaulting to vertical. The rows
                // are this panel's children, so the panel is that list.
                .a11y(a11y::Role::ListBox)
                .a11y_orientation(herogpui_core::Orientation::Vertical)
                .debug_selector(move || panel_selector)
                .w_full()
                .flex()
                .flex_col()
                .gap(px(2.))
                .p(px(4.))
                .overflow_y_scroll()
                // `overscroll-contain` upstream: a wheel over the popup must
                // not scroll the page behind it (Select/ColorPicker pattern).
                // A retained exit panel is visual-only and must not block the
                // next pointer target behind its old bounds.
                .when(overlay_phase == util::OverlayPhase::Open, |el| el.occlude())
                .track_scroll(&panel_scroll_now)
                // RAC caps the popover at the available viewport height
                // (`calculatePosition`'s `getMaxHeight`); the positioner
                // below re-lays the panel out with that cap, so the panel
                // carries a viewport-relative bound rather than a fixed one.
                .max_h_full()
                .rounded(container_radius)
                .bg(colors.overlay.background)
                // v3 gives a floating panel no border: `.popover` and friends are
                // `bg-overlay shadow-overlay` and a radius, and dark mode's
                // inset hairline is what separates the panel from the page.
                .when_some(layout.overlay_hairline, |el, hairline| {
                el.border(layout.border_width).border_color(hairline)
                })
                .text_color(colors.overlay.foreground)
                .when(
                    !layout.overlay_shadow.is_empty(),
                    |e: gpui::Stateful<gpui::Div>| e.shadow(layout.overlay_shadow.clone()),
                );

            // React Aria dismisses the list on a press outside it; Escape is
            // read in the field's own key handler above. A press that started
            // in the input-plus-panel subtree is not outside the ComboBox;
            // the input keeps the list open, while the chevron and rows own
            // their respective clicks.
            let dismiss_close = close_open.clone();
            let dismiss_commit = commit_value.clone();
            let dismiss_blur = blur_scope;
            let mut panel = util::dismiss_on_press_outside_with_token(
                panel,
                dismissal_token,
                move |window, cx| {
                    if inside_pressed.get() {
                        return util::DismissResult::Declined;
                    }
                    dismiss_blur.consume(cx);
                    dismiss_commit(window, cx);
                    dismiss_close(window, cx);
                    util::DismissResult::Handled
                },
            );

            if matches.is_empty() {
                // `allowsCustomValue` means an unmatched query is still valid,
                // so the empty state has to say something different.
                let message = if self.allows_custom_value {
                    "Press Enter to use this value"
                } else {
                    "No matching options"
                };
                panel = panel.child(
                    div()
                        .px(px(8.))
                        .py(px(6.))
                        .text_size(util::FIELD_TEXT)
                        .line_height(px(20.))
                        .text_color(colors.muted)
                        .child(message),
                );
            }

            // Everything a row reads, owned: `uniform_list`'s callback is
            // `'static` and runs again on every scroll, so it cannot borrow
            // `self` or the theme -- and one row builder for both paths is what
            // keeps a virtual list drawing the same row as a short one.
            let matches_len = matches.len();
            let rows = matches;
            let sections = self.sections.clone();
            let row_disabled_keys = self.disabled_keys.clone();
            let row_read_only = self.is_read_only;
            let row_selected_keys = self.selected_keys.clone();
            let indicator: Option<Rc<dyn Fn(bool) -> gpui::AnyElement>> =
                self.indicator.take().map(Rc::from);
            let on_change_all = self.on_selection_change_all.clone();
            let row_input_change = self.on_input_change.clone();
            let on_change_one = self.on_selection_change.clone();
            let row_state = self.state.clone();
            let row_cursor = cursor;
            let selection_own = selection_own;
            let row_open_own = open_own.clone();
            let row_open_state = open_state;
            let row_close_open = close_open.clone();
            let row_muted = colors.muted;
            let row_hover_bg = self.row_hover_bg.unwrap_or(colors.default.color);
            let row_focus = colors.focus;
            let row_accent = colors.accent.color;
            let row_disabled_opacity = layout.disabled_opacity;
            // The rows' shared parent id, owned by the `'static` row builder:
            // each row adds its item key as its own segment below it.
            let row_base = element_id::scoped(&base_id, "item");
            // `useOption` adds `aria-posinset`/`aria-setsize` only
            // `if (isVirtualized)`; `row_height` is what windows this list.
            let row_virtualized = self.row_height.is_some();
            let panel_interactive = overlay_phase == util::OverlayPhase::Open;
            let row_count = rows.len();
            let row_padding_x = self.row_padding_x.unwrap_or(px(8.));
            let row_font_family = self.row_font_family.clone();
            let row_padding_y = self.row_padding_y.unwrap_or(px(6.));
            let row_of = move |index: usize, fixed_h: Option<Pixels>, cx: &mut App| {
                let item = &rows[index];
                // A section header rides above the row it introduces, so the two
                // are one element -- a virtual row is one slot tall.
                let mut head: Vec<gpui::AnyElement> = Vec::new();
                let done = |head: Vec<gpui::AnyElement>, row: gpui::AnyElement| {
                    div()
                        .flex()
                        .flex_col()
                        .when_some(fixed_h, |el, h| el.h(h).w_full())
                        .children(head)
                        .child(row)
                        .into_any_element()
                };
                // `ListBox.Section`'s `Header`, above the item it introduces.
                if let Some((_, label)) = sections.iter().find(|(at, _)| at == item.key()) {
                    head.push(
                        div()
                            .px(px(8.))
                            .pt(px(6.))
                            .pb(px(4.))
                            .text_size(px(12.))
                            .line_height(px(16.))
                            .font_weight(gpui::FontWeight::MEDIUM)
                            .text_color(row_muted)
                            .child(label.to_string())
                            .into_any_element(),
                    );
                }
                // The row's element id comes from the item's key, so two items
                // that share a label never share an interactive row.
                let item_disabled = row_disabled_keys.contains(item.key());
                let hover_bg = row_hover_bg;
                let row_selector = format!("combobox-{entity_id}-item-{}", item.key());
                let row_selected = row_selected_keys.contains(item.key());
                let has_indicator_slot = indicator.is_some() || (multiple && row_selected);
                let mut row = div()
                        .id(element_id::scoped(&row_base, item.key().clone()))
                        // `useOption.mjs`: `role: 'option'` plus
                        // `'aria-selected'` whenever the list selects at all.
                        // The highlighted row is what `useComboBox` points its
                        // input's `aria-activedescendant` at; gpui states that
                        // relation on the descendant, so the row can say it
                        // even though this component does not own the input.
                        .a11y_named(
                            a11y::Role::ListBoxOption,
                            &a11y::Name::labelled(item.label().clone()),
                        )
                        .a11y_selected(row_selected_keys.contains(item.key()))
                        .when(cursor_at == Some(index), |row| row.a11y_active_descendant())
                        .when(row_virtualized, |row| {
                            row.a11y_set_position(index, row_count)
                        })
                        .debug_selector(move || row_selector)
                        // `.list-box-item`: `min-h-9 rounded-2xl px-2 py-1.5 gap-3`.
                        .min_h(util::FIELD_HEIGHT)
                        .px(row_padding_x)
                        .py(row_padding_y)
                        .gap(px(12.))
                        .rounded(util::soft_radius(cx))
                        .flex()
                        .items_center()
                        .justify_between()
                        .text_size(util::FIELD_TEXT)
                        .line_height(px(20.))
                        // HeroUI's list-box item reserves `pe-7` whenever its
                        // indicator slot is present; the indicator itself is
                        // absolute at the inline end. Keeping it out of flex
                        // flow prevents long labels from pushing the checkmark.
                        .relative()
                        .when(has_indicator_slot, |row| row.pr(px(28.)));
                if let Some(family) = row_font_family.clone() {
                    row = row.font_family(family);
                }

                if item_disabled {
                    row = row.opacity(row_disabled_opacity);
                } else if !row_read_only {
                    row = row
                        .cursor(util::interactive_cursor(cx))
                        .hover(move |s| s.bg(hover_bg));
                }

                // `status-focused` on the row the keyboard is on.
                if util::shows_focus_ring(cursor_at == Some(index), cx) {
                    row = row.border_2().border_color(row_focus);
                }

                // HeroUI's ListBox.Item does not add an ellipsis rule. Keep
                // normal text flow in both natural and virtual rows; the
                // caller owns the fixed row geometry when `row_height` is
                // supplied, just as the upstream Virtualizer owns its
                // `rowHeight` layout.
                let label = div().flex_1().min_w_0().whitespace_normal();
                row = row.child(label.child(item.label().to_string()));

                // `ListBox.ItemIndicator`: a caller-drawn tick replaces the
                // check glyph, and is asked for on every row so it can draw the
                // unselected state too.
                match &indicator {
                    Some(render) => {
                        row = row.child(
                            div()
                                .absolute()
                                .top_0()
                                .bottom_0()
                                .right(px(8.))
                                .w(px(16.))
                                .flex()
                                .items_center()
                                .justify_center()
                                .child(render(row_selected)),
                        );
                    }
                    None if multiple && row_selected => {
                        row = row.child(
                            div()
                                .absolute()
                                .top_0()
                                .bottom_0()
                                .right(px(8.))
                                .w(px(16.))
                                .flex()
                                .items_center()
                                .justify_center()
                                .child(
                                    gpui::svg()
                                        .size(px(13.))
                                        .path(icons::CHECK)
                                        .text_color(row_accent),
                                ),
                        );
                    }
                    None => {}
                }

                if item_disabled || row_read_only {
                    return done(head, row.into_any_element());
                }

                // Multiple mode toggles membership and leaves the panel open.
                if multiple {
                    if panel_interactive && (on_change_all.is_some() || selection_own.is_some()) {
                        let cb = on_change_all.clone();
                        let own = selection_own.clone();
                        let current = row_selected_keys.clone();
                        let value = item.key().clone();
                        let state = row_state.clone();
                        let cursor = row_cursor.clone();
                        let next_cursor = cursor_for(&rows, index, Some(String::new()));
                        let input_change = row_input_change.clone();
                        row = row.on_click(move |_, window, cx| {
                            let had_query = !state.read(cx).value().is_empty();
                            let focus_handle = state.read(cx).focus_handle.clone();
                            focus_handle.focus(window, cx);
                            state.update(cx, |st, cx| {
                                st.set_value(String::new());
                                cx.notify();
                            });
                            cursor.update(cx, |v, _| *v = Some(next_cursor.clone()));
                            let mut next = current.clone();
                            toggle_key(&mut next, &value);
                            // Uncontrolled: keep the new set, or picking an
                            // item would do nothing.
                            if let Some(held) = &own {
                                let set = next.clone();
                                held.update(cx, |v, cx| {
                                    *v = set;
                                    cx.notify();
                                });
                            }
                            if let Some(cb) = &cb {
                                cb(&next, window, cx);
                            }
                            if had_query {
                                if let Some(cb) = &input_change {
                                    cb("", window, cx);
                                }
                            }
                        });
                    }
                    return done(head, row.into_any_element());
                }

                // Taking a suggestion fills the field with the row's label and
                // closes the list, the way a click does; the selection rides
                // the row's key.
                let value = item.key().clone();
                let label = item.label().clone();
                let state = row_state.clone();
                let on_selection_change = on_change_one.clone();
                let on_selection_change_all = on_change_all.clone();
                let selection_changed = row_selected_keys.first() != Some(&value);
                let own = selection_own.clone();
                let open_own = row_open_own.clone();
                let close_open = row_close_open.clone();
                if panel_interactive {
                    row = row.on_click(move |_, window, cx| {
                        let is_open = open_own
                            .as_ref()
                            .map_or(row_open_state, |held| *held.read(cx));
                        if !is_open {
                            return;
                        }
                        // Close first so the retained exit frame does not
                        // re-run the custom filter for the selected label.
                        close_open(window, cx);
                        state.update(cx, |s, cx| {
                            s.set_value(label.to_string());
                            cx.notify();
                        });
                        // Uncontrolled: record the pick in the selection too, or
                        // `ComboBox.Value` would never see it.
                        if let Some(held) = &own {
                            let next = vec![value.clone()];
                            held.update(cx, |v, cx| {
                                *v = next;
                                cx.notify();
                            });
                        }
                        if selection_changed {
                            if let Some(cb) = &on_selection_change_all {
                                cb(std::slice::from_ref(&value), window, cx);
                            }
                        }
                        if let Some(cb) = &on_selection_change {
                            cb(&value, window, cx);
                        }
                    });
                }

                done(head, row.into_any_element())
            };

            match self.row_height {
                // Virtual: only the rows in view are built, which is what makes
                // a thousand options affordable. The list itself is the scroll
                // container: `Infer` sizes it from its rows — the full
                // natural height on the positioner's measure pass (so the
                // flip sees the real extent, like upstream's `overlaySize`),
                // capped to the available height on the capped pass — while
                // the ListBox stays `overflow-clip`, as in v3. A fixed inner
                // height plus an outer scroller would nest two scroll
                // containers and strand rows between them.
                Some(row_height) => {
                    panel = panel.child(
                        gpui::uniform_list(
                            element_id::scoped(&base_id, "rows"),
                            matches_len,
                            move |range, _window, cx| {
                                range
                                    .map(|i| row_of(i, Some(row_height), cx))
                                    .collect::<Vec<_>>()
                            },
                        )
                        .track_scroll(&list_scroll_now)
                        .with_sizing_behavior(gpui::ListSizingBehavior::Infer)
                        .w_full(),
                    );
                }
                None => {
                    for index in 0..matches_len {
                        panel = panel.child(row_of(index, None, cx));
                    }
                }
            }

            let (slide_x, slide_y) = crate::popover::placement_entry_offset(entry_placement);
            let zoom = crate::anim::ZoomBox::panel(px(4.), container_radius).padding_x(px(4.));
            let zoom = crate::anim::ZoomBox {
                slide_x: (slide_x != 0.0).then(|| px(slide_x)),
                slide_y: (slide_y != 0.0).then(|| px(slide_y)),
                ..zoom
            };
            let panel = if overlay_phase == util::OverlayPhase::Exiting {
                crate::anim::exiting(
                    panel,
                    element_id::scoped(&base_id, "anim-out"),
                    zoom,
                    crate::anim::Motion::LIST_OUT,
                    cx,
                )
            } else {
                crate::anim::entering_zoom(
                    panel,
                    element_id::scoped(&base_id, "anim"),
                    zoom,
                    crate::anim::Motion::LIST_IN,
                    cx,
                )
            };
            // RAC positions the popover against the field with an 8px gap,
            // flips it when the other side has more room, and caps it at the
            // available viewport height past a 12px inset.
            root = root.child(util::floating(
                crate::popover::scrollable_field_popover_with_resolved_placement(
                    anchor_bounds,
                    self.placement,
                    Some(resolved_placement),
                    panel,
                ),
            ));
        }

        // The popover hangs off the field it belongs to, so the field — not
        // the panel — is the root's first child; the deferred panel still
        // paints over the value row below it.
        root = util::apply_sx(root, &self.sx);
        root.when_some(value_content, |root, value| root.child(value))
            .track_focus(&blur_focus)
    }
}

// The pinned `.combo-box__trigger` hovers `text-field-foreground` and stays
// `bg-transparent`; a filled hover looks plausible on screen, so the check is
// mechanical.
#[cfg(test)]
mod hover_tokens {
    #[test]
    fn the_trigger_hover_recolours_the_text_and_fills_nothing() {
        // Scan the implementation only; this test's own text names the
        // forbidden accessor.
        let source = include_str!("combo_box.rs")
            .split("#[cfg(test)]")
            .next()
            .expect("the implementation section is always present");
        assert!(
            source.contains(".hover(move |s| s.text_color(trigger_hover_fg))"),
            "the trigger hover must recolour the text to `text-field-foreground` \
             (pinned `.combo-box__trigger:hover`)"
        );
        assert!(
            !source.contains("let hover_bg = colors.default.hover();"),
            "the trigger hover must not fill a background \
             (pinned `.combo-box__trigger` is `bg-transparent`)"
        );
    }
}