herogpui-components 0.9.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
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
//! Table — port of `@heroui/table` (v3).
//!
//! `variant` selects between the surface container (`primary`) and the flat,
//! transparent-row layout (`secondary`).
//!
//! Selection and sorting are controlled, as they are in v3: the table reports
//! what the user asked for and the caller owns the data. In particular the
//! table never reorders its own rows — it cannot, since a row is a list of
//! rendered cells, not a record.

use gpui::{
    prelude::*, px, AnyElement, App, ClickEvent, InteractiveElement, IntoElement, ParentElement,
    Pixels, RenderOnce, SharedString, Styled, Window,
};
use herogpui_core::{element_id, SelectionBehavior, SelectionMode};
use herogpui_theme::ActiveTheme;

use crate::{
    a11y::{self, A11y as _},
    checkbox::Checkbox,
    icons,
};

type OnRowClick = std::sync::Arc<dyn Fn(&usize, &ClickEvent, &mut Window, &mut App) + 'static>;
type OnSelectionChange = std::sync::Arc<dyn Fn(&[SharedString], &mut Window, &mut App) + 'static>;
type OnSortChange = std::sync::Arc<dyn Fn(&SortDescriptor, &mut Window, &mut App) + 'static>;
type OnLoadMore = std::sync::Arc<dyn Fn(&mut Window, &mut App) + 'static>;
type OnResize = std::sync::Arc<dyn Fn(&[(SharedString, Pixels)], &mut Window, &mut App) + 'static>;
type VirtualRowKey = std::sync::Arc<dyn Fn(usize) -> SharedString + 'static>;
type VirtualRow = std::sync::Arc<dyn Fn(usize) -> TableRow + 'static>;
type VirtualRowText = std::sync::Arc<dyn Fn(usize) -> SharedString + 'static>;
type VirtualTree = std::sync::Arc<dyn Fn(usize) -> VirtualTreeMetadata + 'static>;

const DEFAULT_COLUMN_MIN_WIDTH: f32 = 75.;

/// Visual variant of a table (`variant`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum TableVariant {
    /// A surface container behind the rows.
    #[default]
    Primary,
    /// Flat, with transparent rows and no container.
    Secondary,
}

impl TableVariant {
    pub const ALL: [TableVariant; 2] = [TableVariant::Primary, TableVariant::Secondary];

    pub fn label(self) -> &'static str {
        match self {
            TableVariant::Primary => "Primary",
            TableVariant::Secondary => "Secondary",
        }
    }
}

/// `sortDirection` on `Table.SortableColumnHeader`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SortDirection {
    Ascending,
    Descending,
}

impl SortDirection {
    /// The direction a second click on the same column asks for.
    pub fn flipped(self) -> Self {
        match self {
            SortDirection::Ascending => SortDirection::Descending,
            SortDirection::Descending => SortDirection::Ascending,
        }
    }
}

type Indicator = std::sync::Arc<dyn Fn(SortDirection) -> AnyElement + 'static>;

/// `sortDescriptor` — which column is sorted, and which way.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SortDescriptor {
    pub column: SharedString,
    pub direction: SortDirection,
}

impl SortDescriptor {
    pub fn new(column: impl Into<SharedString>, direction: SortDirection) -> Self {
        Self {
            column: column.into(),
            direction,
        }
    }

    /// The descriptor a click on `column` should produce.
    ///
    /// Clicking the sorted column flips it; clicking any other column starts
    /// ascending, which is what React Aria does.
    pub fn next(current: Option<&SortDescriptor>, column: impl Into<SharedString>) -> Self {
        let column = column.into();
        match current {
            Some(d) if d.column == column => Self {
                column,
                direction: d.direction.flipped(),
            },
            _ => Self {
                column,
                direction: SortDirection::Ascending,
            },
        }
    }
}

/// One column (`Table.Column`).
#[derive(Clone, Debug)]
pub struct TableColumn {
    label: SharedString,
    allows_sorting: bool,
    is_row_header: bool,
    /// `allowsResizing` — whether a handle on this column's trailing edge
    /// resizes it.
    allows_resizing: bool,
    /// `width` — a caller-owned controlled column width.
    width: Option<Pixels>,
    /// `defaultWidth` — the uncontrolled starting width. Without one the
    /// column shares the row evenly, which is what `flex-1` does.
    default_width: Option<Pixels>,
    /// `minWidth` — the column's floor.
    min_width: Option<Pixels>,
    /// `maxWidth` — the column's ceiling.
    max_width: Option<Pixels>,
}

impl TableColumn {
    pub fn new(label: impl Into<SharedString>) -> Self {
        Self {
            label: label.into(),
            allows_sorting: false,
            is_row_header: false,
            allows_resizing: false,
            width: None,
            default_width: None,
            min_width: None,
            max_width: None,
        }
    }

    /// `allowsResizing` — put a drag handle on this column's trailing edge.
    pub fn allows_resizing(mut self, v: bool) -> Self {
        self.allows_resizing = v;
        self
    }

    /// `defaultWidth` — the column's starting width, which a resize handle then
    /// moves.
    pub fn default_width(mut self, width: impl Into<Pixels>) -> Self {
        self.default_width = Some(width.into());
        self
    }

    /// `width` — the caller-owned controlled width of this column.
    pub fn width(mut self, width: impl Into<Pixels>) -> Self {
        self.width = Some(width.into());
        self
    }

    /// `minWidth` — the width this column will not go below.
    pub fn min_width(mut self, width: impl Into<Pixels>) -> Self {
        self.min_width = Some(width.into());
        self
    }

    /// `maxWidth` — the width this column will not exceed.
    pub fn max_width(mut self, width: impl Into<Pixels>) -> Self {
        self.max_width = Some(width.into());
        self
    }

    /// `allowsSorting` — makes the header a sort control.
    pub fn allows_sorting(mut self, v: bool) -> Self {
        self.allows_sorting = v;
        self
    }

    /// `isRowHeader` — this column names the row.
    ///
    /// With no accessibility layer to expose it to, the effect here is visual:
    /// the column's cells carry medium weight so the identifying value reads
    /// first.
    pub fn is_row_header(mut self, v: bool) -> Self {
        self.is_row_header = v;
        self
    }
}

impl From<SharedString> for TableColumn {
    fn from(label: SharedString) -> Self {
        TableColumn::new(label)
    }
}

impl From<&str> for TableColumn {
    fn from(label: &str) -> Self {
        TableColumn::new(label.to_owned())
    }
}

/// One row (`Table.Row`).
pub struct TableRow {
    key: Option<SharedString>,
    text_value: Option<SharedString>,
    cells: Vec<AnyElement>,
    /// The rows nested under this one. v3 calls them the row's `children`, and
    /// `expandedKeys` decides which parents show theirs.
    children: Vec<TableRow>,
}

/// Cheap tree structure for one preorder item in a virtual table.
///
/// The row factory still runs only for items the viewport builds. This metadata
/// is projected for the whole collection so expansion can derive the visible
/// indices without eagerly constructing any cells.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct VirtualTreeMetadata {
    pub depth: usize,
    pub parent_key: Option<SharedString>,
    pub has_children: bool,
}

impl TableRow {
    pub fn new(cells: Vec<AnyElement>) -> Self {
        Self {
            key: None,
            text_value: None,
            cells,
            children: Vec::new(),
        }
    }

    /// The rows nested under this one.
    pub fn children(mut self, rows: Vec<TableRow>) -> Self {
        self.children = rows;
        self
    }

    /// The selection key. Defaults to the row's index.
    pub fn key(mut self, key: impl Into<SharedString>) -> Self {
        self.key = Some(key.into());
        self
    }

    /// The plain-text value used by the table's typeahead.
    ///
    /// Cells are opaque `AnyElement`s, so rows without this value do not
    /// participate in typeahead even when a cell visibly draws text.
    pub fn text_value(mut self, value: impl Into<SharedString>) -> Self {
        self.text_value = Some(value.into());
        self
    }
}

type OnExpandedChange = std::sync::Arc<dyn Fn(&[SharedString], &mut Window, &mut App) + 'static>;

#[derive(Clone, Copy, PartialEq, Eq)]
enum RowActivation {
    Pointer,
    Enter,
    Space,
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum RowIntent {
    Action,
    Selection,
    None,
}

#[derive(Clone, Debug, Default)]
struct TableTypeahead {
    query: String,
    last: Option<web_time::Instant>,
}

#[derive(Clone, Debug, Default)]
struct TableSelectionRange {
    anchor: Option<SharedString>,
    current: Option<SharedString>,
    is_all: bool,
}

impl TableTypeahead {
    fn is_active(&self, now: web_time::Instant) -> bool {
        !self.query.is_empty()
            && self
                .last
                .is_some_and(|last| now.duration_since(last) <= crate::list_nav::TYPEAHEAD_TIMEOUT)
    }

    fn push(&mut self, key: &str, now: web_time::Instant) -> String {
        if self
            .last
            .is_none_or(|last| now.duration_since(last) > crate::list_nav::TYPEAHEAD_TIMEOUT)
        {
            self.query.clear();
        }
        self.last = Some(now);
        self.query.push_str(key);
        self.query.clone()
    }

    fn clear(&mut self) {
        self.query.clear();
        self.last = None;
    }
}

#[derive(Clone)]
struct TableTypeaheadNavigation {
    state: gpui::Entity<TableTypeahead>,
    labels: Vec<String>,
    virtual_indices: Option<Vec<usize>>,
    virtual_text: Option<VirtualRowText>,
    stops: Vec<usize>,
    keys: Vec<SharedString>,
    cursor: gpui::Entity<Option<SharedString>>,
    fixed_virtual: bool,
    fixed_scroll: gpui::UniformListScrollHandle,
    variable_scroll: Option<gpui::ListState>,
}

impl TableTypeaheadNavigation {
    fn push(
        &self,
        character: &str,
        now: web_time::Instant,
        clear_on_failure: bool,
        cx: &mut App,
    ) -> bool {
        let from = self
            .cursor
            .read(cx)
            .as_ref()
            .and_then(|key| self.keys.iter().position(|row| row == key))
            .filter(|index| self.stops.contains(index));
        let mut query = String::new();
        self.state.update(cx, |state, _| {
            query = state.push(character, now);
        });
        let projected_labels = self
            .virtual_text
            .as_ref()
            .zip(self.virtual_indices.as_ref())
            .map(|(text_value, indices)| {
                indices
                    .iter()
                    .map(|index| text_value(*index).to_string())
                    .collect::<Vec<_>>()
            });
        let searchable_labels = projected_labels.as_ref().unwrap_or(&self.labels);
        let Some(next) =
            crate::list_nav::typeahead(searchable_labels, &self.stops, from, &query, false)
        else {
            if clear_on_failure {
                self.state.update(cx, |state, _| state.clear());
            }
            return false;
        };
        self.cursor.update(cx, |value, cx| {
            *value = self.keys.get(next).cloned();
            cx.notify();
        });
        if self.fixed_virtual {
            self.fixed_scroll
                .scroll_to_item(next, gpui::ScrollStrategy::Center);
        } else if let Some(state) = &self.variable_scroll {
            state.scroll_to(gpui::ListOffset {
                item_ix: next,
                offset_in_item: px(0.),
            });
        }
        true
    }
}

#[derive(Clone, PartialEq, Eq)]
enum LoadMoreCollection {
    Rows(Vec<SharedString>),
    Virtual {
        count: usize,
        identity: SharedString,
    },
}

fn row_intent(
    activation: RowActivation,
    mode: SelectionMode,
    behavior: SelectionBehavior,
    selection_is_empty: bool,
    has_action: bool,
) -> RowIntent {
    // React Aria's replace behavior reserves a row's plain pointer activation
    // for selection whenever the row is selectable; its action becomes a
    // secondary (double-click/Enter) action. Toggle keeps the existing
    // single-click action while the collection is empty.
    let primary_action = has_action
        && (mode == SelectionMode::None
            || (behavior == SelectionBehavior::Toggle && selection_is_empty));
    match activation {
        RowActivation::Pointer if primary_action => RowIntent::Action,
        RowActivation::Pointer if mode != SelectionMode::None => RowIntent::Selection,
        RowActivation::Enter if primary_action => RowIntent::Action,
        RowActivation::Enter if !has_action && mode != SelectionMode::None => RowIntent::Selection,
        RowActivation::Space if mode != SelectionMode::None => RowIntent::Selection,
        _ => RowIntent::None,
    }
}

fn select_all_flags(selectable: &[SharedString], selected: &[SharedString]) -> (bool, bool) {
    let selected_count = selectable
        .iter()
        .filter(|key| selected.contains(key))
        .count();
    let all_selected = !selectable.is_empty() && selected_count == selectable.len();
    let indeterminate = !selected.is_empty() && !all_selected;
    (all_selected, indeterminate)
}

fn same_selection(left: &[SharedString], right: &[SharedString]) -> bool {
    left.len() == right.len()
        && left.iter().collect::<std::collections::HashSet<_>>()
            == right.iter().collect::<std::collections::HashSet<_>>()
}

fn extend_selection_range(
    current: &[SharedString],
    collection: &[SharedString],
    selectable: &[SharedString],
    range: &TableSelectionRange,
    target: &SharedString,
) -> Vec<SharedString> {
    if range.is_all {
        return vec![target.clone()];
    }
    let anchor = range.anchor.as_ref().unwrap_or(target);
    let previous = range.current.as_ref().unwrap_or(target);
    let mut anchor_at = None;
    let mut previous_at = None;
    let mut target_at = None;
    for (index, key) in collection.iter().enumerate() {
        anchor_at = anchor_at.or_else(|| (key == anchor).then_some(index));
        previous_at = previous_at.or_else(|| (key == previous).then_some(index));
        target_at = target_at.or_else(|| (key == target).then_some(index));
    }
    let between = |from: Option<usize>, to: Option<usize>| {
        from.zip(to)
            .map(|(from, to)| if from <= to { from..=to } else { to..=from })
    };
    let mut next = current.to_vec();
    if let Some(previous_range) = between(anchor_at, previous_at) {
        let removed: std::collections::HashSet<&SharedString> =
            previous_range.map(|index| &collection[index]).collect();
        next.retain(|key| !removed.contains(key));
    }
    if let Some(target_range) = between(anchor_at, target_at) {
        let selectable: std::collections::HashSet<&SharedString> = selectable.iter().collect();
        let mut selected: std::collections::HashSet<SharedString> = next.iter().cloned().collect();
        for index in target_range {
            let key = &collection[index];
            if selectable.contains(key) && selected.insert(key.clone()) {
                next.push(key.clone());
            }
        }
    }
    next
}

/// Pinned React Aria 3.51.0 `useSelectableCollection` registers Home and End
/// only for the chords each platform's handler admits: none, Shift, Alt, and
/// Alt+Shift on macOS -- no Meta or Control handler exists -- and none,
/// Shift, Control, and Control+Shift on Windows and Linux. The upstream
/// matcher reads exactly the browser's canonical modifier flags -- Alt,
/// Control, Meta, Shift -- so GPUI's `function` flag is ignored here: a
/// browser exposes no Fn state for it to read, so vetoing on the flag would
/// claim a pinned guard that does not exist, and the framework delivers an
/// Fn-bearing press with every matched modifier flag still false. A chord
/// outside the registration is entirely inert: no focus move, no selection,
/// no preventDefault. `macos` is simulated explicitly so every platform's
/// unit tests can prove both maps.
fn home_end_registered(modifiers: gpui::Modifiers, macos: bool) -> bool {
    if macos {
        !modifiers.control && !modifiers.platform
    } else {
        !modifiers.alt && !modifiers.platform
    }
}

/// Pinned `useSelectableCollection` (`isCtrlKeyPressed`): a Shift move
/// extends the range on the collection's navigation keys, while Home and
/// End extend only from Control+Shift on Windows and Linux. macOS registers
/// no Home/End extension at all -- its Shift and Alt+Shift chords move the
/// focus alone -- so the platform is an explicit bool rather than a `cfg!`.
fn shift_home_end_extends(key_name: &str, control: bool, macos: bool) -> bool {
    !matches!(key_name, "home" | "end") || (!macos && control)
}

/// A column with a `defaultWidth` takes it; the rest split what is left.
///
/// `flex_basis(0)` is the part that matters: a bare `flex_1` sizes a cell by its
/// content, so the tree column's indent shifted every column after it, and a
/// fraction of the *whole* row cannot account for the fixed columns.
fn flex_cell(el: gpui::Div) -> gpui::Div {
    el.flex_basis(px(0.)).flex_1()
}

/// The pinned table stylesheet replaces the tree column's start padding with
/// one `1rem` step for every 1-based row level. `flatten_tree` stores the root
/// at depth zero, so a root keeps the regular 16px cell padding and a child at
/// depth `d` resolves to `16px * (d + 1)`. Keeping this in one helper avoids
/// the intrinsic-width probe and the painted cell drifting apart at deeper
/// levels.
fn tree_column_padding(depth: usize) -> Option<Pixels> {
    (depth > 0).then(|| px(16. * (depth as f32 + 1.)))
}

/// The horizontal extent of the direct children that a cell lays out. GPUI
/// reports absolute child bounds, so taking their union keeps a label and a
/// sort indicator together while ignoring an empty cell. One-pixel separator
/// overlays are deliberately excluded; they are decorative and must not turn
/// into a column's intrinsic width.
#[allow(clippy::float_cmp)] // f32::MAX is the unset sentinel, checked exactly
fn intrinsic_children_width(bounds: &[gpui::Bounds<Pixels>]) -> f32 {
    let mut left = f32::MAX;
    let mut right = f32::MIN;
    for bound in bounds.iter().filter(|bound| bound.size.width > px(2.)) {
        left = left.min(f32::from(bound.origin.x));
        right = right.max(f32::from(bound.origin.x + bound.size.width));
    }
    if left == f32::MAX {
        0.0
    } else {
        (right - left).max(0.0)
    }
}

/// Paints the split inset ring HeroUI uses for a focused row cell.
///
/// A single rounded overlay on the row makes the focus geometry look plausible
/// until a cell has its own clipping/background: the outer corners and the
/// shared vertical edges then bleed into neighboring cells. Keeping the four
/// strips on each cell reproduces the stylesheet's first/middle/last cases
/// without changing cell layout or intercepting the row's click handler.
fn table_cell_focus_ring(cx: &App, first: bool, last: bool) -> gpui::Div {
    let color = cx.colors().focus;
    let radius = crate::util::key_radius(cx);
    let mut top = gpui::div()
        .absolute()
        .top_0()
        .left_0()
        .right_0()
        .h(px(2.))
        .bg(color);
    let mut bottom = gpui::div()
        .absolute()
        .bottom_0()
        .left_0()
        .right_0()
        .h(px(2.))
        .bg(color);
    if first {
        top = top.rounded_tl(radius);
        bottom = bottom.rounded_bl(radius);
    }
    if last {
        top = top.rounded_tr(radius);
        bottom = bottom.rounded_br(radius);
    }
    let mut ring = gpui::div().absolute().inset_0().child(top).child(bottom);
    if first {
        ring = ring.child(
            gpui::div()
                .absolute()
                .top_0()
                .bottom_0()
                .left_0()
                .w(px(2.))
                .rounded_tl(radius)
                .rounded_bl(radius)
                .bg(color),
        );
    }
    if last {
        ring = ring.child(
            gpui::div()
                .absolute()
                .top_0()
                .bottom_0()
                .right_0()
                .w(px(2.))
                .rounded_tr(radius)
                .rounded_br(radius)
                .bg(color),
        );
    }
    ring
}

/// HeroUI Table.
#[derive(IntoElement)]
pub struct Table {
    /// Distinguishes one table's keyed state from another's: the resized column
    /// widths, the drag in progress, the focus handle and the row cursor all
    /// hang off it. v3 needs no such prop -- React keys by position in the tree
    /// -- so the default is a name shared by every table, which only goes wrong
    /// when a page shows two of them.
    id: SharedString,
    /// `indicator` — v3's render prop for the sort chevron, handed the
    /// `sortDirection` the column is sorted in.
    indicator: Option<Indicator>,
    columns: Vec<TableColumn>,
    rows: Vec<TableRow>,
    /// `treeColumn` — which column carries the expand chevron.
    tree_column: usize,
    /// `expandedKeys` — the parent rows showing their children.
    expanded_keys: Vec<SharedString>,
    on_expanded_change: Option<OnExpandedChange>,
    /// `TableLayout`'s `rowHeight`. Together with [`Table::virtual_rows`] it
    /// virtualizes the body: a fixed row height is what lets the scroll geometry
    /// be computed rather than laid out.
    row_height: Option<Pixels>,
    /// `TableLayout`'s `estimatedRowHeight` — virtualizes rows whose heights
    /// differ, where `rowHeight` needs them all the same.
    estimated_row_height: Option<Pixels>,
    /// `TableLayout`'s `loaderHeight` — the fixed height of the load-more row.
    loader_height: Option<Pixels>,
    /// `scrollOffset` on `Table.LoadMore`, in viewport heights.
    load_more_offset: f32,
    /// How tall the virtual body is. v3 sets it with a `className`.
    max_h: Option<Pixels>,
    /// `TableLayout`'s `gap` and `padding`, both 0 in v3: rows meet, separated
    /// by their border rather than by space.
    gap: Option<Pixels>,
    padding: Option<Pixels>,
    /// The row factory a virtual table needs. Cells are `AnyElement`, which
    /// cannot be built up front and then handed out again on the next scroll,
    /// so a virtual table asks for its rows one at a time.
    virtual_rows: Option<(usize, SharedString, VirtualRowKey, VirtualRow)>,
    virtual_text_value: Option<VirtualRowText>,
    virtual_tree_metadata: Option<VirtualTree>,
    variant: TableVariant,
    selection_mode: SelectionMode,
    selection_behavior: SelectionBehavior,
    selected_keys: Vec<SharedString>,
    default_selected_keys: Vec<SharedString>,
    disabled_keys: Vec<SharedString>,
    disallow_empty_selection: bool,
    is_selection_controlled: bool,
    sort_descriptor: Option<SortDescriptor>,
    show_indicator: bool,
    is_pending: bool,
    empty_state: Option<AnyElement>,
    footer: Option<AnyElement>,
    on_row_click: Option<OnRowClick>,
    on_selection_change: Option<OnSelectionChange>,
    on_sort_change: Option<OnSortChange>,
    on_load_more: Option<OnLoadMore>,
    on_resize_start: Option<OnResize>,
    on_resize: Option<OnResize>,
    on_resize_end: Option<OnResize>,
    /// The fill a hovered *unselected* row takes, in place of the variant's
    /// hover wash. A selected row keeps its selection fill.
    row_hover_bg: Option<gpui::Hsla>,
    /// The wrapper shell's corner radius, in place of the owning
    /// `container_radius` helper. `Primary` paints its own tray radius over
    /// this one, exactly as it covers the helper's value.
    radius: Option<Pixels>,
    /// The `sx` slot, refined over the root style at the end of render.
    sx: Option<Box<gpui::StyleRefinement>>,
}

impl Table {
    pub fn new(columns: Vec<SharedString>) -> Self {
        Self {
            id: SharedString::from("table"),
            indicator: None,
            columns: columns.into_iter().map(TableColumn::new).collect(),
            rows: Vec::new(),
            tree_column: 0,
            expanded_keys: Vec::new(),
            on_expanded_change: None,
            row_height: None,
            estimated_row_height: None,
            loader_height: None,
            load_more_offset: 1.0,
            max_h: None,
            gap: None,
            padding: None,
            virtual_rows: None,
            virtual_text_value: None,
            virtual_tree_metadata: None,
            variant: TableVariant::Primary,
            selection_mode: SelectionMode::None,
            selection_behavior: SelectionBehavior::Toggle,
            selected_keys: Vec::new(),
            default_selected_keys: Vec::new(),
            disabled_keys: Vec::new(),
            disallow_empty_selection: false,
            is_selection_controlled: false,
            sort_descriptor: None,
            show_indicator: true,
            is_pending: false,
            empty_state: None,
            footer: None,
            on_row_click: None,
            on_selection_change: None,
            on_sort_change: None,
            on_load_more: None,
            on_resize_start: None,
            on_resize: None,
            on_resize_end: None,
            row_hover_bg: None,
            radius: None,
            sx: None,
        }
    }

    /// The id this table's own state is keyed by.
    ///
    /// Two tables on one page share their resized widths, their row cursor and
    /// their focus without it, because `use_keyed_state` keys by the id it is
    /// given and nothing else.
    pub fn id(mut self, id: impl Into<SharedString>) -> Self {
        self.id = id.into();
        self
    }

    /// `indicator` — replaces the sort chevron.
    ///
    /// The closure receives `sortDirection`, the value v3 passes into the same
    /// render prop, so a caller can draw an arrow, a caret or a label without
    /// re-deriving which way the column is sorted.
    pub fn indicator(mut self, render: impl Fn(SortDirection) -> AnyElement + 'static) -> Self {
        self.indicator = Some(std::sync::Arc::new(render));
        self
    }

    /// Replaces the columns with fully configured ones.
    pub fn columns(mut self, columns: Vec<TableColumn>) -> Self {
        self.columns = columns;
        self
    }

    /// Adds one configured column.
    pub fn column(mut self, column: impl Into<TableColumn>) -> Self {
        self.columns.push(column.into());
        self
    }

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

    /// `TableLayout`'s `rowHeight` — and, with [`Table::virtual_rows`], what
    /// virtualizes the body.
    ///
    /// v3 wraps the table in `<Virtualizer layout={TableLayout}
    /// layoutOptions={{rowHeight: 40}}>`; the wrapper has no separate identity
    /// here, so the option that defines the layout carries it. gpui's
    /// `uniform_list` builds only the rows the viewport shows, and it can do
    /// that because every row is this tall.
    pub fn row_height(mut self, height: impl Into<Pixels>) -> Self {
        self.row_height = Some(height.into());
        self
    }

    /// How tall the scrolling body is. v3's example sets it with `h-[400px]` on
    /// the table itself.
    pub fn max_h(mut self, height: impl Into<Pixels>) -> Self {
        self.max_h = Some(height.into());
        self
    }

    /// `TableLayout`'s `gap` -- space between rows, which v3 leaves at 0.
    pub fn gap(mut self, gap: impl Into<Pixels>) -> Self {
        self.gap = Some(gap.into());
        self
    }

    /// `TableLayout`'s `padding` -- space around the rows, 0 in v3.
    pub fn padding(mut self, padding: impl Into<Pixels>) -> Self {
        self.padding = Some(padding.into());
        self
    }

    /// The rows of a virtualized table, built on demand.
    ///
    /// v3 writes `<Table items={users}>{(user) => <Table.Row>…}</Table>` and the
    /// Virtualizer calls that function for the rows in view. Cells here are
    /// `AnyElement`, which is built once and consumed once, so a virtual table
    /// cannot be handed its rows up front -- it has to be able to ask again
    /// every time the viewport moves.
    /// `key` projects the collection key without building the row. Keyboard
    /// navigation and select-all need the full collection, but calling `row`
    /// for every item would defeat virtualization.
    /// `identity` stays stable for one collection and changes when the caller
    /// replaces it, so a visible load-more sentinel can re-arm without building
    /// every row just to compare their keys.
    /// `TableLayout`'s `estimatedRowHeight` — virtualize rows that are not all
    /// one height.
    ///
    /// `rowHeight` maps to `uniform_list`, which measures one row and multiplies;
    /// this maps to gpui's `list`, which measures every row it builds. The
    /// estimate is what it renders beyond the viewport while it learns the real
    /// heights.
    pub fn estimated_row_height(mut self, height: impl Into<Pixels>) -> Self {
        self.estimated_row_height = Some(height.into());
        self
    }

    /// `TableLayout`'s `loaderHeight` — the height of the load-more row.
    pub fn loader_height(mut self, height: impl Into<Pixels>) -> Self {
        self.loader_height = Some(height.into());
        self
    }

    /// Virtual rows for a collection of `count` items.
    ///
    /// `identity` names the collection: it must stay stable for one collection
    /// and change when the caller replaces it. The key and row closures are
    /// treated as stable for that identity — their output is cached between
    /// frames and replayed whenever count, identity, tree mode and the
    /// expanded set are unchanged. If `key` (or [`Table::virtual_tree_metadata`]'s
    /// `metadata`) would return different output for the same indices without
    /// the collection being replaced, the caller must change `identity` so the
    /// cached projection is rebuilt.
    pub fn virtual_rows(
        mut self,
        count: usize,
        identity: impl Into<SharedString>,
        key: impl Fn(usize) -> SharedString + 'static,
        row: impl Fn(usize) -> TableRow + 'static,
    ) -> Self {
        self.virtual_rows = Some((
            count,
            identity.into(),
            std::sync::Arc::new(key),
            std::sync::Arc::new(row),
        ));
        self
    }

    /// Projects each virtual row's `textValue` without building its cells.
    /// Virtual rows do not participate in typeahead unless this is supplied.
    pub fn virtual_text_value(
        mut self,
        text_value: impl Fn(usize) -> SharedString + 'static,
    ) -> Self {
        self.virtual_text_value = Some(std::sync::Arc::new(text_value));
        self
    }

    /// Supplies preorder tree structure for [`Table::virtual_rows`].
    ///
    /// `count` remains the size of the underlying collection. The projection
    /// identifies each item's parent, depth and expandability; controlled
    /// `expanded_keys` then decides which source indices are visible. The
    /// metadata closure is treated as stable for the [`Table::virtual_rows`]
    /// collection identity: if its output changes for the same indices, the
    /// caller must change that identity so the cached projection is rebuilt.
    pub fn virtual_tree_metadata(
        mut self,
        metadata: impl Fn(usize) -> VirtualTreeMetadata + 'static,
    ) -> Self {
        self.virtual_tree_metadata = Some(std::sync::Arc::new(metadata));
        self
    }

    /// Adds one row of cells (`Table.Row` cells).
    /// `treeColumn` — the column whose cells carry the expand chevron.
    pub fn tree_column(mut self, index: usize) -> Self {
        self.tree_column = index;
        self
    }

    /// `expandedKeys` — the parent rows showing their children.
    pub fn expanded_keys(mut self, keys: impl IntoIterator<Item = SharedString>) -> Self {
        self.expanded_keys = keys.into_iter().collect();
        self
    }

    /// Reports the expanded set after a chevron is pressed.
    pub fn on_expanded_change(
        mut self,
        f: impl Fn(&[SharedString], &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_expanded_change = Some(std::sync::Arc::new(f));
        self
    }

    /// Adds a row, with any nested rows it carries.
    pub fn tree_row(mut self, row: TableRow) -> Self {
        self.rows.push(row);
        self
    }

    pub fn row(mut self, cells: Vec<AnyElement>) -> Self {
        self.rows.push(TableRow::new(cells));
        self
    }

    /// Adds one row under an explicit selection key.
    pub fn keyed_row(mut self, key: impl Into<SharedString>, cells: Vec<AnyElement>) -> Self {
        self.rows.push(TableRow::new(cells).key(key));
        self
    }

    /// `selectionMode` — adds the selection column when not `None`.
    pub fn selection_mode(mut self, mode: SelectionMode) -> Self {
        self.selection_mode = mode;
        self
    }

    /// `selectionBehavior` — how a multi-selection changes when a row is
    /// activated. `Toggle` preserves the current set; `Replace` makes a plain
    /// activation the sole selected row. Single selection keeps its own
    /// React Stately toggle/replace rule for both values.
    pub fn selection_behavior(mut self, behavior: SelectionBehavior) -> Self {
        self.selection_behavior = behavior;
        self
    }

    /// The fill a hovered *unselected* interactive row takes, in place of the
    /// variant's hover wash (`bg-surface/40` primary, `bg-default/50`
    /// secondary). A selected row keeps its `bg-surface/10` fill; a disabled
    /// or inert row never hovers.
    pub fn row_hover_bg(mut self, color: impl Into<gpui::Hsla>) -> Self {
        self.row_hover_bg = Some(color.into());
        self
    }

    /// The wrapper shell's corner radius, in place of the owning
    /// `container_radius` helper. `Primary` paints its own tray radius over
    /// this one, exactly as it covers the helper's value, so the override
    /// shows wherever the helper's value does. Not a v3 prop; the removed v2
    /// `radius` prop is prohibited and this is a per-component repository
    /// extension.
    pub fn radius(mut self, radius: impl Into<Pixels>) -> Self {
        self.radius = Some(radius.into());
        self
    }

    /// `selectedKeys` — the controlled selection.
    pub fn selected_keys(
        mut self,
        keys: impl IntoIterator<Item = impl Into<SharedString>>,
    ) -> Self {
        self.selected_keys = keys.into_iter().map(Into::into).collect();
        self.is_selection_controlled = true;
        self
    }

    /// `defaultSelectedKeys` — the initial uncontrolled selection. Later
    /// changes are owned by the table until `selected_keys` is supplied.
    pub fn default_selected_keys(
        mut self,
        keys: impl IntoIterator<Item = impl Into<SharedString>>,
    ) -> Self {
        self.default_selected_keys = keys.into_iter().map(Into::into).collect();
        self
    }

    /// `disallowEmptySelection` — keep the last selected row when a toggle or
    /// Escape would otherwise clear the collection.
    pub fn disallow_empty_selection(mut self, disallow: bool) -> Self {
        self.disallow_empty_selection = disallow;
        self
    }

    /// React Aria's inherited `disabledKeys` — rows excluded from selection,
    /// actions and the roving keyboard stops.
    pub fn disabled_keys(
        mut self,
        keys: impl IntoIterator<Item = impl Into<SharedString>>,
    ) -> Self {
        self.disabled_keys = keys.into_iter().map(Into::into).collect();
        self
    }

    /// `onSelectionChange` — the whole selection after a row is toggled.
    pub fn on_selection_change(
        mut self,
        f: impl Fn(&[SharedString], &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_selection_change = Some(std::sync::Arc::new(f));
        self
    }

    /// `sortDescriptor` — the current sort, shown in the header.
    pub fn sort_descriptor(mut self, descriptor: SortDescriptor) -> Self {
        self.sort_descriptor = Some(descriptor);
        self
    }

    /// `onSortChange` — a sortable header was clicked.
    ///
    /// The table does not reorder its rows; a row is already-rendered cells, so
    /// the caller sorts its data and rebuilds.
    pub fn on_sort_change(
        mut self,
        f: impl Fn(&SortDescriptor, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_sort_change = Some(std::sync::Arc::new(f));
        self
    }

    /// `showIndicator` — whether a sorted column draws its direction chevron.
    pub fn show_indicator(mut self, v: bool) -> Self {
        self.show_indicator = v;
        self
    }

    /// `isLoading` on `Table.LoadMore` — shows the loading sentinel row.
    pub fn is_pending(mut self, v: bool) -> Self {
        self.is_pending = v;
        self
    }

    /// `scrollOffset` on `Table.LoadMore` — how many viewport heights before
    /// the sentinel enters view the load should start. React Aria defaults to
    /// one; v3's async example sets zero for an exact intersection.
    pub fn scroll_offset(mut self, offset: f32) -> Self {
        self.load_more_offset = offset;
        self
    }

    /// `onLoadMore` — the sentinel row entered the scroll viewport.
    pub fn on_load_more(mut self, f: impl Fn(&mut Window, &mut App) + 'static) -> Self {
        self.on_load_more = Some(std::sync::Arc::new(f));
        self
    }

    /// `onResizeStart` on `Table.ResizableContainer` — reports the current
    /// pixel widths when pointer or keyboard resizing begins.
    pub fn on_resize_start(
        mut self,
        f: impl Fn(&[(SharedString, Pixels)], &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_resize_start = Some(std::sync::Arc::new(f));
        self
    }

    /// `onResize` on `Table.ResizableContainer` — reports each proposed width
    /// map. Feed the values back through [`TableColumn::width`] for controlled
    /// resizing.
    pub fn on_resize(
        mut self,
        f: impl Fn(&[(SharedString, Pixels)], &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_resize = Some(std::sync::Arc::new(f));
        self
    }

    /// `onResizeEnd` on `Table.ResizableContainer` — reports the final pixel
    /// widths after pointer or keyboard resizing ends.
    pub fn on_resize_end(
        mut self,
        f: impl Fn(&[(SharedString, Pixels)], &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_resize_end = Some(std::sync::Arc::new(f));
        self
    }

    /// `Table.Footer` — a row under the body, which is where v3 puts a table's
    /// pagination.
    pub fn footer(mut self, content: impl IntoElement) -> Self {
        self.footer = Some(content.into_any_element());
        self
    }

    /// `renderEmptyState` — shown in place of rows when there are none.
    pub fn empty_state(mut self, content: impl IntoElement) -> Self {
        self.empty_state = Some(content.into_any_element());
        self
    }

    pub fn on_row_click(
        mut self,
        f: impl Fn(&usize, &ClickEvent, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_row_click = Some(std::sync::Arc::new(f));
        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 table's root element after every value the variant and
    /// the active theme chose, so they win.
    pub fn sx(mut self, style: impl FnOnce(gpui::Div) -> gpui::Div) -> Self {
        self.sx = Some(crate::util::capture_sx(style));
        self
    }

    /// Every row's selection key, in order.
    fn row_keys(&self) -> Vec<SharedString> {
        fn collect(rows: &[TableRow], path: &str, out: &mut Vec<SharedString>) {
            for (index, row) in rows.iter().enumerate() {
                let key = match &row.key {
                    Some(key) => key.clone(),
                    None if path.is_empty() => SharedString::from(index.to_string()),
                    None => SharedString::from(format!("{path}-{index}")),
                };
                out.push(key.clone());
                collect(&row.children, key.as_ref(), out);
            }
        }

        let mut keys = Vec::new();
        collect(&self.rows, "", &mut keys);
        keys
    }
}

/// A virtual table's projected keys and visible rows, cached between frames.
///
/// The projection depends only on what [`Table::virtual_rows`] already names —
/// the collection's identity and count — plus the expanded set and whether
/// tree metadata is projected. Any frame where none of those changed reuses
/// the cached projection instead of calling the key and tree closures again;
/// the closures are free to return different values only when the caller
/// replaces the collection, which is what `identity` is for.
#[derive(Default)]
struct VirtualProjection {
    count: usize,
    identity: SharedString,
    expanded: std::sync::Arc<std::collections::HashSet<SharedString>>,
    tree: bool,
    full_keys: std::sync::Arc<Vec<SharedString>>,
    /// Behind an `Arc` because the list builders hold it across the frame.
    visible: std::sync::Arc<Vec<(usize, SharedString, VirtualTreeMetadata)>>,
    selectable_collection_keys: Option<std::sync::Arc<Vec<SharedString>>>,
    selectable_disabled_keys: Option<std::sync::Arc<Vec<SharedString>>>,
}

fn filtered_selectable_keys(
    full_keys: &[SharedString],
    disabled_keys: &[SharedString],
) -> std::sync::Arc<Vec<SharedString>> {
    std::sync::Arc::new(
        full_keys
            .iter()
            .filter(|key| !disabled_keys.contains(key))
            .cloned()
            .collect(),
    )
}

fn resolved_column_widths(
    columns: &[TableColumn],
    resized: &[Option<Pixels>],
    measured: &[Option<Pixels>],
    proposal: Option<(usize, Pixels)>,
) -> Vec<(SharedString, Pixels)> {
    columns
        .iter()
        .enumerate()
        .filter_map(|(index, column)| {
            let width = proposal
                .filter(|(proposed_index, _)| *proposed_index == index)
                .map(|(_, width)| width)
                .or(column.width)
                .or_else(|| resized.get(index).copied().flatten())
                .or(column.default_width)
                .or_else(|| measured.get(index).copied().flatten())?;
            let width = if column.allows_resizing {
                let min = column.min_width.map_or(DEFAULT_COLUMN_MIN_WIDTH, f32::from);
                let max = column.max_width.map_or(f32::MAX, f32::from);
                px(f32::from(width).floor().min(max).max(min))
            } else {
                width
            };
            Some((column.label.clone(), width))
        })
        .collect()
}

fn final_column_widths(
    columns: &[TableColumn],
    resized: &[Option<Pixels>],
    measured: &[Option<Pixels>],
    column: usize,
) -> Vec<(SharedString, Pixels)> {
    let proposal = resized
        .get(column)
        .copied()
        .flatten()
        .map(|width| (column, width));
    resolved_column_widths(columns, resized, measured, proposal)
}

fn clear_controlled_resize_proposal(
    columns: &[TableColumn],
    resized: &gpui::Entity<Vec<Option<Pixels>>>,
    column: usize,
    cx: &mut App,
) {
    if columns
        .get(column)
        .is_some_and(|column| column.width.is_some())
    {
        resized.update(cx, |values, cx| {
            if values
                .get_mut(column)
                .is_some_and(|width| width.take().is_some())
            {
                cx.notify();
            }
        });
    }
}

impl RenderOnce for Table {
    fn render(mut self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        // The caller's id, as the root every part of this table hangs off.
        let base_id: gpui::ElementId = self.id.clone().into();
        // Column widths a resize handle has moved, and the drag in progress.
        // `use_keyed_state` takes `cx` mutably, so both precede the tokens.
        let resized =
            window.use_keyed_state(element_id::scoped(&base_id, "resized"), cx, |_, _| {
                Vec::<Option<Pixels>>::new()
            });
        let resized_now = resized.read(cx).clone();
        let measured_widths = window.use_keyed_state(
            element_id::scoped(&base_id, "measured-widths"),
            cx,
            |_, _| Vec::<Option<Pixels>>::new(),
        );
        let measured_widths_now = measured_widths.read(cx).clone();
        let dragging =
            window.use_keyed_state(element_id::scoped(&base_id, "resizing"), cx, |_, _| {
                None::<(usize, f32, f32)>
            });
        let drag_now = *dragging.read(cx);
        let keyboard_resizing = window.use_keyed_state(
            element_id::scoped(&base_id, "keyboard-resizing"),
            cx,
            |_, _| None::<usize>,
        );
        let keyboard_resize_now = *keyboard_resizing.read(cx);
        let load_more_state = window.use_keyed_state(
            element_id::scoped(&base_id, "load-more-state"),
            cx,
            |_, _| (false, None::<LoadMoreCollection>),
        );
        // The body is one tab stop with a cursor inside it, the way a list is.
        let table_focus =
            crate::util::tab_stop_handle(element_id::scoped(&base_id, "focus"), window, cx);
        let row_cursor =
            window.use_keyed_state(element_id::scoped(&base_id, "cursor"), cx, |_, _| {
                None::<SharedString>
            });
        let selection_range = window.use_keyed_state(
            element_id::scoped(&base_id, "selection-range"),
            cx,
            |_, _| TableSelectionRange::default(),
        );
        let typeahead =
            window.use_keyed_state(element_id::scoped(&base_id, "typeahead"), cx, |_, _| {
                TableTypeahead::default()
            });
        let (selected_keys, selection_own) = crate::util::controlled(
            window,
            cx,
            element_id::scoped(&base_id, "selected"),
            self.is_selection_controlled
                .then(|| self.selected_keys.clone()),
            self.default_selected_keys.clone(),
        );
        self.selected_keys = selected_keys;
        let needs_selectable_keys = self.selection_mode == SelectionMode::Multiple;
        let virtual_projection: Option<std::sync::Arc<VirtualProjection>> = self
            .virtual_rows
            .as_ref()
            .map(|(count, identity, key_for_row, _)| {
                let cache = window.use_keyed_state(
                    element_id::scoped(&base_id, "virtual-projection"),
                    cx,
                    |_, _| None::<std::sync::Arc<VirtualProjection>>,
                );
                let cached = cache.read(cx).clone();
                let tree = self.virtual_tree_metadata.is_some();
                match cached {
                    Some(cached)
                        if cached.count == *count
                            && cached.identity == *identity
                            && cached.tree == tree
                            && (!tree
                                || (cached.expanded.len() == self.expanded_keys.len()
                                    && self
                                        .expanded_keys
                                        .iter()
                                        .all(|key| cached.expanded.contains(key)))) =>
                    {
                        if !needs_selectable_keys
                            || cached
                                .selectable_disabled_keys
                                .as_ref()
                                .is_some_and(|disabled| {
                                    disabled.as_slice() == self.disabled_keys.as_slice()
                                })
                        {
                            cached
                        } else {
                            let projection = std::sync::Arc::new(VirtualProjection {
                                count: cached.count,
                                identity: cached.identity.clone(),
                                expanded: std::sync::Arc::clone(&cached.expanded),
                                tree: cached.tree,
                                full_keys: std::sync::Arc::clone(&cached.full_keys),
                                visible: std::sync::Arc::clone(&cached.visible),
                                selectable_collection_keys: Some(filtered_selectable_keys(
                                    cached.full_keys.as_slice(),
                                    &self.disabled_keys,
                                )),
                                selectable_disabled_keys: Some(std::sync::Arc::new(
                                    self.disabled_keys.clone(),
                                )),
                            });
                            cache.update(cx, |slot, _| {
                                *slot = Some(std::sync::Arc::clone(&projection));
                            });
                            projection
                        }
                    }
                    _ => {
                        let mut full_keys = Vec::with_capacity(*count);
                        let mut visible = Vec::with_capacity(*count);
                        if let Some(project) = &self.virtual_tree_metadata {
                            let mut visible_by_key =
                                std::collections::HashMap::with_capacity(*count);
                            for source_index in 0..*count {
                                let key = key_for_row(source_index);
                                let metadata = project(source_index);
                                let is_visible =
                                    metadata.parent_key.as_ref().is_none_or(|parent| {
                                        visible_by_key.get(parent).copied().unwrap_or(false)
                                            && self.expanded_keys.contains(parent)
                                    });
                                visible_by_key.insert(key.clone(), is_visible);
                                full_keys.push(key.clone());
                                if is_visible {
                                    visible.push((source_index, key, metadata));
                                }
                            }
                        } else {
                            for source_index in 0..*count {
                                let key = key_for_row(source_index);
                                full_keys.push(key.clone());
                                visible.push((source_index, key, VirtualTreeMetadata::default()));
                            }
                        }
                        let full_keys = std::sync::Arc::new(full_keys);
                        let selectable_collection_keys = needs_selectable_keys.then(|| {
                            filtered_selectable_keys(full_keys.as_slice(), &self.disabled_keys)
                        });
                        let selectable_disabled_keys = needs_selectable_keys
                            .then(|| std::sync::Arc::new(self.disabled_keys.clone()));
                        let projection = std::sync::Arc::new(VirtualProjection {
                            count: *count,
                            identity: identity.clone(),
                            expanded: if tree {
                                std::sync::Arc::new(self.expanded_keys.iter().cloned().collect())
                            } else {
                                std::sync::Arc::default()
                            },
                            tree,
                            full_keys,
                            visible: std::sync::Arc::new(visible),
                            selectable_collection_keys,
                            selectable_disabled_keys,
                        });
                        cache.update(cx, |slot, _| {
                            *slot = Some(std::sync::Arc::clone(&projection));
                        });
                        projection
                    }
                }
            });
        let virtual_visible_count = virtual_projection
            .as_ref()
            .map_or(0, |projection| projection.visible.len());
        let virtual_visible_keys = virtual_projection.as_ref().map(|projection| {
            projection
                .visible
                .iter()
                .map(|(_, key, _)| key.clone())
                .collect::<Vec<_>>()
        });
        let virtual_row_heights = match (
            &self.virtual_rows,
            self.estimated_row_height,
            &virtual_visible_keys,
        ) {
            (Some((_, identity, _, _)), Some(_), Some(keys)) if self.row_height.is_none() => {
                let count = keys.len();
                let state = window.use_keyed_state(
                    element_id::scoped(
                        &element_id::scoped(&base_id, "row-heights"),
                        identity.clone(),
                    ),
                    cx,
                    |_, _| (Vec::<SharedString>::new(), Vec::<Option<Pixels>>::new()),
                );
                if state.read(cx).0.as_slice() != keys.as_slice() {
                    let stored_keys = keys.clone();
                    state.update(cx, |stored, _| {
                        *stored = (stored_keys, vec![None; count]);
                    });
                }
                Some(state)
            }
            _ => None,
        };
        let virtual_scroll = window.use_keyed_state(
            element_id::scoped(&base_id, "virtual-scroll"),
            cx,
            |_, _| gpui::UniformListScrollHandle::new(),
        );
        let virtual_scroll_now = virtual_scroll.read(cx).clone();
        let load_more_virtual_scroll = (self.row_height.is_some() && self.virtual_rows.is_some())
            .then(|| virtual_scroll_now.clone());
        let virtual_list_state = match (
            self.row_height,
            self.estimated_row_height,
            &self.virtual_rows,
        ) {
            (None, Some(estimate), Some((_, identity, _, _))) => {
                let count = virtual_visible_count;
                let overdraw = self.max_h.unwrap_or(px(400.)).max(estimate * 3.);
                let state = window
                    .use_keyed_state(
                        element_id::scoped(
                            &element_id::scoped(&base_id, "list-state"),
                            identity.clone(),
                        ),
                        cx,
                        move |_, _| gpui::ListState::new(count, gpui::ListAlignment::Top, overdraw),
                    )
                    .read(cx)
                    .clone();
                if state.item_count() != count {
                    state.reset(count);
                }
                Some(state)
            }
            _ => None,
        };
        let load_more_variable_scroll = virtual_list_state
            .clone()
            .zip(self.estimated_row_height)
            .map(|(state, estimate)| (state, virtual_visible_count, estimate));
        // A sortable header had a click listener and no focus, so sorting was
        // mouse-only. v3's grid roves one tab stop across its cells; this port
        // gives each sortable header its own stop, which is the part that
        // matters. Created before the theme: `use_keyed_state` takes `cx`
        // mutably and `cx.colors()` holds a borrow.
        let sortable = self.on_sort_change.is_some();
        // Every column header is focusable, not just the sortable ones: v3's
        // PageUp leaves the body for the first column header whatever it is.
        // Only a sortable header is a *tab stop*, though -- it has to be, so
        // Enter and Space can sort it -- which keeps every table's Tab order
        // exactly as it was while giving the keyboard somewhere to land.
        let header_focus: Vec<gpui::FocusHandle> = self
            .columns
            .iter()
            .enumerate()
            .map(|(i, column)| {
                let id = element_id::scoped(&element_id::indexed(&base_id, "sort", i), "focus");
                if column.allows_sorting && sortable {
                    crate::util::tab_stop_handle(id, window, cx)
                } else {
                    window
                        .use_keyed_state(id, cx, |_, cx| cx.focus_handle())
                        .read(cx)
                        .clone()
                }
            })
            .collect();
        let ring_visible = crate::util::focus_visible(cx);
        let header_focused: Vec<bool> = header_focus
            .iter()
            .map(|h| h.is_focused(window) && ring_visible)
            .collect();
        let resize_focus: Vec<Option<gpui::FocusHandle>> = self
            .columns
            .iter()
            .enumerate()
            .map(|(i, column)| {
                column.allows_resizing.then(|| {
                    crate::util::tab_stop_handle(
                        element_id::scoped(&element_id::indexed(&base_id, "resize", i), "focus"),
                        window,
                        cx,
                    )
                })
            })
            .collect();
        let resize_focused: Vec<bool> = resize_focus
            .iter()
            .map(|h| h.as_ref().is_some_and(|h| h.is_focused(window)) && ring_visible)
            .collect();
        if keyboard_resize_now.is_some_and(|column_index| {
            resize_focus
                .get(column_index)
                .and_then(Option::as_ref)
                .is_none()
        }) {
            keyboard_resizing.update(cx, |active, cx| {
                *active = None;
                cx.notify();
            });
        }

        let resizable = self.columns.iter().any(|c| c.allows_resizing);
        let resize_limits: Vec<(f32, f32)> = self
            .columns
            .iter()
            .map(|column| {
                (
                    column.min_width.map_or(DEFAULT_COLUMN_MIN_WIDTH, f32::from),
                    column.max_width.map_or(f32::MAX, f32::from),
                )
            })
            .collect();
        let effective_widths: Vec<Option<Pixels>> = self
            .columns
            .iter()
            .enumerate()
            .map(|(column_index, column)| {
                let width = column.width.or_else(|| {
                    resized_now
                        .get(column_index)
                        .copied()
                        .flatten()
                        .or(column.default_width)
                });
                if column.allows_resizing {
                    let (min, max) = resize_limits[column_index];
                    width.map(|width| px(f32::from(width).floor().min(max).max(min)))
                } else {
                    width
                }
            })
            .collect();
        // The one column-track computation. Upstream draws a `border-separate`
        // table, so the header's `<th>` cells resolve tracks every row shares;
        // this port stands in for that with one `(width, min, max)` triple per
        // column — the explicit width when one wins, otherwise `flex-basis:0;
        // flex-grow:1` floored by the widest cell measured across the header
        // and every body row. The header cells below and every `RowCtx` row
        // must read this same triple, and the sortable and resizable header
        // wrappers must carry it too: a wrapper that only grows equally would
        // resolve its own track and stagger the header off the body. A table
        // narrower than the tracks then overflows `scroll-x` as one grid
        // instead of squeezing each row separately.
        let layout_width_bounds: Vec<(Option<Pixels>, Option<Pixels>)> = self
            .columns
            .iter()
            .enumerate()
            .map(|(column_index, column)| {
                let measured = measured_widths_now.get(column_index).copied().flatten();
                if column.allows_resizing {
                    if effective_widths[column_index].is_some() {
                        (None, None)
                    } else {
                        let min = measured.map_or(resize_limits[column_index].0, |width| {
                            resize_limits[column_index].0.max(f32::from(width))
                        });
                        (Some(px(min)), column.max_width)
                    }
                } else {
                    let min = match (column.min_width, measured) {
                        (Some(configured), Some(content)) => {
                            Some(px(f32::from(configured).max(f32::from(content))))
                        }
                        (Some(configured), None) => Some(configured),
                        (None, Some(content)) => Some(content),
                        (None, None) => None,
                    };
                    (min, column.max_width)
                }
            })
            .collect();
        let resize_columns = std::sync::Arc::new(self.columns.clone());
        let resize_measurements = std::sync::Arc::new(measured_widths_now.clone());
        let colors = cx.colors().clone();
        // Copies of the tokens the tail needs: the row builder borrows `cx`
        // mutably, which ends the borrow `cx.colors()` holds.
        let muted = colors.muted;
        let secondary = self.variant == TableVariant::Secondary;
        let selectable = self.selection_mode != SelectionMode::None;
        // Only multiple selection consumes the full enabled-key set. The
        // virtual projection shares it between frames; None and Single do not
        // materialize a collection that no consumer reads.
        let non_virtual_keys = virtual_projection.is_none().then(|| self.row_keys());
        let selectable_collection_keys: Option<std::sync::Arc<Vec<SharedString>>> =
            needs_selectable_keys.then(|| match virtual_projection.as_ref() {
                Some(projection) => projection
                    .selectable_collection_keys
                    .as_ref()
                    .expect("multiple virtual Tables cache selectable keys")
                    .clone(),
                None => filtered_selectable_keys(
                    non_virtual_keys
                        .as_ref()
                        .expect("multiple non-virtual Tables have row keys")
                        .as_slice(),
                    &self.disabled_keys,
                ),
            });
        let load_more_collection = match &self.virtual_rows {
            Some((count, identity, _, _)) => LoadMoreCollection::Virtual {
                count: *count,
                identity: identity.clone(),
            },
            None => LoadMoreCollection::Rows(non_virtual_keys.unwrap_or_default()),
        };

        let mut wrapper = gpui::div()
            .w_full()
            .flex()
            .flex_col()
            .track_focus(&table_focus)
            .overflow_hidden()
            .rounded(
                self.radius
                    .unwrap_or_else(|| crate::util::container_radius(cx)),
            )
            .text_color(colors.foreground);
        // A column, so the scroll container below is a vertical flex item: it
        // shrinks with a bounded parent (its `overflow_hidden` zeroes the
        // minimum), handing the virtual body its real viewport. A block would
        // size it to content and only clip the overflow.

        // `.table-root--primary` is a `bg-surface-secondary px-1 pb-1` tray with
        // `border-radius: min(32px, --radius * 2.5)`, and the rows sit in a
        // `bg-surface` block inside it; `secondary` is flat. This used to draw
        // one white card with a border, which is the block without its tray.
        if !secondary {
            let radius = cx.layout().radius_lg() * 2.5;
            wrapper = wrapper
                .bg(colors.surface_secondary)
                .rounded(radius.min(px(32.)))
                .px(px(4.))
                .pb(px(4.));
        }

        // The wrapper is a column, so this content column may shrink
        // vertically with a bounded parent -- that is what lets a virtual
        // body take the laid-out viewport rather than the `max_h` cap.
        // Horizontally it must never shrink: the scroll container at the
        // bottom of the render is a column with `items_start`, whose cross
        // axis leaves this child at its max-content width, so a table wider
        // than its box still slides on it. (A row-flex scroller would need
        // `flex_shrink_0` here for the same guarantee, which would also
        // forbid the vertical shrink.)
        //
        // The content column, whose width is what the scroller at the bottom
        // of the render measures against. A `w_full` child commits to the
        // scroller's width, which is exactly the scroller's own -- the scroll
        // maxima are then zero and a wide table clips at the tray edge instead
        // of sliding. `min_w_full` keeps the column at the viewport when no
        // column pins a width. `min_h_0` lets the column shrink vertically
        // with a bounded parent: without it the content-based minimum keeps
        // the max-content height and a virtual body never sees its real
        // viewport.
        // `aria-colcount` counts the collection's columns, and the selection
        // column is one of them upstream. `aria-rowcount` is only knowable
        // when the port virtualizes, which is exactly when upstream sets it.
        let grid_column_count = self.columns.len() + usize::from(selectable);
        // `useTable`'s `state.treeColumn != null` means the collection was
        // built as a tree, not merely that a column index was named:
        // `Table::tree_column` only picks which column carries the chevron,
        // and it defaults to `0` on every flat table. A tree here is a
        // collection with nested rows, virtual or not.
        let is_tree = self.virtual_tree_metadata.is_some()
            || self.rows.iter().any(|row| !row.children.is_empty());
        let virtual_row_total = virtual_projection.as_ref().map(|_| virtual_visible_count);
        let mut table = gpui::div()
            .flex()
            .flex_col()
            .min_w_full()
            .min_h_0()
            .text_size(px(14.))
            .line_height(px(20.))
            .when_some(self.gap, |el, g| el.gap(g))
            .when_some(self.padding, |el, p| el.p(p))
            // The accessibility contract goes on the *end* of this chain:
            // `.shots/design_audit.py` reads `.table__content`'s text size
            // through a 240-character window opening at `let mut table =
            // gpui::div(`, and it reports the rule unreadable when anything
            // is spliced in ahead of `.text_size(..)`.
            //
            // `react-aria/dist/private/table/useTable.mjs` starts from
            // `.../grid/useGrid.mjs`'s `role: 'grid'` and overrides it to
            // `'treegrid'` only `if (state.treeColumn != null)`. RAC's
            // `Table.mjs` adds no role of its own.
            //
            // `aria-rowcount` / `aria-colcount` are set only
            // `if (isVirtualized)` — the DOM then holds a window onto a
            // longer collection and the counts cannot be read off the tree —
            // and `useTable` then makes the row count
            // `state.collection.size + state.collection.headerRows.length`,
            // which is why the one header row is added to it. The
            // `aria-multiselectable` that `useGrid` sets beside them has no
            // gpui builder (see `crate::a11y`).
            .id(element_id::scoped(&base_id, "grid"))
            .a11y(if is_tree {
                a11y::Role::TreeGrid
            } else {
                a11y::Role::Grid
            })
            .when_some(virtual_row_total, |el, rows| {
                el.a11y_grid_size(rows + 1, grid_column_count)
            });

        // ---- header ------------------------------------------------------
        // `.table__header`, whose cells are `.table__column`s and whose
        // sortable ones wrap in `.table__sortable-column-header`.
        let mut header = gpui::div()
            .id(element_id::scoped(&base_id, "header"))
            // `useTableHeaderRow.mjs` is a bare `role: 'row'`. Upstream wraps
            // it in a `<TableHeader>` whose `useTableRowGroup` gives it
            // `role: 'rowgroup'`; this port draws the single header row
            // directly into the table, so there is no second element for that
            // node to sit on. The body below *is* a container of rows, and it
            // carries the rowgroup.
            .a11y(a11y::Role::Row)
            .flex()
            .border_b_1()
            .border_color(colors.separator.alpha(0.5))
            .when(!secondary, |h| h.bg(colors.surface_secondary));

        if selectable {
            // The select-all box only makes sense for a multiple selection; a
            // single-selection table keeps the column for alignment.
            let mut cell = gpui::div()
                .id(element_id::scoped(&base_id, "select-all-cell"))
                // The selection column is a real column of the collection
                // upstream, so its header is a `role: 'columnheader'` like any
                // other (`useTableColumnHeader.mjs`), holding the select-all
                // checkbox `useTableSelectAllCheckbox` names.
                .a11y(a11y::Role::ColumnHeader)
                .a11y_column_index(0)
                .flex()
                .items_center()
                .justify_center()
                .relative()
                .w(px(44.))
                .py(px(10.));
            if secondary {
                let radius = cx.layout().radius_2xl().min(px(32.));
                cell = cell
                    .bg(colors.surface_secondary)
                    .rounded_tl(radius)
                    .rounded_bl(radius);
            }
            if self.selection_mode == SelectionMode::Multiple {
                // The `Mod+A` keydown handler reads the same set, so it gets a
                // clone rather than the variable itself.
                let all = selectable_collection_keys
                    .as_ref()
                    .expect("multiple Tables have selectable keys")
                    .clone();
                let (all_selected, indeterminate) =
                    select_all_flags(all.as_slice(), &self.selected_keys);
                let mut box_el = Checkbox::new(element_id::scoped(&base_id, "select-all"))
                    .is_selected(all_selected)
                    .is_indeterminate(indeterminate);
                let cb = self.on_selection_change.clone();
                if cb.is_some() || selection_own.is_some() {
                    let selection_own = selection_own.clone();
                    let selection_range = selection_range.clone();
                    let disallow_empty_selection = self.disallow_empty_selection;
                    box_el = box_el.on_change(move |_next, window, cx| {
                        if all_selected && disallow_empty_selection {
                            return;
                        }
                        // Anything short of everything selects everything.
                        let next: Vec<SharedString> = if all_selected {
                            Vec::new()
                        } else {
                            all.as_slice().to_vec()
                        };
                        if let Some(held) = &selection_own {
                            held.update(cx, |value, cx| {
                                *value = next.clone();
                                cx.notify();
                            });
                        }
                        if let Some(cb) = &cb {
                            cb(&next, window, cx);
                        }
                        selection_range.update(cx, |range, _| {
                            *range = if all_selected {
                                TableSelectionRange::default()
                            } else {
                                TableSelectionRange {
                                    is_all: true,
                                    ..TableSelectionRange::default()
                                }
                            };
                        });
                    });
                }
                cell = cell.child(box_el);
            }
            header = header.child(cell);
        }

        for (column_index, column) in self.columns.iter().enumerate() {
            let sorted = self
                .sort_descriptor
                .as_ref()
                .filter(|d| d.column == column.label);
            // A resized column keeps the width the drag left it at.
            let effective = effective_widths[column_index];
            let (layout_min, layout_max) = layout_width_bounds[column_index];
            let first_header = column_index == 0 && !selectable;
            let last_header = column_index + 1 == self.columns.len();
            let mut cell = gpui::div()
                .when(effective.is_none(), flex_cell)
                .when_some(effective, |c, w| c.w(w))
                .when_some(layout_min, |c, w| c.min_w(w))
                .when_some(layout_max, |c, w| c.max_w(w))
                .flex()
                .items_center()
                .gap(px(4.))
                // `.table__column` is `px-4 py-2.5 text-xs`.
                .px(px(16.))
                .py(px(10.))
                .text_size(px(12.))
                .line_height(px(16.))
                .font_weight(gpui::FontWeight::MEDIUM)
                .when(column.allows_sorting, |c| c.w_full().justify_between())
                .text_color(if sorted.is_some() {
                    colors.foreground
                } else {
                    colors.muted
                })
                .relative();
            if !column.allows_resizing && !cfg!(target_arch = "wasm32") {
                let measurements = measured_widths.clone();
                cell = cell.on_children_prepainted(move |bounds, _, cx| {
                    let content = intrinsic_children_width(&bounds);
                    if content <= 0. {
                        return;
                    }
                    let next = px(content + 32.);
                    measurements.update(cx, |values, cx| {
                        if values.len() <= column_index {
                            values.resize(column_index + 1, None);
                        }
                        if values[column_index].is_none_or(|current| next > current) {
                            values[column_index] = Some(next);
                            cx.notify();
                        }
                    });
                });
            }
            cell = cell.child(column.label.clone());
            let header_selector = format!("table-header-track-{column_index}");
            cell = cell.debug_selector(move || header_selector);

            if secondary {
                let radius = cx.layout().radius_2xl().min(px(32.));
                cell = cell.bg(colors.surface_secondary);
                if first_header {
                    cell = cell.rounded_tl(radius).rounded_bl(radius);
                }
                if last_header {
                    cell = cell.rounded_tr(radius).rounded_br(radius);
                }
            }

            if let Some(descriptor) = sorted {
                if self.show_indicator {
                    // `indicator` is v3's render prop on
                    // `Table.SortableColumnHeader`: it receives the direction
                    // the column is sorted in and replaces the chevron.
                    cell = cell.child(match &self.indicator {
                        Some(render) => render(descriptor.direction),
                        None => {
                            let indicator_id = element_id::indexed(
                                &element_id::scoped(&base_id, "sort-indicator"),
                                "column",
                                column_index,
                            );
                            crate::anim::rotating_indicator_with_duration(
                                &indicator_id,
                                descriptor.direction == SortDirection::Descending,
                                gpui::svg()
                                    .size(px(12.))
                                    .path(icons::CHEVRON_UP)
                                    // svg() never inherits text colour.
                                    .text_color(colors.foreground),
                                100,
                                window,
                                cx,
                            )
                        }
                    });
                }
            }

            if !last_header && !column.allows_resizing {
                cell = cell.child(
                    gpui::div()
                        .absolute()
                        .right_0()
                        .top(px(10.))
                        .h(px(16.))
                        .w(px(1.))
                        .rounded(crate::util::hairline_radius(cx))
                        .bg(colors.separator),
                );
            }

            // A sortable header wraps the cell in a click target, which is a
            // different element type, so both branches unify to AnyElement.
            let cell = match (column.allows_sorting, self.on_sort_change.clone()) {
                (true, Some(cb)) => {
                    let next =
                        SortDescriptor::next(self.sort_descriptor.as_ref(), column.label.clone());
                    // `.table__column[data-allows-sorting]:hover` recolours the
                    // header text to `--foreground`; it paints no background.
                    // A group name is a plain string, not an `ElementId`, so it
                    // cannot carry structure -- but it still has to start from
                    // this table's own id, or two tables share the group.
                    let sort_group: SharedString =
                        format!("{}-sort-hover-{}", self.id, column.label).into();
                    let header_cell = gpui::div()
                        .id(element_id::scoped(
                            &element_id::scoped(&base_id, "sort"),
                            column.label.clone(),
                        ))
                        // `useTableColumnHeader.mjs` is `role: 'columnheader'`
                        // with `'aria-colindex'` from the grid cell props
                        // underneath it and `'aria-sort'` on a sortable
                        // column. The sort direction has no gpui builder —
                        // upstream itself drops it on Android Talkback and
                        // duplicates it into `aria-describedby` instead — so
                        // it is a recorded omission in `crate::a11y`.
                        .a11y_named(
                            a11y::Role::ColumnHeader,
                            &a11y::Name::labelled(column.label.clone()),
                        )
                        .a11y_column_index(column_index + usize::from(selectable))
                        .group(sort_group.clone())
                        // The wrapper owns the column's track, so it reads the
                        // same triple the body cell read: a fixed width when
                        // one wins, otherwise the shared flex floor. Leaving
                        // the wrapper an unconditional equal-growth track
                        // ignored the width entirely and resolved the header's
                        // tracks separately from the body's.
                        .when(effective.is_none(), |wrapper| {
                            wrapper.flex_basis(px(0.)).flex_grow(1.).flex_shrink(1.)
                        })
                        .when_some(effective, |wrapper, w| wrapper.w(w))
                        .when_some(layout_min, |wrapper, w| wrapper.min_w(w))
                        .when_some(layout_max, |wrapper, w| wrapper.max_w(w))
                        .flex()
                        .cursor(crate::util::interactive_cursor(cx))
                        // The focus is what makes Enter and Space sort: gpui
                        // fires a *focused* element's click listeners for them.
                        .track_focus(&header_focus[column_index])
                        .on_click(move |_, window, cx| cb(&next.clone(), window, cx))
                        .child(cell.group_hover(sort_group, |s| s.text_color(colors.foreground)));
                    // `.table__column` rings *inside* itself: the next column
                    // is flush against this one, and a ring drawn outside bled
                    // through the transparent cell and filled it.
                    header_cell
                        .relative()
                        .when(header_focused[column_index], |c| {
                            c.child(crate::util::inset_focus_ring(cx))
                        })
                        .into_any_element()
                }
                // Not sortable, so nothing to press -- but still focusable, so
                // PageUp has a header to land on, and it rings when it does.
                _ => cell
                    .id(element_id::indexed(&base_id, "header", column_index))
                    // The same `role: 'columnheader'`; a column that does not
                    // sort simply has no `aria-sort` upstream either
                    // (`ariaSort` stays `undefined` unless `allowsSorting`).
                    .a11y_named(
                        a11y::Role::ColumnHeader,
                        &a11y::Name::labelled(column.label.clone()),
                    )
                    .a11y_column_index(column_index + usize::from(selectable))
                    .track_focus(&header_focus[column_index])
                    .relative()
                    .when(header_focused[column_index], |c| {
                        c.child(crate::util::inset_focus_ring(cx))
                    })
                    .into_any_element(),
            };

            // `allowsResizing` puts a handle on the column's trailing edge. The
            // wrapper is what keeps the handle inside the column's box.
            // `.table__resizable-container` is the box that keeps the handle
            // inside the column, which is what this wrapper is.
            let cell = if column.allows_resizing {
                let held = dragging.clone();
                let start_width = effective
                    .or_else(|| measured_widths_now.get(column_index).copied().flatten())
                    .unwrap_or(px(160.));
                let keyboard = keyboard_resizing.clone();
                let keyboard_out = keyboard.clone();
                let keyboard_for_pointer = keyboard.clone();
                let widths = resized.clone();
                let widths_for_pointer = widths.clone();
                let widths_for_outside = widths.clone();
                let (min_width, max_width) = resize_limits[column_index];
                let controlled = column.width.is_some();
                let focus_for_mouse = resize_focus[column_index]
                    .as_ref()
                    .expect("resizable columns have a focus handle")
                    .clone();
                // As with the sort hover group: a string, but this table's own.
                let resizer_group: SharedString =
                    format!("{}-resizer-{column_index}", self.id).into();
                let accent_color = colors.accent.color;
                let focus_color = colors.focus;
                let is_resizing = drag_now.is_some_and(|(index, _, _)| index == column_index)
                    || keyboard_resize_now == Some(column_index);
                let measured = measured_widths.clone();
                let columns_for_pointer = resize_columns.clone();
                let columns_for_outside = resize_columns.clone();
                let columns_for_keys = resize_columns.clone();
                let measurements_for_pointer = resize_measurements.clone();
                let measurements_for_outside = resize_measurements.clone();
                let measurements_for_keys = resize_measurements.clone();
                let resize_start_for_pointer = self.on_resize_start.clone();
                let resize_start_for_keys = self.on_resize_start.clone();
                let resize_for_keys = self.on_resize.clone();
                let resize_end_for_pointer = self.on_resize_end.clone();
                let resize_end_for_outside = self.on_resize_end.clone();
                let resize_end_for_keys = self.on_resize_end.clone();
                gpui::div()
                    .relative()
                    .when(effective.is_none(), flex_cell)
                    .when_some(effective, |c, w| c.w(w))
                    // The wrapper owns the column's track, so it carries the
                    // shared bounds instead of leaning on the inner cell's
                    // automatic minimum (see `layout_width_bounds`).
                    .when_some(layout_min, |wrapper, w| wrapper.min_w(w))
                    .when_some(layout_max, |wrapper, w| wrapper.max_w(w))
                    .when(effective.is_none(), |wrapper| {
                        wrapper.child(
                            gpui::canvas(
                                move |bounds: gpui::Bounds<Pixels>, _, cx| {
                                    let width = px(f32::from(bounds.size.width).floor());
                                    measured.update(cx, |values, cx| {
                                        if values.len() <= column_index {
                                            values.resize(column_index + 1, None);
                                        }
                                        if values[column_index] != Some(width) {
                                            values[column_index] = Some(width);
                                            cx.notify();
                                        }
                                    });
                                    bounds
                                },
                                |_, _, _, _| {},
                            )
                            .absolute()
                            .inset_0(),
                        )
                    })
                    .child(cell)
                    .child(
                        gpui::div()
                            .id(element_id::indexed(&base_id, "resize", column_index))
                            .track_focus(
                                resize_focus[column_index]
                                    .as_ref()
                                    .expect("resizable columns have a focus handle"),
                            )
                            .group(resizer_group.clone())
                            .absolute()
                            .top(px(0.))
                            // `px-2` around a `w-px` line, `box-content`: an
                            // 8px grab margin either side of the column edge.
                            .right(px(-8.))
                            .w(px(17.))
                            .h_full()
                            .flex()
                            .items_center()
                            .justify_center()
                            .child(
                                // `h-4 w-px rounded-sm bg-separator`, and
                                // `h-full w-0.5 bg-accent` while hovered.
                                gpui::div()
                                    .w(px(1.))
                                    .h(px(16.))
                                    .rounded(crate::util::hairline_radius(cx))
                                    .bg(colors.separator)
                                    .group_hover(resizer_group.clone(), |s| {
                                        s.w(px(2.)).h_full().bg(accent_color)
                                    })
                                    .when(is_resizing, |s| {
                                        s.w(px(2.)).h_full().bg(accent_color)
                                    })
                                    .when(resize_focused[column_index], |s| {
                                        s.w(px(2.)).h_full().bg(focus_color)
                                    }),
                            )
                            .cursor(gpui::CursorStyle::ResizeLeftRight)
                            .on_mouse_down(gpui::MouseButton::Left, move |ev, window, cx| {
                                window.focus(&focus_for_mouse, cx);
                                if let Some(active_column) = *keyboard_for_pointer.read(cx) {
                                    let current = final_column_widths(
                                        &columns_for_pointer,
                                        widths_for_pointer.read(cx),
                                        &measurements_for_pointer,
                                        active_column,
                                    );
                                    keyboard_for_pointer.update(cx, |active, _| *active = None);
                                    clear_controlled_resize_proposal(
                                        &columns_for_pointer,
                                        &widths_for_pointer,
                                        active_column,
                                        cx,
                                    );
                                    if let Some(callback) = &resize_end_for_pointer {
                                        callback(&current, window, cx);
                                    }
                                }
                                clear_controlled_resize_proposal(
                                    &columns_for_pointer,
                                    &widths_for_pointer,
                                    column_index,
                                    cx,
                                );
                                if let Some(callback) = &resize_start_for_pointer {
                                    let current = resolved_column_widths(
                                        &columns_for_pointer,
                                        widths_for_pointer.read(cx),
                                        &measurements_for_pointer,
                                        None,
                                    );
                                    callback(&current, window, cx);
                                }
                                let x = f32::from(ev.position.x);
                                held.update(cx, |v, _| {
                                    *v = Some((column_index, x, f32::from(start_width)));
                                });
                            })
                            .on_mouse_down_out(move |_, window, cx| {
                                if *keyboard_out.read(cx) == Some(column_index) {
                                    let current = final_column_widths(
                                        &columns_for_outside,
                                        widths_for_outside.read(cx),
                                        &measurements_for_outside,
                                        column_index,
                                    );
                                    keyboard_out.update(cx, |active, cx| {
                                        *active = None;
                                        cx.notify();
                                    });
                                    clear_controlled_resize_proposal(
                                        &columns_for_outside,
                                        &widths_for_outside,
                                        column_index,
                                        cx,
                                    );
                                    if let Some(callback) = &resize_end_for_outside {
                                        callback(&current, window, cx);
                                    }
                                }
                            })
                            .on_key_down(move |event, window, cx| {
                                let key = event.keystroke.key.as_str();
                                let editing = *keyboard.read(cx) == Some(column_index);
                                match key {
                                    "enter" => {
                                        if editing {
                                            let current = final_column_widths(
                                                &columns_for_keys,
                                                widths.read(cx),
                                                &measurements_for_keys,
                                                column_index,
                                            );
                                            keyboard.update(cx, |active, cx| {
                                                *active = None;
                                                cx.notify();
                                            });
                                            clear_controlled_resize_proposal(
                                                &columns_for_keys,
                                                &widths,
                                                column_index,
                                                cx,
                                            );
                                            if let Some(callback) = &resize_end_for_keys {
                                                callback(&current, window, cx);
                                            }
                                        } else {
                                            clear_controlled_resize_proposal(
                                                &columns_for_keys,
                                                &widths,
                                                column_index,
                                                cx,
                                            );
                                            let current = resolved_column_widths(
                                                &columns_for_keys,
                                                widths.read(cx),
                                                &measurements_for_keys,
                                                None,
                                            );
                                            keyboard.update(cx, |active, cx| {
                                                *active = Some(column_index);
                                                cx.notify();
                                            });
                                            if let Some(callback) = &resize_start_for_keys {
                                                callback(&current, window, cx);
                                            }
                                        }
                                        cx.stop_propagation();
                                    }
                                    "escape" | "space" | "tab" if editing => {
                                        let current = final_column_widths(
                                            &columns_for_keys,
                                            widths.read(cx),
                                            &measurements_for_keys,
                                            column_index,
                                        );
                                        keyboard.update(cx, |active, cx| {
                                            *active = None;
                                            cx.notify();
                                        });
                                        clear_controlled_resize_proposal(
                                            &columns_for_keys,
                                            &widths,
                                            column_index,
                                            cx,
                                        );
                                        if let Some(callback) = &resize_end_for_keys {
                                            callback(&current, window, cx);
                                        }
                                        cx.stop_propagation();
                                    }
                                    "right" | "up" | "left" | "down" if editing => {
                                        let delta = if matches!(key, "right" | "up") {
                                            10.
                                        } else {
                                            -10.
                                        };
                                        let mut proposed = start_width;
                                        widths.update(cx, |values, cx| {
                                            if values.len() <= column_index {
                                                values.resize(column_index + 1, None);
                                            }
                                            let current = if controlled {
                                                start_width
                                            } else {
                                                values[column_index].unwrap_or(start_width)
                                            };
                                            let next = (f32::from(current) + delta)
                                                .floor()
                                                .min(max_width)
                                                .max(min_width);
                                            proposed = px(next);
                                            values[column_index] = Some(proposed);
                                            cx.notify();
                                        });
                                        if let Some(callback) = &resize_for_keys {
                                            let current = resolved_column_widths(
                                                &columns_for_keys,
                                                widths.read(cx),
                                                &measurements_for_keys,
                                                Some((column_index, proposed)),
                                            );
                                            callback(&current, window, cx);
                                        }
                                        cx.stop_propagation();
                                    }
                                    _ => {}
                                }
                            }),
                    )
                    .into_any_element()
            } else {
                cell
            };
            header = header.child(cell);
        }
        table = table.child(header);

        // `.table__body` rounds to `min(32px, --radius-2xl)` and its cells are
        // `bg-surface`: the white block inside the tray.
        // `useTableRowGroup.mjs` (through `.../grid/useGridRowGroup.mjs`) is a
        // single `role: 'rowgroup'` — the `<tbody>` around the data rows.
        let mut body = gpui::div()
            .id(element_id::scoped(&base_id, "body"))
            .a11y(a11y::Role::RowGroup)
            .flex()
            .flex_col()
            .w_full();
        if !secondary {
            body = body
                .bg(colors.surface.background)
                .rounded(cx.layout().radius_2xl().min(px(32.)))
                .overflow_hidden();
        }

        // The drag itself: the pointer can leave the table, so paint-time
        // window listeners own the move and release until the drag ends.
        if resizable {
            let held = dragging.clone();
            let held_up = dragging;
            let widths = resized;
            let widths_up = widths.clone();
            let columns_for_move = resize_columns.clone();
            let columns_for_up = resize_columns;
            let measurements_for_move = resize_measurements.clone();
            let measurements_for_up = resize_measurements;
            let resize_callback = self.on_resize.clone();
            let resize_end_callback = self.on_resize_end.clone();
            table = table.relative().child(
                gpui::canvas(
                    |bounds, _, _| bounds,
                    move |_, _, window, _| {
                        let held = held.clone();
                        let widths = widths.clone();
                        let columns_for_move = columns_for_move.clone();
                        let measurements_for_move = measurements_for_move.clone();
                        let resize_callback = resize_callback.clone();
                        window.on_mouse_event(
                            move |event: &gpui::MouseMoveEvent, phase, window, cx| {
                                if phase != gpui::DispatchPhase::Capture
                                    || event.pressed_button != Some(gpui::MouseButton::Left)
                                {
                                    return;
                                }
                                let Some((column, from_x, from_w)) = *held.read(cx) else {
                                    return;
                                };
                                let raw = (from_w + f32::from(event.position.x) - from_x).floor();
                                let min = columns_for_move[column]
                                    .min_width
                                    .map_or(DEFAULT_COLUMN_MIN_WIDTH, f32::from);
                                let max = columns_for_move[column]
                                    .max_width
                                    .map_or(f32::MAX, f32::from);
                                let proposed = px(raw.min(max).max(min));
                                widths.update(cx, |values, cx| {
                                    if values.len() <= column {
                                        values.resize(column + 1, None);
                                    }
                                    values[column] = Some(proposed);
                                    cx.notify();
                                });
                                if let Some(callback) = &resize_callback {
                                    let current = resolved_column_widths(
                                        &columns_for_move,
                                        widths.read(cx),
                                        &measurements_for_move,
                                        Some((column, proposed)),
                                    );
                                    callback(&current, window, cx);
                                }
                            },
                        );

                        let held_up = held_up.clone();
                        let widths_up = widths_up.clone();
                        let columns_for_up = columns_for_up.clone();
                        let measurements_for_up = measurements_for_up.clone();
                        let resize_end_callback = resize_end_callback.clone();
                        window.on_mouse_event(
                            move |event: &gpui::MouseUpEvent, phase, window, cx| {
                                if phase != gpui::DispatchPhase::Capture
                                    || event.button != gpui::MouseButton::Left
                                {
                                    return;
                                }
                                let drag = *held_up.read(cx);
                                if let Some((column, _, _)) = drag {
                                    let current = final_column_widths(
                                        &columns_for_up,
                                        widths_up.read(cx),
                                        &measurements_for_up,
                                        column,
                                    );
                                    held_up.update(cx, |value, cx| {
                                        *value = None;
                                        cx.notify();
                                    });
                                    clear_controlled_resize_proposal(
                                        &columns_for_up,
                                        &widths_up,
                                        column,
                                        cx,
                                    );
                                    if let Some(callback) = &resize_end_callback {
                                        callback(&current, window, cx);
                                    }
                                }
                            },
                        );
                    },
                )
                .absolute()
                .inset_0(),
            );
        }
        // ---- rows --------------------------------------------------------
        // Depth-first, and only through the parents that are open: a nested row
        // is not rendered at all until its parent is expanded.
        let mut flat: Vec<(TableRow, usize, bool, SharedString, Option<SharedString>)> = Vec::new();
        fn flatten(
            rows: Vec<TableRow>,
            depth: usize,
            path: &str,
            parent: Option<&SharedString>,
            expanded: &[SharedString],
            out: &mut Vec<(TableRow, usize, bool, SharedString, Option<SharedString>)>,
        ) {
            for (index, mut row) in rows.into_iter().enumerate() {
                let key = match &row.key {
                    Some(k) => k.clone(),
                    None if path.is_empty() => SharedString::from(index.to_string()),
                    None => SharedString::from(format!("{path}-{index}")),
                };
                let children = std::mem::take(&mut row.children);
                let has_children = !children.is_empty();
                let is_open = expanded.contains(&key);
                out.push((row, depth, has_children, key.clone(), parent.cloned()));
                if has_children && is_open {
                    flatten(children, depth + 1, key.as_ref(), Some(&key), expanded, out);
                }
            }
        }
        flatten(
            std::mem::take(&mut self.rows),
            0,
            "",
            None,
            &self.expanded_keys,
            &mut flat,
        );
        let tree_rows: Vec<(bool, Option<SharedString>)> = virtual_projection.as_ref().map_or_else(
            || {
                flat.iter()
                    .map(|(_, _, has_children, _, parent)| (*has_children, parent.clone()))
                    .collect()
            },
            |projection| {
                projection
                    .visible
                    .iter()
                    .map(|(_, _, metadata)| (metadata.has_children, metadata.parent_key.clone()))
                    .collect()
            },
        );
        let visible_collection_keys: Vec<SharedString> = virtual_visible_keys
            .unwrap_or_else(|| flat.iter().map(|(_, _, _, key, _)| key.clone()).collect());
        let typeahead_labels: Vec<String> = virtual_projection.as_ref().map_or_else(
            || {
                flat.iter()
                    .map(|(row, _, _, _, _)| {
                        row.text_value
                            .as_ref()
                            .map(ToString::to_string)
                            .unwrap_or_default()
                    })
                    .collect()
            },
            |_| Vec::new(),
        );
        let virtual_typeahead_indices = virtual_projection.as_ref().map(|projection| {
            projection
                .visible
                .iter()
                .map(|(source_index, _, _)| *source_index)
                .collect::<Vec<_>>()
        });
        let virtual_text_value = self.virtual_text_value.clone();
        let cursor_key = row_cursor.read(cx).clone();
        let cursor_valid = cursor_key.as_ref().is_none_or(|key| {
            visible_collection_keys.contains(key) && !self.disabled_keys.contains(key)
        });
        if !cursor_valid {
            row_cursor.update(cx, |key, cx| {
                *key = None;
                cx.notify();
            });
        }
        let cursor_at = if window.is_window_active() && table_focus.is_focused(window) {
            cursor_key
                .as_ref()
                .and_then(|key| visible_collection_keys.iter().position(|row| row == key))
                .filter(|index| {
                    !self
                        .disabled_keys
                        .contains(&visible_collection_keys[*index])
                })
                .filter(|_| crate::util::focus_visible(cx))
        } else {
            None
        };
        // Whether any row in this table is expandable at all: a flat table
        // keeps its cells flush, rather than reserving a chevron's width.
        let tree_column_has_children = virtual_projection.as_ref().map_or_else(
            || flat.iter().any(|(_, _, has, _, _)| *has),
            |projection| {
                projection
                    .visible
                    .iter()
                    .any(|(_, _, metadata)| metadata.has_children)
            },
        );
        let expanded_keys = std::rc::Rc::new(std::mem::take(&mut self.expanded_keys));

        // Everything a row needs, held once. The virtual path builds its rows
        // inside a `'static` closure, so it cannot borrow `self` -- and having
        // one row builder for both paths is what keeps a virtual table drawing
        // the same row as a short one.
        let table_id = self.id.clone();
        // Which of the row run's edges coincide with a curved edge of the box
        // that clips it. A virtual body only meets its box at an edge it is
        // actually scrolled to; an unresolved scroll state answers "no",
        // which keeps a square fill rather than a wrongly rounded one.
        let (round_top, round_bottom) = {
            let (touches_top, touches_bottom) = if self.row_height.is_some()
                && self.virtual_rows.is_some()
            {
                let at_top = {
                    let scroll = virtual_scroll_now.0.borrow();
                    scroll.base_handle.offset().y >= px(-0.5)
                };
                // `is_scrolled_to_end` answers `None` when the list does
                // not scroll at all, and then every row is on screen.
                (
                    at_top,
                    virtual_scroll_now.is_scrolled_to_end().unwrap_or(true),
                )
            } else if let Some(state) = &virtual_list_state {
                let top = state.logical_scroll_top();
                let viewport = state.viewport_bounds();
                (
                    top.item_ix == 0 && top.offset_in_item <= px(0.5),
                    virtual_visible_count == 0
                        || state
                            .bounds_for_item(virtual_visible_count - 1)
                            .is_some_and(|bounds| bounds.bottom() <= viewport.bottom() + px(0.5)),
                )
            } else {
                // Plain rows have no scroller of their own, so the run's
                // edges are the box's edges.
                (true, true)
            };
            edge_corner_rounding(
                secondary,
                self.footer.is_some(),
                touches_top,
                touches_bottom,
                cx.layout().radius_2xl().min(px(32.)),
                self.radius
                    .unwrap_or_else(|| crate::util::container_radius(cx)),
            )
        };
        let ctx = std::rc::Rc::new(RowCtx {
            id: base_id.clone(),
            measured_widths,
            measure_intrinsic: self
                .columns
                .iter()
                // `on_children_prepainted` reports the browser canvas child
                // bounds as the full flex track during a web rerender. If we
                // feed that transient width back as a minimum, the first
                // column consumes the whole table after a selection update.
                // Native GPUI reports intrinsic child bounds correctly, so
                // retain the measurement path there and let web flex tracks
                // remain fluid unless a caller pins a width.
                .map(|column| !column.allows_resizing && !cfg!(target_arch = "wasm32"))
                .collect(),
            widths: self
                .columns
                .iter()
                .enumerate()
                .map(|(c, _)| {
                    let (layout_min, layout_max) = layout_width_bounds[c];
                    (
                        effective_widths.get(c).copied().flatten(),
                        layout_min,
                        layout_max,
                    )
                })
                .collect(),
            row_header_columns: self.columns.iter().map(|c| c.is_row_header).collect(),
            tree_column: self.tree_column,
            tree_column_has_children,
            selectable,
            selection_mode: self.selection_mode,
            selection_behavior: self.selection_behavior,
            selected_keys: self.selected_keys.clone(),
            row_keys: visible_collection_keys,
            disabled_keys: self.disabled_keys.clone(),
            disallow_empty_selection: self.disallow_empty_selection,
            expanded: expanded_keys.clone(),
            on_expanded_change: self.on_expanded_change.clone(),
            on_selection_change: self.on_selection_change.clone(),
            selection_own: selection_own.clone(),
            selection_range: selection_range.clone(),
            on_row_click: self.on_row_click.clone(),
            focus: table_focus.clone(),
            cursor_own: row_cursor.clone(),
            cursor: cursor_at,
            secondary,
            row_hover_bg: self.row_hover_bg,
            hover_group_prefix: table_id.clone(),
            virtualized: virtual_projection.is_some(),
            round_top,
            round_bottom,
            is_tree,
        });

        // v3 gives a table a roving row focus: the arrows walk it, Home and End
        // jump, and Enter activates the row -- the same resolver every list here
        // uses, over the rows that exist.
        {
            let stops: Vec<usize> = ctx
                .row_keys
                .iter()
                .enumerate()
                .filter_map(|(index, key)| (!self.disabled_keys.contains(key)).then_some(index))
                .collect();
            let held = row_cursor;
            let typeahead = typeahead;
            let labels = typeahead_labels;
            let virtual_indices = virtual_typeahead_indices;
            let virtual_text = virtual_text_value;
            let on_row_click = self.on_row_click.clone();
            let keys = ctx.row_keys.clone();
            let table_focus_for_keys = table_focus;
            let selection = self.on_selection_change.clone();
            let selection_own_for_keys = selection_own;
            let selection_range_for_keys = selection_range;
            let selected_now = self.selected_keys.clone();
            let mode = self.selection_mode;
            let selection_behavior = self.selection_behavior;
            let disallow_empty_selection = self.disallow_empty_selection;
            // React Aria's collection hook defaults `selectOnFocus` to true
            // for `selectionBehavior="replace"`.
            let select_on_focus =
                selection_behavior == SelectionBehavior::Replace && mode != SelectionMode::None;
            let plain_rows = self.virtual_rows.is_none();
            let fixed_virtual = self.row_height.is_some() && self.virtual_rows.is_some();
            // Pinned `TableKeyboardDelegate` pages by one visible rectangle, so
            // the step reads the virtual body's own laid-out viewport -- the
            // pinned handle's `base_handle.bounds()` -- and not the configured
            // `max_h` cap: a bounded parent (or a resized window) shows fewer
            // rows than the cap allows. A zero viewport answers nothing, which
            // the shared resolver turns into no movement.
            let fixed_row_height = self.row_height.filter(|_| fixed_virtual);
            let fixed_scroll = virtual_scroll_now.clone();
            let variable_scroll = virtual_list_state.clone();
            let variable_heights = virtual_row_heights.clone();
            let variable_estimate = self.estimated_row_height;
            let expanded = expanded_keys;
            let on_expanded = self.on_expanded_change.clone();
            if !keys.is_empty() {
                let typeahead_navigation = std::rc::Rc::new(TableTypeaheadNavigation {
                    state: typeahead,
                    labels,
                    virtual_indices,
                    virtual_text,
                    stops: stops.clone(),
                    keys: keys.clone(),
                    cursor: held.clone(),
                    fixed_virtual,
                    fixed_scroll: fixed_scroll.clone(),
                    variable_scroll: variable_scroll.clone(),
                });
                let capture_typeahead = typeahead_navigation.clone();
                let capture_typeahead_up = typeahead_navigation.clone();
                let capture_focus = table_focus_for_keys.clone();
                let capture_focus_up = table_focus_for_keys.clone();
                wrapper = wrapper.capture_key_down(move |event, window, cx| {
                    if !capture_focus.contains_focused(window, cx) {
                        return;
                    }
                    let key_name = event.keystroke.key.as_str();
                    let typed = event.keystroke.key_char.as_deref().unwrap_or(key_name);
                    let modifiers = &event.keystroke.modifiers;
                    let now = web_time::Instant::now();
                    let is_space = key_name == "space" || typed == " ";
                    if is_space
                        && capture_typeahead.state.read(cx).is_active(now)
                        && !modifiers.control
                        && !modifiers.platform
                        && !modifiers.alt
                    {
                        cx.stop_propagation();
                        capture_typeahead.push(" ", now, false, cx);
                    }
                });
                wrapper = wrapper.capture_key_up(move |event, window, cx| {
                    if !capture_focus_up.contains_focused(window, cx) {
                        return;
                    }
                    let key_name = event.keystroke.key.as_str();
                    let typed = event.keystroke.key_char.as_deref().unwrap_or(key_name);
                    let modifiers = &event.keystroke.modifiers;
                    let is_space = key_name == "space" || typed == " ";
                    if is_space
                        && capture_typeahead_up
                            .state
                            .read(cx)
                            .is_active(web_time::Instant::now())
                        && !modifiers.control
                        && !modifiers.platform
                        && !modifiers.alt
                    {
                        cx.stop_propagation();
                    }
                });
                let key_typeahead = typeahead_navigation;
                // The header PageUp hands the focus to. Cloned out because the
                // handler outlives this frame's `header_focus`.
                let page_up_header = header_focus.first().cloned();
                let headers_for_keys = header_focus;
                wrapper = wrapper.on_key_down(move |event, window, cx| {
                    if !table_focus_for_keys.contains_focused(window, cx) {
                        return;
                    }
                    let from = held
                        .read(cx)
                        .as_ref()
                        .and_then(|key| keys.iter().position(|row| row == key))
                        .filter(|index| stops.contains(index));
                    // Pinned React Aria `useTableRow`: horizontal keys belong
                    // to the focused tree row before the list resolver sees
                    // them. Right opens; Left closes or returns to the parent.
                    let key_name = event.keystroke.key.as_str();
                    let typed = event.keystroke.key_char.as_deref().unwrap_or(key_name);
                    let modifiers = &event.keystroke.modifiers;
                    let now = web_time::Instant::now();
                    let is_space = key_name == "space" || typed == " ";
                    let is_character = {
                        let mut chars = key_name.chars();
                        chars.next().is_some() && chars.next().is_none() && !is_space
                    };
                    let is_typeahead =
                        is_character && !modifiers.control && !modifiers.platform && !modifiers.alt;
                    if is_typeahead {
                        if key_typeahead.push(typed, now, true, cx) {
                            cx.stop_propagation();
                        }
                        return;
                    }
                    // Pinned React Aria 3.51 `useSelectableCollection` binds
                    // `Mod+A` -- the platform Mod, Control here -- to
                    // `selectAll`, and only when the selection mode is
                    // multiple. The shortcut matches its modifiers exactly,
                    // so any extra modifier lets the event fall through.
                    if key_name == "a"
                        && event.keystroke.modifiers.secondary()
                        && !event.keystroke.modifiers.shift
                        && !event.keystroke.modifiers.alt
                        && !event.keystroke.modifiers.function
                        && if cfg!(target_os = "macos") {
                            !event.keystroke.modifiers.control
                        } else {
                            !event.keystroke.modifiers.platform
                        }
                        && mode == SelectionMode::Multiple
                    {
                        let selectable_collection_keys = selectable_collection_keys
                            .as_ref()
                            .expect("multiple Tables have selectable keys");
                        let selectable_collection_keys = selectable_collection_keys.clone();
                        let selectable_collection_keys = selectable_collection_keys.as_slice();
                        let (all_selected, _) =
                            select_all_flags(selectable_collection_keys, &selected_now);
                        let materializes_all =
                            same_selection(selectable_collection_keys, &selected_now);
                        let already_all = all_selected
                            || (selection_range_for_keys.read(cx).is_all && materializes_all);
                        // Pinned React Stately's `selectAll` is idempotent once
                        // the whole selectable collection is already selected.
                        if !already_all {
                            let next = selectable_collection_keys.to_vec();
                            if let Some(held) = &selection_own_for_keys {
                                held.update(cx, |value, cx| {
                                    *value = next.clone();
                                    cx.notify();
                                });
                            }
                            if let Some(cb) = &selection {
                                cb(&next, window, cx);
                            }
                            selection_range_for_keys.update(cx, |range, _| {
                                *range = TableSelectionRange {
                                    is_all: true,
                                    ..TableSelectionRange::default()
                                };
                            });
                        }
                        cx.stop_propagation();
                        return;
                    }
                    // Other collection keys belong only to the body's roving
                    // focus stop. A nested cell action must keep its own Enter
                    // and Space handling even though Mod+A bubbles to the root.
                    // Pinned TableKeyboardDelegate crosses header<->body in
                    // both plain and virtual tables: Down/PageDown from a
                    // focused header enters the body.
                    if headers_for_keys
                        .iter()
                        .any(|header| header.is_focused(window))
                    {
                        let next = match key_name {
                            "down" => stops.first(),
                            "pagedown" => stops.last(),
                            _ => None,
                        };
                        if let Some(next) = next {
                            held.update(cx, |value, cx| {
                                *value = Some(keys[*next].clone());
                                cx.notify();
                            });
                            window.focus(&table_focus_for_keys, cx);
                            cx.stop_propagation();
                        }
                        return;
                    }
                    if !table_focus_for_keys.is_focused(window) {
                        return;
                    }
                    if key_name == "escape"
                        && mode != SelectionMode::None
                        && !disallow_empty_selection
                        && !selected_now.is_empty()
                    {
                        let next = Vec::new();
                        if let Some(held) = &selection_own_for_keys {
                            held.update(cx, |value, cx| {
                                *value = next.clone();
                                cx.notify();
                            });
                        }
                        if let Some(cb) = &selection {
                            cb(&next, window, cx);
                        }
                        selection_range_for_keys.update(cx, |range, _| {
                            *range = TableSelectionRange::default();
                        });
                        cx.stop_propagation();
                        return;
                    }
                    if let Some(index) = from {
                        let focused_key = &keys[index];
                        if let Some((has_children, parent)) = tree_rows.get(index) {
                            if key_name == "right"
                                && *has_children
                                && !expanded.contains(focused_key)
                            {
                                if let Some(cb) = &on_expanded {
                                    let mut next = expanded.as_ref().clone();
                                    next.push(focused_key.clone());
                                    cb(&next, window, cx);
                                }
                                crate::util::set_focus_visible(true, cx);
                                cx.stop_propagation();
                                return;
                            } else if key_name == "left" {
                                if *has_children && expanded.contains(focused_key) {
                                    if let Some(cb) = &on_expanded {
                                        let mut next = expanded.as_ref().clone();
                                        next.retain(|key| key != focused_key);
                                        cb(&next, window, cx);
                                    }
                                    crate::util::set_focus_visible(true, cx);
                                    cx.stop_propagation();
                                    return;
                                } else if let Some(parent) = parent {
                                    if let Some(parent_index) =
                                        keys.iter().position(|key| key == parent)
                                    {
                                        held.update(cx, |value, cx| {
                                            *value = Some(parent.clone());
                                            cx.notify();
                                        });
                                        if fixed_virtual {
                                            fixed_scroll.scroll_to_item(
                                                parent_index,
                                                gpui::ScrollStrategy::Center,
                                            );
                                        } else if let Some(state) = &variable_scroll {
                                            state.scroll_to(gpui::ListOffset {
                                                item_ix: parent_index,
                                                offset_in_item: px(0.),
                                            });
                                        }
                                        crate::util::set_focus_visible(true, cx);
                                        cx.stop_propagation();
                                        return;
                                    }
                                }
                            }
                        }
                    }
                    let page_by_step = |from: usize, step: usize| match key_name {
                        "pagedown" => {
                            let boundary = from.saturating_add(step).min(keys.len() - 1);
                            stops
                                .iter()
                                .copied()
                                .find(|stop| *stop >= boundary)
                                .or_else(|| stops.last().copied())
                        }
                        "pageup" => {
                            let boundary = from.saturating_sub(step);
                            stops
                                .iter()
                                .rev()
                                .copied()
                                .find(|stop| *stop <= boundary)
                                .or_else(|| stops.first().copied())
                        }
                        _ => None,
                    };
                    let fixed_page_move = from.and_then(|from| {
                        let row_height = fixed_row_height?;
                        let viewport_height =
                            f32::from(fixed_scroll.0.borrow().base_handle.bounds().size.height);
                        if viewport_height <= 0. {
                            return None;
                        }
                        let step = ((viewport_height / f32::from(row_height)).ceil() as usize)
                            .saturating_sub(1);
                        page_by_step(from, step)
                    });
                    let variable_page_move = from.and_then(|from| {
                        let viewport_height =
                            variable_scroll.as_ref()?.viewport_bounds().size.height;
                        let heights = variable_heights.as_ref()?.read(cx);
                        let estimate = variable_estimate?;
                        let height_at = |index: usize| {
                            heights.1.get(index).copied().flatten().unwrap_or(estimate)
                        };
                        let mut distance = height_at(from);
                        let mut target = from;
                        match key_name {
                            "pagedown" => {
                                if distance >= viewport_height {
                                    return Some(target);
                                }
                                for next in stops.iter().copied().filter(|next| *next > from) {
                                    for index in target + 1..=next {
                                        distance += height_at(index);
                                    }
                                    target = next;
                                    if distance >= viewport_height {
                                        break;
                                    }
                                }
                                Some(target)
                            }
                            "pageup" => {
                                if distance >= viewport_height {
                                    return Some(target);
                                }
                                for previous in stops
                                    .iter()
                                    .rev()
                                    .copied()
                                    .filter(|previous| *previous < from)
                                {
                                    for index in previous..target {
                                        distance += height_at(index);
                                    }
                                    target = previous;
                                    if distance >= viewport_height {
                                        break;
                                    }
                                }
                                Some(target)
                            }
                            _ => None,
                        }
                    });
                    let is_variable_page =
                        fixed_page_move.is_none() && variable_page_move.is_some();
                    // Pinned TableKeyboardDelegate sends PageDown to the last
                    // enabled row, and PageUp out of the body entirely, into
                    // the first column header. The header is focusable whether
                    // or not it sorts, so this leaves the body rather than
                    // stopping at its first row. Virtual tables page by
                    // viewport first; only when the upward page move has
                    // nowhere to go (the cursor is already the first enabled
                    // stop, or the computed page target equals it) does
                    // PageUp enter the header. The cursor stays seated so
                    // Down from the header returns to the first enabled row.
                    if plain_rows && key_name == "pageup" {
                        if let Some(header) = &page_up_header {
                            window.focus(header, cx);
                            cx.stop_propagation();
                            return;
                        }
                    } else if !plain_rows && key_name == "pageup" {
                        let at_top = match from {
                            Some(position) => {
                                stops.first().is_some_and(|first| *first == position)
                                    || fixed_page_move.is_some_and(|target| Some(target) == from)
                                    || variable_page_move.is_some_and(|target| Some(target) == from)
                            }
                            None => false,
                        };
                        if at_top {
                            if let Some(header) = &page_up_header {
                                window.focus(header, cx);
                                cx.stop_propagation();
                                return;
                            }
                        }
                    }
                    let plain_page_move =
                        from.filter(|_| plain_rows).and_then(|_| match key_name {
                            "pagedown" => stops.last().copied(),
                            _ => None,
                        });
                    let page_move = fixed_page_move
                        .or(variable_page_move)
                        .or(plain_page_move)
                        .filter(|next| Some(*next) != from);
                    // The pinned registrations install no Home/End handler
                    // for an unregistered chord -- Cmd- or Ctrl-bearing on
                    // macOS, Alt- or platform-bearing elsewhere -- so the
                    // whole event stays inert: no focus move, no selection,
                    // no preventDefault, and no first-press settle either.
                    if matches!(key_name, "home" | "end")
                        && !home_end_registered(*modifiers, cfg!(target_os = "macos"))
                    {
                        return;
                    }
                    let initial_home_end_extends = shift_home_end_extends(
                        "home",
                        modifiers.control,
                        cfg!(target_os = "macos"),
                    );
                    let initial_shift_settle = from.is_none()
                        && modifiers.shift
                        && (key_name == "up"
                            || (matches!(key_name, "home" | "end") && !initial_home_end_extends)
                            || (key_name == "down" && stops.len() < 2));
                    let navigation = if from.is_none() && modifiers.shift && key_name == "down" {
                        stops
                            .get(1)
                            .or_else(|| stops.first())
                            .copied()
                            .map_or(crate::list_nav::Move::Ignore, crate::list_nav::Move::To)
                    } else if initial_shift_settle {
                        (if key_name == "end" {
                            stops.last()
                        } else {
                            stops.first()
                        })
                        .copied()
                        .map_or(crate::list_nav::Move::Ignore, crate::list_nav::Move::To)
                    } else {
                        page_move.map_or_else(
                            || crate::list_nav::resolve(&stops, from, key_name, false),
                            crate::list_nav::Move::To,
                        )
                    };
                    match navigation {
                        crate::list_nav::Move::To(next) => {
                            // Pinned `useSelectableCollection`: Shift extends a
                            // multiple selection from the anchor with no other
                            // chord, so plain Shift navigation is exact.
                            let exact_shift_navigation = if cfg!(target_os = "macos") {
                                !modifiers.control && !modifiers.platform && !modifiers.function
                            } else {
                                !modifiers.alt && !modifiers.platform && !modifiers.function
                            };
                            let extends_selection = modifiers.shift
                                && mode == SelectionMode::Multiple
                                && exact_shift_navigation
                                && !initial_shift_settle
                                && Some(next) != from
                                && shift_home_end_extends(
                                    key_name,
                                    modifiers.control,
                                    cfg!(target_os = "macos"),
                                );
                            if extends_selection {
                                if let Some(target) = keys.get(next) {
                                    let range = selection_range_for_keys.read(cx).clone();
                                    let next_selection = extend_selection_range(
                                        &selected_now,
                                        &keys,
                                        selectable_collection_keys
                                            .as_ref()
                                            .expect("multiple Tables have selectable keys")
                                            .as_slice(),
                                        &range,
                                        target,
                                    );
                                    selection_range_for_keys.update(cx, |range, _| {
                                        if range.anchor.is_none() {
                                            range.anchor = Some(target.clone());
                                        }
                                        range.current = Some(target.clone());
                                        range.is_all = false;
                                    });
                                    if !same_selection(&next_selection, &selected_now) {
                                        if let Some(held) = &selection_own_for_keys {
                                            held.update(cx, |value, cx| {
                                                *value = next_selection.clone();
                                                cx.notify();
                                            });
                                        }
                                        if let Some(cb) = &selection {
                                            cb(&next_selection, window, cx);
                                        }
                                    }
                                }
                            } else if select_on_focus
                                && !modifiers.shift
                                && !((cfg!(target_os = "macos") && modifiers.alt)
                                    || (!cfg!(target_os = "macos") && modifiers.control))
                            {
                                if let Some(target) = keys.get(next) {
                                    let next_selection = vec![target.clone()];
                                    if !same_selection(&next_selection, &selected_now) {
                                        if let Some(held) = &selection_own_for_keys {
                                            held.update(cx, |value, cx| {
                                                *value = next_selection.clone();
                                                cx.notify();
                                            });
                                        }
                                        if let Some(cb) = &selection {
                                            cb(&next_selection, window, cx);
                                        }
                                    }
                                    selection_range_for_keys.update(cx, |range, _| {
                                        *range = TableSelectionRange {
                                            anchor: Some(target.clone()),
                                            current: Some(target.clone()),
                                            ..TableSelectionRange::default()
                                        };
                                    });
                                }
                            }
                            held.update(cx, |v, cx| {
                                *v = keys.get(next).cloned();
                                cx.notify();
                            });
                            if fixed_virtual {
                                fixed_scroll.scroll_to_item(next, gpui::ScrollStrategy::Center);
                            } else if let Some(state) = &variable_scroll {
                                if is_variable_page {
                                    state.scroll_to_reveal_item(next);
                                } else {
                                    // Unmeasured rows have no cached height, so
                                    // `scroll_to_reveal_item` cannot locate a far
                                    // target. Jump by logical index; the next
                                    // layout measures that row at the viewport.
                                    state.scroll_to(gpui::ListOffset {
                                        item_ix: next,
                                        offset_in_item: px(0.),
                                    });
                                }
                            }
                        }
                        crate::list_nav::Move::Activate => {
                            let Some(index) = from else { return };
                            let activation = if event.keystroke.key == "enter" {
                                RowActivation::Enter
                            } else {
                                RowActivation::Space
                            };
                            match row_intent(
                                activation,
                                mode,
                                selection_behavior,
                                selected_now.is_empty(),
                                on_row_click.is_some(),
                            ) {
                                RowIntent::Action => {
                                    if let Some(cb) = &on_row_click {
                                        cb(&index, &ClickEvent::default(), window, cx);
                                    }
                                }
                                RowIntent::Selection => {
                                    if let Some(key) = keys.get(index) {
                                        let was_selected = selected_now.contains(key);
                                        let extends_selection =
                                            modifiers.shift && mode == SelectionMode::Multiple;
                                        let next = if extends_selection {
                                            let range = selection_range_for_keys.read(cx).clone();
                                            extend_selection_range(
                                                &selected_now,
                                                &keys,
                                                selectable_collection_keys
                                                    .as_ref()
                                                    .expect("multiple Tables have selectable keys")
                                                    .as_slice(),
                                                &range,
                                                key,
                                            )
                                        } else {
                                            let non_contiguous = if cfg!(target_os = "macos") {
                                                modifiers.alt
                                            } else {
                                                modifiers.control
                                            };
                                            crate::selection::next_selection_with_behavior(
                                                &selected_now,
                                                key,
                                                mode,
                                                if non_contiguous {
                                                    SelectionBehavior::Toggle
                                                } else {
                                                    selection_behavior
                                                },
                                                disallow_empty_selection,
                                            )
                                        };
                                        let changed = !same_selection(&next, &selected_now);
                                        if changed {
                                            if let Some(held) = &selection_own_for_keys {
                                                held.update(cx, |value, cx| {
                                                    *value = next.clone();
                                                    cx.notify();
                                                });
                                            }
                                            if let Some(cb) = &selection {
                                                cb(&next, window, cx);
                                            }
                                        }
                                        if extends_selection && changed {
                                            selection_range_for_keys.update(cx, |range, _| {
                                                if range.anchor.is_none() {
                                                    range.anchor = Some(key.clone());
                                                }
                                                range.current = Some(key.clone());
                                                range.is_all = false;
                                            });
                                        } else if !extends_selection
                                            && mode == SelectionMode::Multiple
                                            && !was_selected
                                        {
                                            selection_range_for_keys.update(cx, |range, _| {
                                                range.anchor = Some(key.clone());
                                                range.current = Some(key.clone());
                                                range.is_all = false;
                                            });
                                        } else if !extends_selection
                                            && mode == SelectionMode::Multiple
                                        {
                                            selection_range_for_keys.update(cx, |range, _| {
                                                if range.is_all {
                                                    *range = TableSelectionRange::default();
                                                }
                                            });
                                        }
                                    }
                                }
                                RowIntent::None => {}
                            }
                        }
                        crate::list_nav::Move::Ignore => {}
                    }
                });
            }
        }

        let row_count = if self.virtual_rows.is_some()
            && (self.row_height.is_some() || self.estimated_row_height.is_some())
        {
            virtual_visible_count
        } else {
            flat.len()
        };
        let virtual_projection = std::rc::Rc::new(
            virtual_projection
                .map(|projection| std::sync::Arc::clone(&projection.visible))
                .unwrap_or_default(),
        );

        // `estimatedRowHeight` takes the variable-height path: gpui's `list`
        // measures each row it builds, and its state is intrusive, so it lives in
        // the window's keyed store and resets when the count changes.
        if let (Some(row_height), Some((_, _, _, factory))) =
            (self.row_height, self.virtual_rows.clone())
        {
            // The body scrolls inside `uniform_list`, which asks for the rows the
            // viewport shows and no others. A fixed height caps the roomy-window
            // body at the configured value, so an unbounded (natural-height)
            // page parent sizes the whole table to header + cap + padding
            // instead of the rows' full natural height; `min_h_0` lets that
            // fixed height shrink as a flex item with a bounded parent, handing
            // the virtual body its real viewport. (`Infer` + `max_h` caps the
            // list's own bounds but reports the full natural height upward, so
            // the outer table stretches white past the shown rows.)
            let height = self.max_h.unwrap_or(px(400.));
            let rows = ctx.clone();
            let projection = virtual_projection;
            // The headless probe name for the virtual viewport's bounds.
            let rows_selector = format!("{table_id}-virtual-rows");
            body = body.child(
                gpui::uniform_list(
                    element_id::scoped(&base_id, "virtual-rows"),
                    row_count,
                    move |range, _window, cx| {
                        range
                            .map(|i| {
                                let (source_index, key, metadata) = &projection[i];
                                let row_data = factory(*source_index);
                                rows.row(
                                    i,
                                    row_data,
                                    metadata.depth,
                                    metadata.has_children,
                                    key,
                                    Some(row_height),
                                    cx,
                                )
                            })
                            .collect::<Vec<_>>()
                    },
                )
                .track_scroll(&virtual_scroll_now)
                .h(height)
                .min_h_0()
                .w_full()
                .debug_selector(move || rows_selector),
            );
        } else if let (Some(state), Some((_, _, _, factory))) =
            (virtual_list_state, self.virtual_rows.clone())
        {
            let height = self.max_h.unwrap_or(px(400.));
            let rows = ctx.clone();
            let projection = virtual_projection;
            let measured_heights =
                virtual_row_heights.expect("estimated row height creates a measurement store");
            body = body.child(
                gpui::list(state, move |i, _window, cx| {
                    let (source_index, key, metadata) = &projection[i];
                    let row_data = factory(*source_index);
                    let row = rows.row(
                        i,
                        row_data,
                        metadata.depth,
                        metadata.has_children,
                        key,
                        None,
                        cx,
                    );
                    let measured = measured_heights.clone();
                    gpui::div()
                        .relative()
                        .w_full()
                        .child(row)
                        .child(
                            gpui::canvas(
                                move |bounds: gpui::Bounds<Pixels>, _, cx| {
                                    measured.update(cx, |(_, heights), cx| {
                                        if heights.get(i).copied().flatten()
                                            != Some(bounds.size.height)
                                        {
                                            heights[i] = Some(bounds.size.height);
                                            cx.notify();
                                        }
                                    });
                                    bounds
                                },
                                |_, _, _, _| {},
                            )
                            .absolute()
                            .inset_0(),
                        )
                        .into_any_element()
                })
                .h(height)
                .w_full(),
            );
        } else {
            for (i, (row_data, depth, has_children, tree_key, _)) in flat.into_iter().enumerate() {
                body = body.child(ctx.row(i, row_data, depth, has_children, &tree_key, None, cx));
            }
        }

        // ---- empty state -------------------------------------------------
        if row_count == 0 {
            if let Some(content) = self.empty_state {
                body = body.child(
                    gpui::div()
                        .flex()
                        .items_center()
                        .justify_center()
                        .w_full()
                        .py(px(28.))
                        .text_color(muted)
                        .child(content),
                );
            }
        }

        table = table.child(body);

        // ---- load-more sentinel ------------------------------------------
        if self.is_pending || self.on_load_more.is_some() {
            if let Some(cb) = self.on_load_more.clone() {
                let state = load_more_state;
                let scroll_offset = self.load_more_offset;
                let virtual_scroll = load_more_virtual_scroll;
                let variable_scroll = load_more_variable_scroll;
                table = table.child(
                    gpui::canvas(
                        move |bounds, window, cx| {
                            // Plain rows place this canvas at the real content
                            // end, so ancestor masks provide its viewport
                            // intersection. Virtual rows keep that end inside
                            // their own scroll state instead.
                            let mask = window.content_mask().bounds;
                            let in_view = bounds.right() >= mask.left()
                                && bounds.left() <= mask.right()
                                && bounds.bottom() >= mask.top()
                                && bounds.top() <= mask.bottom() + mask.size.height * scroll_offset;
                            let virtual_end_is_near = if let Some(handle) = &virtual_scroll {
                                let scroll = handle.0.borrow();
                                scroll.last_item_size.is_some_and(|size| {
                                    let remaining = size.contents.height
                                        + scroll.base_handle.offset().y
                                        - size.item.height;
                                    remaining <= size.item.height * scroll_offset
                                })
                            } else if let Some((state, count, estimate)) = &variable_scroll {
                                let viewport = state.viewport_bounds();
                                let viewport_height = viewport.size.height;
                                let top = state.logical_scroll_top();
                                // Unmeasured ListState rows have zero height,
                                // so project the unseen tail from the caller's
                                // layout estimate instead.
                                let remaining = *estimate * count.saturating_sub(top.item_ix)
                                    - top.offset_in_item
                                    - viewport_height;
                                let margin = viewport_height * scroll_offset;
                                let measured_end_is_near = *count == 0
                                    || state.bounds_for_item(count.saturating_sub(1)).is_some_and(
                                        |bounds| bounds.bottom() <= viewport.bottom() + margin,
                                    );
                                measured_end_is_near || (scroll_offset > 0. && remaining <= margin)
                            } else {
                                true
                            };
                            let visible = if virtual_scroll.is_some() || variable_scroll.is_some() {
                                virtual_end_is_near
                            } else {
                                in_view
                            };
                            let previous = state.read(cx).clone();
                            let collection_changed = previous
                                .1
                                .as_ref()
                                .is_none_or(|identity| identity != &load_more_collection);
                            let should_load = visible && (!previous.0 || collection_changed);
                            if previous.0 != visible || should_load {
                                state.update(cx, |value, cx| {
                                    value.0 = visible;
                                    if should_load {
                                        value.1 = Some(load_more_collection.clone());
                                    }
                                    cx.notify();
                                });
                            }
                            if should_load {
                                cb(window, cx);
                            }
                        },
                        |_, _, _, _| {},
                    )
                    .size(px(1.)),
                );
            }

            if self.is_pending {
                let sentinel = gpui::div()
                .id(element_id::scoped(&base_id, "load-more"))
                .flex()
                .items_center()
                .justify_center()
                .gap(px(8.))
                .w_full()
                // `.table__load-more-content` is `gap-2 py-2`; `loaderHeight`
                // fixes the row's height instead when the caller sets it.
                .py(px(8.))
                .when_some(self.loader_height, |el, h| el.h(h))
                .text_size(px(13.))
                .text_color(muted)
                    .child(
                        crate::spinner::Spinner::new(element_id::scoped(&base_id, "load-spinner"))
                            .size(herogpui_core::Size::Sm),
                    )
                    .child("Loading\u{2026}");
                table = table.child(sentinel);
            }
        }

        if let Some(footer) = self.footer {
            // `.table__footer` is `flex items-center px-4 py-2.5`.
            table = table.child(
                gpui::div()
                    .flex()
                    .items_center()
                    .w_full()
                    .px(px(16.))
                    .py(px(10.))
                    .child(footer),
            );
        }

        // `.table__scroll-container` is `overflow-x-auto` around the content: a
        // column whose cross axis leaves the content column at its
        // max-content width, so a table wider than its box is free to exceed
        // the scroller and scroll *on* it, while `min_w_full` still fills a
        // narrow box. A row flex here would shrink that child to the viewport
        // unless it carried `flex_shrink_0`, which would also forbid the
        // column's vertical shrink inside a bounded parent; the column
        // direction shrinks the content vertically while never touching its
        // width. `min_h_0` is what permits that shrink: the scroller only
        // scrolls horizontally, so its visible y-overflow would otherwise keep
        // the content-based minimum and never yield.
        // The headless probe name for the scroll viewport's bounds, so a test
        // can read the grid's overflow against it.
        let scroll_selector = format!("{table_id}-scroll-x");
        let el = wrapper.child(
            gpui::div()
                .id(element_id::scoped(&base_id, "scroll-x"))
                .debug_selector(move || scroll_selector)
                .flex()
                .flex_col()
                .items_start()
                .w_full()
                .min_h_0()
                .overflow_x_scroll()
                .restrict_scroll_to_axis()
                .child(table),
        );
        crate::util::apply_sx(el, &self.sx)
    }
}

/// Everything one body row needs, so both the plain and the virtualized path can
/// draw it from the same code.
/// Which corners of a body row's full-bleed fill must be rounded so the fill
/// does not square the curved edge it sits against.
///
/// Vanilla GPUI clips an `overflow_hidden()` child to its parent's rectangle
/// rather than to the parent's rounded corners, so the fill has to carry the
/// curve itself. Which box owns that curve differs by variant: the primary
/// variant's rows sit in the rounded `.table__body` block, while the
/// secondary variant is flat and the wrapper's own corners are the only
/// curve — and there the header sits above the rows, so the top corners are
/// never the rows', and a footer takes the bottom ones when one is present.
fn edge_corner_rounding(
    secondary: bool,
    has_footer: bool,
    touches_top: bool,
    touches_bottom: bool,
    body_radius: Pixels,
    wrapper_radius: Pixels,
) -> (Option<Pixels>, Option<Pixels>) {
    if secondary {
        (
            None,
            (touches_bottom && !has_footer).then_some(wrapper_radius),
        )
    } else {
        (
            touches_top.then_some(body_radius),
            touches_bottom.then_some(body_radius),
        )
    }
}

struct RowCtx {
    /// The table's id, so one table's row ids cannot collide with another's.
    /// Every row part is scoped off it.
    id: gpui::ElementId,
    /// Intrinsic content widths for non-resizable columns. The table uses
    /// these as shared minimum tracks so a long body cell cannot make its row
    /// disagree with the header or its siblings.
    measured_widths: gpui::Entity<Vec<Option<Pixels>>>,
    measure_intrinsic: Vec<bool>,
    /// `(defaultWidth or the resize, minWidth, maxWidth)` per column.
    widths: Vec<(Option<Pixels>, Option<Pixels>, Option<Pixels>)>,
    row_header_columns: Vec<bool>,
    tree_column: usize,
    tree_column_has_children: bool,
    selectable: bool,
    selection_mode: SelectionMode,
    selection_behavior: SelectionBehavior,
    selected_keys: Vec<SharedString>,
    row_keys: Vec<SharedString>,
    disabled_keys: Vec<SharedString>,
    disallow_empty_selection: bool,
    expanded: std::rc::Rc<Vec<SharedString>>,
    on_expanded_change: Option<OnExpandedChange>,
    on_selection_change: Option<OnSelectionChange>,
    selection_own: Option<gpui::Entity<Vec<SharedString>>>,
    selection_range: gpui::Entity<TableSelectionRange>,
    on_row_click: Option<OnRowClick>,
    focus: gpui::FocusHandle,
    cursor_own: gpui::Entity<Option<SharedString>>,
    /// The row the keyboard is on, which wears `status-focused`.
    cursor: Option<usize>,
    /// The `.table-root--secondary` flat layout, whose row hover is a
    /// different token from the primary's.
    secondary: bool,
    /// The caller's unselected-row hover fill, when one was named. Selected
    /// rows keep their selection fill regardless.
    row_hover_bg: Option<gpui::Hsla>,
    /// Prefix for per-row hover groups. HeroUI paints hover and selected
    /// surfaces on each cell, allowing the cell's radius/clip to own the
    /// resulting geometry instead of leaking a row-level fill through gaps.
    hover_group_prefix: SharedString,
    /// Whether the collection is windowed, which is the guard upstream puts
    /// `aria-rowindex` behind (`.../grid/useGridRow.mjs`).
    virtualized: bool,
    /// The radius the first row's outer cells must round their fill to, when
    /// the top of the row run really is the curved edge of its box. `None`
    /// leaves the fill square, which is what a scrolled virtual body needs.
    round_top: Option<Pixels>,
    /// The same for the last row's outer cells and the bottom edge.
    round_bottom: Option<Pixels>,
    /// Whether the collection is a tree, which is what makes
    /// `useTableRow.mjs` add `aria-level` and `aria-expanded` to a row.
    is_tree: bool,
}

impl RowCtx {
    /// One body row.
    ///
    /// `fixed_h` is `Some` only on the virtual path, where every row is one
    /// `rowHeight` tall because that is the number the scroll geometry comes
    /// from.
    #[allow(clippy::too_many_arguments)]
    /// One `.table__row`: `relative h-full` with a `border-separator/50`
    /// bottom edge except on the final visible row, and `.table__cell`s inside
    /// it.
    fn row(
        &self,
        i: usize,
        row_data: TableRow,
        depth: usize,
        has_children: bool,
        tree_key: &SharedString,
        fixed_h: Option<Pixels>,
        cx: &mut App,
    ) -> AnyElement {
        let colors = cx.colors();
        let tree_column = self.tree_column;
        let tree_column_has_children = self.tree_column_has_children;
        let key = tree_key.clone();
        let is_selected = self.selected_keys.contains(&key);
        let is_disabled = self.disabled_keys.contains(&key);
        let row_header_columns = &self.row_header_columns;
        let selected_bg = is_selected.then(|| colors.surface.background.alpha(0.1));
        let hover_bg = (!is_selected && !is_disabled).then(|| {
            self.row_hover_bg.unwrap_or(if self.secondary {
                colors.default.color.alpha(0.5)
            } else {
                colors.surface.background.alpha(0.4)
            })
        });
        let hover_group: SharedString = format!("{}-row-hover-{i}", self.hover_group_prefix).into();
        let row_focused = self.cursor == Some(i);

        let mut row = gpui::div()
            .id(element_id::indexed(&self.id, "row", i))
            // `useTableRow.mjs` delegates to `.../grid/useGridRow.mjs`:
            // `role: 'row'` with `'aria-selected': selectionMode !== 'none' ?
            // isSelected : undefined`, and `aria-rowindex` only
            // `if (isVirtualized)`. On a tree table it then adds
            // `'aria-expanded': hasChildRows ? ... : undefined` and
            // `'aria-level': treeNode.level + 1`.
            //
            // The `aria-posinset`/`aria-setsize` half of that tree block is
            // *not* stated, and not because gpui lacks the builders: upstream
            // counts a row's siblings out of the tree collection, and what
            // reaches this function is the flattened list of *visible* rows
            // plus this row's own depth. The sibling count at that depth is
            // not derivable from it, and a guess is worse than silence.
            .a11y(a11y::Role::Row)
            .when(self.selection_mode != SelectionMode::None, |row| {
                row.a11y_selected(is_selected)
            })
            .when(self.virtualized, |row| row.a11y_row_index(i))
            .when(self.is_tree, |row| row.a11y_level(depth))
            .when(self.is_tree && has_children, |row| {
                row.a11y_expanded(self.expanded.iter().any(|k| k == tree_key))
            })
            .flex()
            .group(hover_group.clone())
            // A virtual row is laid out on its own, so it takes the width it is
            // *given*: without `w_full` the columns bunch at the left edge. That
            // is true of both virtual paths, so it is not conditional on the
            // fixed height any more -- `gpui::list`'s rows have none.
            .w_full()
            .when_some(fixed_h, |e, h| e.h(h));
        if !self.secondary && i + 1 < self.row_keys.len() {
            row = row.border_b_1().border_color(colors.separator.alpha(0.5));
        }

        let data_count = row_data.cells.len();
        // The row's fill is painted per cell, so the outer cells of the first
        // and last rows carry the box's curve on the edge they touch.
        let round_top = (i == 0).then_some(self.round_top).flatten();
        let round_bottom = (i + 1 == self.row_keys.len())
            .then_some(self.round_bottom)
            .flatten();

        if self.selectable {
            let mut cell = gpui::div()
                .id(element_id::indexed(&self.id, "select-cell", i))
                // The selection column's body cell. `useTableCell.mjs` gives
                // every data cell `.../grid/useGridCell.mjs`'s
                // `role: 'gridcell'` and `'aria-colindex': colIndex + 1`.
                .a11y(a11y::Role::GridCell)
                .a11y_column_index(0)
                .flex()
                .items_center()
                .justify_center()
                .relative()
                .w(px(44.))
                .py(px(10.))
                .when_some(selected_bg, |cell, bg| cell.bg(bg))
                .when_some(hover_bg, |cell, bg| {
                    cell.group_hover(hover_group.clone(), move |s| s.bg(bg))
                })
                .when_some(round_top, |cell, r| cell.rounded_tl(r))
                .when_some(round_bottom, |cell, r| cell.rounded_bl(r))
                .when(data_count == 0, |cell| {
                    cell.when_some(round_top, |cell, r| cell.rounded_tr(r))
                        .when_some(round_bottom, |cell, r| cell.rounded_br(r))
                })
                .on_mouse_down(gpui::MouseButton::Left, |_, _, cx| {
                    cx.stop_propagation();
                });
            let mut box_el = Checkbox::new(element_id::indexed(&self.id, "select", i))
                .is_selected(is_selected)
                .is_disabled(is_disabled);
            let cb = self.on_selection_change.clone();
            if !is_disabled && (cb.is_some() || self.selection_own.is_some()) {
                let current = self.selected_keys.clone();
                let key2 = key.clone();
                let mode = self.selection_mode;
                let disallow_empty_selection = self.disallow_empty_selection;
                let selection_own = self.selection_own.clone();
                let selection_range = self.selection_range.clone();
                box_el = box_el.on_change(move |_next, window, cx| {
                    cx.stop_propagation();
                    // A checkbox is the explicit selection affordance. React
                    // Aria toggles it even when the surrounding row uses
                    // `selectionBehavior="replace"`.
                    let next = crate::selection::next_selection(
                        &current,
                        &key2,
                        mode,
                        disallow_empty_selection,
                    );
                    if let Some(held) = &selection_own {
                        held.update(cx, |value, cx| {
                            *value = next.clone();
                            cx.notify();
                        });
                    }
                    if let Some(cb) = &cb {
                        cb(&next, window, cx);
                    }
                    if mode == SelectionMode::Multiple && !is_selected {
                        selection_range.update(cx, |range, _| {
                            range.anchor = Some(key2.clone());
                            range.current = Some(key2.clone());
                            range.is_all = false;
                        });
                    } else if mode == SelectionMode::Multiple {
                        selection_range.update(cx, |range, _| {
                            if range.is_all {
                                *range = TableSelectionRange::default();
                            }
                        });
                    }
                });
            }
            cell = cell.child(box_el);
            if row_focused {
                cell = cell.child(table_cell_focus_ring(cx, true, data_count == 0));
            }
            row = row.child(cell);
        }

        // Cells are flex rows so inline children (chips, buttons) size to
        // their content instead of stretching to the column width.
        let widths = &self.widths;
        let is_expanded = self.expanded.iter().any(|k| k == tree_key);
        let toggle_key = tree_key.clone();
        let expanded_before = self.expanded.clone();
        let on_expanded = self.on_expanded_change.clone();
        row = row.children(row_data.cells.into_iter().enumerate().map(|(c, cell)| {
            let (width, min_width, max_width) =
                widths.get(c).copied().unwrap_or((None, None, None));
            let mut cell_el = gpui::div()
                .when(width.is_none(), flex_cell)
                .when_some(width, |e, w| e.w(w))
                .when_some(min_width, |e, w| e.min_w(w))
                .when_some(max_width, |e, w| e.max_w(w))
                .flex()
                .items_center()
                .gap(px(6.))
                .relative()
                // `.table__cell` is `px-4 py-3`.
                .px(px(16.))
                .py(px(12.))
                .when(self.secondary, |e| {
                    e.border_b_1()
                        .border_color(colors.separator_tertiary().alpha(0.5))
                })
                .when(row_header_columns.get(c).copied().unwrap_or(false), |e| {
                    e.font_weight(gpui::FontWeight::MEDIUM)
                })
                .when_some(selected_bg, |cell, bg| cell.bg(bg))
                .when_some(hover_bg, |cell, bg| {
                    cell.group_hover(hover_group.clone(), move |s| s.bg(bg))
                })
                .when(!self.selectable && c == 0, |cell| {
                    cell.when_some(round_top, |cell, r| cell.rounded_tl(r))
                        .when_some(round_bottom, |cell, r| cell.rounded_bl(r))
                })
                .when(c + 1 == data_count, |cell| {
                    cell.when_some(round_top, |cell, r| cell.rounded_tr(r))
                        .when_some(round_bottom, |cell, r| cell.rounded_br(r))
                });
            if self.measure_intrinsic.get(c).copied().unwrap_or(false) {
                let measurements = self.measured_widths.clone();
                let tree_indent = if c == tree_column {
                    tree_column_padding(depth).map_or(0., f32::from)
                } else {
                    0.
                };
                cell_el = cell_el.on_children_prepainted(move |bounds, _, cx| {
                    let content = intrinsic_children_width(&bounds);
                    if content <= 0. {
                        return;
                    }
                    let next = px(content + 32. + tree_indent);
                    measurements.update(cx, |values, cx| {
                        if values.len() <= c {
                            values.resize(c + 1, None);
                        }
                        if values[c].is_none_or(|current| next > current) {
                            values[c] = Some(next);
                            cx.notify();
                        }
                    });
                });
            }
            // At the end of the chain, and after `flex_cell` — that helper
            // takes a `gpui::Div`, which an `.id(..)` would have turned into a
            // `Stateful<Div>` — and clear of the `.table__cell` padding window
            // `.shots/design_audit.py` opens on the comment above.
            //
            // `useTableCell.mjs` is `.../grid/useGridCell.mjs`'s
            // `role: 'gridcell'`, swapped for `'rowheader'` when the cell's
            // column key is in `rowHeaderColumnKeys` — the port's
            // `TableColumn::is_row_header`. The cell's contents are an
            // arbitrary `AnyElement` here, so unlike a row (which upstream
            // names from `node.textValue`) it carries no name of its own;
            // whatever the caller composed inside reports itself.
            let mut cell_el = cell_el
                .debug_selector(move || format!("table-row-track-{i}-{c}"))
                .id(element_id::indexed(
                    &element_id::indexed(&self.id, "row", i),
                    "cell",
                    c,
                ))
                .a11y(if row_header_columns.get(c).copied().unwrap_or(false) {
                    a11y::Role::RowHeader
                } else {
                    a11y::Role::GridCell
                })
                .a11y_column_index(c + usize::from(self.selectable));
            // The tree column carries the indent and the chevron; a row with
            // no children still indents, so siblings line up.
            if c == tree_column {
                if let Some(padding) = tree_column_padding(depth) {
                    cell_el = cell_el.pl(padding);
                }
                if has_children {
                    let mut chevron = gpui::div()
                        .id(element_id::scoped(
                            &element_id::scoped(&self.id, "expand"),
                            toggle_key.clone(),
                        ))
                        .flex()
                        .items_center()
                        .justify_center()
                        .size(px(18.))
                        .flex_shrink_0()
                        .when(!is_disabled, |chevron| {
                            chevron
                                .cursor(crate::util::interactive_cursor(cx))
                                .on_mouse_down(gpui::MouseButton::Left, |_, _, cx| {
                                    cx.stop_propagation();
                                })
                        })
                        .child(
                            gpui::svg()
                                .size(px(12.))
                                .path(if is_expanded {
                                    icons::CHEVRON_DOWN
                                } else {
                                    icons::CHEVRON_RIGHT
                                })
                                .text_color(colors.muted),
                        );
                    if !is_disabled {
                        if let Some(cb) = on_expanded.clone() {
                            let key = toggle_key.clone();
                            let before = expanded_before.clone();
                            let focus = self.focus.clone();
                            let cursor = self.cursor_own.clone();
                            chevron = chevron.on_click(move |_, window, cx| {
                                cx.stop_propagation();
                                let mut next = before.as_ref().clone();
                                if let Some(at) = next.iter().position(|k| *k == key) {
                                    next.remove(at);
                                } else {
                                    next.push(key.clone());
                                }
                                cb(&next, window, cx);
                                window.focus(&focus, cx);
                                cursor.update(cx, |value, cx| {
                                    *value = Some(key.clone());
                                    cx.notify();
                                });
                            });
                        }
                    }
                    cell_el = cell_el.child(chevron);
                } else if depth > 0 || tree_column_has_children {
                    // A leaf keeps the chevron's width so its text lines up
                    // with its expandable siblings'.
                    cell_el = cell_el.child(gpui::div().size(px(18.)).flex_shrink_0());
                }
            }
            cell_el = cell_el.child(cell);
            if row_focused {
                let cell_index = c + usize::from(self.selectable);
                let total_cells = data_count + usize::from(self.selectable);
                cell_el = cell_el.child(table_cell_focus_ring(
                    cx,
                    cell_index == 0,
                    cell_index + 1 == total_cells,
                ));
            }
            cell_el
        }));

        let row_action = self.on_row_click.clone();
        let row_selection = self.on_selection_change.clone();
        let selection_own = self.selection_own.clone();
        let selection_behavior = self.selection_behavior;
        let disallow_empty_selection = self.disallow_empty_selection;
        if !is_disabled
            && (row_action.is_some()
                || (self.selectable && (row_selection.is_some() || selection_own.is_some())))
        {
            let current = self.selected_keys.clone();
            let mode = self.selection_mode;
            let selection_range = self.selection_range.clone();
            let range_collection = self.row_keys.clone();
            let range_selectable: Vec<SharedString> = self
                .row_keys
                .iter()
                .filter(|key| !self.disabled_keys.contains(key))
                .cloned()
                .collect();
            let moved = self.cursor_own.clone();
            let focus = self.focus.clone();
            let focus_for_click = self.focus.clone();
            let key_for_cursor = key.clone();
            row = row
                .cursor(crate::util::interactive_cursor(cx))
                .on_mouse_down(gpui::MouseButton::Left, move |_, window, cx| {
                    if window.default_prevented() {
                        return;
                    }
                    window.focus(&focus, cx);
                    moved.update(cx, |value, cx| {
                        *value = Some(key_for_cursor.clone());
                        cx.notify();
                    });
                })
                .on_click(move |ev, w, cx| {
                    if !focus_for_click.is_focused(w) {
                        return;
                    }
                    match row_intent(
                        RowActivation::Pointer,
                        mode,
                        selection_behavior,
                        current.is_empty(),
                        row_action.is_some(),
                    ) {
                        RowIntent::Action => {
                            if let Some(cb) = &row_action {
                                cb(&i, ev, w, cx);
                            }
                        }
                        RowIntent::Selection => {
                            let was_selected = current.contains(&key);
                            let extends_selection =
                                ev.modifiers().shift && mode == SelectionMode::Multiple;
                            let next = if extends_selection {
                                let range = selection_range.read(cx).clone();
                                extend_selection_range(
                                    &current,
                                    &range_collection,
                                    &range_selectable,
                                    &range,
                                    &key,
                                )
                            } else {
                                let modifiers = ev.modifiers();
                                let non_contiguous = if cfg!(target_os = "macos") {
                                    modifiers.alt
                                } else {
                                    modifiers.control
                                };
                                crate::selection::next_selection_with_behavior(
                                    &current,
                                    &key,
                                    mode,
                                    if non_contiguous {
                                        SelectionBehavior::Toggle
                                    } else {
                                        selection_behavior
                                    },
                                    disallow_empty_selection,
                                )
                            };
                            let changed = !same_selection(&next, &current);
                            if changed {
                                if let Some(held) = &selection_own {
                                    held.update(cx, |value, cx| {
                                        *value = next.clone();
                                        cx.notify();
                                    });
                                }
                                if let Some(cb) = &row_selection {
                                    cb(&next, w, cx);
                                }
                            }
                            if extends_selection && changed {
                                selection_range.update(cx, |range, _| {
                                    if range.anchor.is_none() {
                                        range.anchor = Some(key.clone());
                                    }
                                    range.current = Some(key.clone());
                                    range.is_all = false;
                                });
                            } else if !extends_selection
                                && mode == SelectionMode::Multiple
                                && !was_selected
                            {
                                selection_range.update(cx, |range, _| {
                                    range.anchor = Some(key.clone());
                                    range.current = Some(key.clone());
                                    range.is_all = false;
                                });
                            } else if !extends_selection && mode == SelectionMode::Multiple {
                                selection_range.update(cx, |range, _| {
                                    if range.is_all {
                                        *range = TableSelectionRange::default();
                                    }
                                });
                            }
                        }
                        RowIntent::None => {}
                    }
                });
        }

        // v3 rings the focused row *inside* itself: each cell carries its own
        // inset strips so the outline stays clipped to the cell geometry.
        row.when(is_disabled, |row| row.opacity(cx.layout().disabled_opacity))
            .into_any_element()
    }
}

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

    #[test]
    fn tree_column_padding_uses_one_rem_per_one_based_level() {
        assert_eq!(tree_column_padding(0), None);
        assert_eq!(tree_column_padding(1), Some(px(32.)));
        assert_eq!(tree_column_padding(2), Some(px(48.)));
        assert_eq!(tree_column_padding(3), Some(px(64.)));
    }

    #[test]
    fn a_new_column_starts_ascending() {
        let next = SortDescriptor::next(None, "name");
        assert_eq!(next, SortDescriptor::new("name", SortDirection::Ascending));
    }

    #[test]
    fn clicking_the_sorted_column_flips_it() {
        let current = SortDescriptor::new("name", SortDirection::Ascending);
        let next = SortDescriptor::next(Some(&current), "name");
        assert_eq!(next.direction, SortDirection::Descending);
        let back = SortDescriptor::next(Some(&next), "name");
        assert_eq!(back.direction, SortDirection::Ascending);
    }

    #[test]
    fn disabled_only_controlled_selection_is_indeterminate() {
        let selectable = vec![SharedString::from("alpha")];
        let selected = vec![SharedString::from("beta")];
        assert_eq!(select_all_flags(&selectable, &selected), (false, true));
    }

    #[test]
    fn switching_column_resets_to_ascending() {
        let current = SortDescriptor::new("name", SortDirection::Descending);
        let next = SortDescriptor::next(Some(&current), "size");
        assert_eq!(next, SortDescriptor::new("size", SortDirection::Ascending));
    }

    #[test]
    fn row_keys_fall_back_to_the_index() {
        let table = Table::new(vec!["A".into()])
            .row(vec![])
            .keyed_row("second", vec![])
            .row(vec![]);
        assert_eq!(
            table.row_keys(),
            vec![
                SharedString::from("0"),
                SharedString::from("second"),
                SharedString::from("2"),
            ]
        );
    }

    /// The Home/End gate takes the platform as an explicit bool, so this
    /// truth table is free of `cfg!` and mechanically proves both maps from
    /// any host: no macOS chord ever extends -- Shift and Alt+Shift move the
    /// focus alone -- while Windows and Linux extend exactly from
    /// Control+Shift.
    #[test]
    fn shift_home_end_extends_only_from_control_outside_macos() {
        for key in ["home", "end"] {
            assert!(
                !shift_home_end_extends(key, true, true),
                "macOS registers no Home/End extension"
            );
            assert!(!shift_home_end_extends(key, false, true));
            assert!(
                shift_home_end_extends(key, true, false),
                "Control+Shift+{key} must extend on Windows and Linux"
            );
            assert!(
                !shift_home_end_extends(key, false, false),
                "plain Shift+{key} must only move the focus"
            );
        }
    }

    /// The grid delegate's arrows never consult the Home/End gate: their
    /// forbidden extra chords are rejected earlier, by
    /// `exact_shift_navigation`.
    #[test]
    fn shift_navigation_keys_do_not_consult_the_home_end_gate() {
        for key in ["left", "right", "up", "down"] {
            assert!(shift_home_end_extends(key, false, true));
            assert!(shift_home_end_extends(key, true, false));
        }
    }

    /// The registration gate takes `Modifiers`, so the pinned chord map can
    /// be spelled out: macOS registers none, Shift, Alt, and Alt+Shift and
    /// every Control- or Meta-bearing chord is entirely inert, while
    /// Windows and Linux register none, Shift, Control, and Control+Shift
    /// and reject every Alt- or Meta-bearing chord. The upstream matcher
    /// sees only the browser's Alt/Control/Meta/Shift flags, so GPUI's
    /// `function` flag is ignored: `fn` stays registered on both maps, and
    /// it never rescues a chord the platform itself rejects.
    #[test]
    fn home_end_registration_matches_the_pinned_chord_map() {
        let none = gpui::Modifiers::none();
        let shift = gpui::Modifiers {
            shift: true,
            ..none
        };
        let alt = gpui::Modifiers { alt: true, ..none };
        let alt_shift = gpui::Modifiers { shift: true, ..alt };
        let function = gpui::Modifiers {
            function: true,
            ..none
        };
        let function_alt = gpui::Modifiers {
            alt: true,
            ..function
        };
        for modifiers in [none, shift, alt, alt_shift, function, function_alt] {
            assert!(
                home_end_registered(modifiers, true),
                "macOS must register {modifiers:?}"
            );
        }
        let control = gpui::Modifiers {
            control: true,
            ..none
        };
        let control_shift = gpui::Modifiers {
            shift: true,
            ..control
        };
        let platform = gpui::Modifiers {
            platform: true,
            ..none
        };
        let platform_shift = gpui::Modifiers {
            shift: true,
            ..platform
        };
        for modifiers in [control, control_shift, platform, platform_shift] {
            assert!(
                !home_end_registered(modifiers, true),
                "macOS must not register {modifiers:?}"
            );
        }
        for modifiers in [none, shift, control, control_shift, function] {
            assert!(
                home_end_registered(modifiers, false),
                "Windows and Linux must register {modifiers:?}"
            );
        }
        for modifiers in [alt, alt_shift, function_alt, platform, platform_shift] {
            assert!(
                !home_end_registered(modifiers, false),
                "Windows and Linux must not register {modifiers:?}"
            );
        }
    }

    /// The keystroke spellings real events hand the gate: `ctrl` parses to
    /// the Control field the Windows/Linux registration admits and macOS
    /// vetoes, `cmd` to the platform field macOS vetoes, `alt-shift` to
    /// the chord that stays registered (focus-only) on macOS alone, and
    /// `fn` to the flag the browser matcher never sees, so it registers
    /// exactly like the bare key on both maps.
    #[test]
    fn keystroke_spellings_reach_the_registration_gate() {
        let ctrl_shift_home = gpui::Keystroke::parse("ctrl-shift-home").unwrap();
        assert!(home_end_registered(ctrl_shift_home.modifiers, false));
        assert!(!home_end_registered(ctrl_shift_home.modifiers, true));
        let cmd_shift_home = gpui::Keystroke::parse("cmd-shift-home").unwrap();
        assert!(!home_end_registered(cmd_shift_home.modifiers, true));
        let alt_shift_end = gpui::Keystroke::parse("alt-shift-end").unwrap();
        assert!(home_end_registered(alt_shift_end.modifiers, true));
        assert!(!home_end_registered(alt_shift_end.modifiers, false));
        let fn_home = gpui::Keystroke::parse("fn-home").unwrap();
        assert!(fn_home.modifiers.function);
        assert!(home_end_registered(fn_home.modifiers, true));
        assert!(home_end_registered(fn_home.modifiers, false));
    }

    // The pinned sortable column hover only recolours the header text to
    // `--foreground`; it paints no background. `soft()` is a lighter, wrong
    // wash, so the check is mechanical.
    #[test]
    fn the_sort_header_hover_paints_no_background() {
        // Scan the implementation only; this test's own text names the
        // forbidden accessor.
        let source = include_str!("table.rs")
            .split("#[cfg(test)]")
            .next()
            .expect("the implementation section is always present");
        assert!(
            source.contains(".group_hover(sort_group, |s| s.text_color(colors.foreground))"),
            "the sortable header hover must recolour the text to `--foreground` \
             (pinned `.table__column[data-allows-sorting]:hover`)"
        );
        assert!(
            !source.contains("colors.default.soft()"),
            "the sortable header hover must not come back as a soft background"
        );
    }

    // The pinned row hover is variant-specific: `.table-root--primary` rows
    // fill `bg-surface/40`, `.table-root--secondary` rows fill
    // `bg-default/50`.
    #[test]
    fn the_row_hover_is_variant_specific() {
        // Scan the implementation only.
        let source = include_str!("table.rs")
            .split("#[cfg(test)]")
            .next()
            .expect("the implementation section is always present");
        assert!(
            source.contains("colors.default.color.alpha(0.5)")
                && source.contains("colors.surface.background.alpha(0.4)"),
            "the row hover must read `bg-default/50` on secondary and \
             `bg-surface/40` on primary"
        );
    }

    // The pinned selected row fills `bg-surface/10`, and the rule follows the
    // hover rule in the pinned stylesheet, so it wins the cascade: a hovered
    // selected row keeps the selected fill. `accent.soft()` is a role wash
    // the pinned table never paints, so the check is mechanical.
    #[test]
    fn the_selected_row_fills_surface_ten_percent_and_outranks_the_hover() {
        // Scan the implementation only; this test's own text names the
        // forbidden accessor.
        let source = include_str!("table.rs")
            .split("#[cfg(test)]")
            .next()
            .expect("the implementation section is always present");
        assert!(
            source.contains(
                "let selected_bg = is_selected.then(|| colors.surface.background.alpha(0.1));"
            ),
            "the selected row must fill `bg-surface/10` \
             (pinned `.table__row[data-selected] .table__cell`)"
        );
        assert!(
            source.contains(".when_some(selected_bg, |cell, bg| cell.bg(bg))")
                && source.contains("cell.group_hover(hover_group.clone(), move |s| s.bg(bg))"),
            "selected and hover fills must be painted on each cell, with the \
             selected row omitting the hover group so HeroUI's selected rule wins"
        );
        assert!(
            !source.contains("accent.soft()"),
            "the selected row must not paint a role soft wash"
        );
    }

    #[test]
    fn table_focus_ring_is_split_per_cell() {
        let source = include_str!("table.rs")
            .split("#[cfg(test)]")
            .next()
            .expect("the implementation section is always present");
        assert!(
            source.contains("fn table_cell_focus_ring(cx: &App, first: bool, last: bool)")
                && source.contains(".top_0()")
                && source.contains(".bottom_0()")
                && source.contains("cell_el = cell_el.child(table_cell_focus_ring("),
            "focused rows must paint clipped edge strips on each cell"
        );
        assert!(
            !source.contains("r.child(crate::util::inset_focus_ring(cx))"),
            "the row must not use one rounded overlay that bleeds across cells"
        );
    }

    #[test]
    fn table_header_uses_medium_weight() {
        let source = include_str!("table.rs")
            .split("#[cfg(test)]")
            .next()
            .expect("the implementation section is always present");
        assert!(
            source.contains(".text_size(px(12.))")
                && source.contains(".line_height(px(16.))")
                && source.contains(".font_weight(gpui::FontWeight::MEDIUM)"),
            "table column headers must use the pinned `font-medium` weight"
        );
    }

    #[test]
    fn table_header_preserves_caller_label_case() {
        let source = include_str!("table.rs")
            .split("#[cfg(test)]")
            .next()
            .expect("the implementation section is always present");
        assert!(
            source.contains(".child(column.label.clone());"),
            "table column headers must render the caller's label without uppercasing it"
        );
    }

    #[test]
    fn table_header_and_rows_use_half_alpha_separator() {
        let source = include_str!("table.rs")
            .split("#[cfg(test)]")
            .next()
            .expect("the implementation section is always present");
        assert!(
            source.match_indices("colors.separator.alpha(0.5)").count() >= 2,
            "the header and row separators must use the separator token at 50% alpha"
        );
    }

    #[test]
    fn table_last_row_omits_the_bottom_separator() {
        let source = include_str!("table.rs")
            .split("#[cfg(test)]")
            .next()
            .expect("the implementation section is always present");
        assert!(
            source.contains("if !self.secondary && i + 1 < self.row_keys.len() {")
                && source
                    .contains("row = row.border_b_1().border_color(colors.separator.alpha(0.5));"),
            "the final visible Table row must not receive a bottom separator"
        );
    }

    #[test]
    fn secondary_table_uses_surface_headers_and_cell_separators() {
        let source = include_str!("table.rs")
            .split("#[cfg(test)]")
            .next()
            .expect("the implementation section is always present");
        assert!(
            source.contains("cell = cell\n                    .bg(colors.surface_secondary)")
                && source.contains("colors.separator_tertiary().alpha(0.5)"),
            "secondary tables must paint the header surface and per-cell tertiary separators"
        );
    }

    #[test]
    fn table_headers_keep_short_separators_and_rotate_builtin_sort_indicator() {
        let source = include_str!("table.rs")
            .split("#[cfg(test)]")
            .next()
            .expect("the implementation section is always present");
        assert!(
            source.contains(".h(px(16.))")
                && source.contains(".bg(colors.separator)")
                && source.contains("rotating_indicator_with_duration")
                && source.contains(".path(icons::CHEVRON_UP)"),
            "table headers must draw the pinned separator and use the shared 100ms rotation"
        );
    }

    /// The primary variant's rows sit in the rounded `.table__body`, whose
    /// top and bottom curves both bound the row run.
    #[test]
    fn primary_row_fills_round_to_the_body_on_the_edges_they_touch() {
        let body = px(16.);
        let wrapper = px(24.);
        assert_eq!(
            edge_corner_rounding(false, false, true, true, body, wrapper),
            (Some(body), Some(body))
        );
        // A footer sits below the body, so it never takes the body's curve.
        assert_eq!(
            edge_corner_rounding(false, true, true, true, body, wrapper),
            (Some(body), Some(body))
        );
        // A virtual body scrolled off either edge is cut straight there.
        assert_eq!(
            edge_corner_rounding(false, false, false, true, body, wrapper),
            (None, Some(body))
        );
        assert_eq!(
            edge_corner_rounding(false, false, true, false, body, wrapper),
            (Some(body), None)
        );
        assert_eq!(
            edge_corner_rounding(false, false, false, false, body, wrapper),
            (None, None)
        );
    }

    /// The secondary variant is flat, so the wrapper's corners are the only
    /// curve -- and the header always stands between them and the first row.
    #[test]
    fn secondary_row_fills_round_only_to_the_wrapper_bottom() {
        let body = px(16.);
        let wrapper = px(24.);
        assert_eq!(
            edge_corner_rounding(true, false, true, true, body, wrapper),
            (None, Some(wrapper))
        );
        // A footer takes the wrapper's bottom edge instead.
        assert_eq!(
            edge_corner_rounding(true, true, true, true, body, wrapper),
            (None, None)
        );
        assert_eq!(
            edge_corner_rounding(true, false, true, false, body, wrapper),
            (None, None)
        );
    }

    /// The decision is taken once per render and threaded through `RowCtx`,
    /// and only the first and last rows' outer cells may consume it.
    #[test]
    fn only_the_outer_cells_of_the_edge_rows_round_their_fill() {
        let source = include_str!("table.rs")
            .split("#[cfg(test)]")
            .next()
            .expect("the implementation section is always present");
        assert!(
            source.contains("let round_top = (i == 0).then_some(self.round_top).flatten();")
                && source.contains("let round_bottom = (i + 1 == self.row_keys.len())"),
            "only the first and last body rows may round their cell fills"
        );
        assert!(
            source.contains(".when(!self.selectable && c == 0, |cell| {")
                && source.contains(".when(c + 1 == data_count, |cell| {")
                && source.contains(".when_some(round_top, |cell, r| cell.rounded_tl(r))")
                && source.contains(".when_some(round_bottom, |cell, r| cell.rounded_br(r))"),
            "the row's leading and trailing cells must carry the box's corners"
        );
        assert!(
            source.contains("virtual_scroll_now.is_scrolled_to_end().unwrap_or(true)")
                && source.contains("top.item_ix == 0 && top.offset_in_item <= px(0.5)"),
            "a virtual body must only round the edges it is scrolled to"
        );
    }

    #[test]
    fn virtual_selectable_keys_are_not_materialized_on_every_render() {
        let source = include_str!("table.rs")
            .split("#[cfg(test)]")
            .next()
            .expect("the implementation section is always present");
        assert!(
            !source.contains("let selectable_collection_keys: Vec<SharedString> ="),
            "virtual Table must not allocate a selectable-key Vec for every render"
        );
    }
}