teksilo-widgets 0.9.0

Widget library for Teksilo — over a hundred widgets and layout primitives, from Button to TreeTableView.
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
// SPDX-License-Identifier: MPL-2.0
// SPDX-FileCopyrightText: 2026 FernTech

//! `TableView<T>` — generic, virtualized, accessible tabular widget.
//!
//! Built atop the [`ListModel<T>`](teksilo_data::ListModel) /
//! [`ListDataSource`] data layer in
//! `teksilo-data` and the `teksilo-tokens` `TableStyle`. Mirrors Qt's
//! `QTableView`, SwiftUI's `Table`, and JavaFX's `TableView`.
//! The core skeleton: single body pane, row-virtualized with alternating
//! backgrounds, grid lines, `Role::Table > Role::Row > Role::Cell`
//! accessibility, multi-row selection, and an empty-state slot. Headers,
//! sort, filter, resize, reorder, pinning, cell selection, and editing are
//! also included. Row heights come in three modes: uniform (`row_height`,
//! the default fast path), exact per-row callback (`row_height_fn`), and
//! auto-measured (`auto_row_height` — rows grow to their tallest cell,
//! height-for-width). See docs/table-view.md "Row heights".
//!
//! ```ignore
//! use teksilo_data::ListModel;
//! use teksilo_widgets::table_view::{Column, ColumnWidth, TableView};
//! use teksilo_i18n::lit;
//!
//! struct Person { name: String, age: u32 }
//!
//! let model: ListModel<Person> = ListModel::new();
//! let _table = TableView::new(model)
//!     .add_column(Column::new("name", ColumnWidth::Flex(1.0))
//!         .label(lit!("Name"))
//!         .cell(|p: &Person, _cx| Box::new(
//!             teksilo_widgets::primitives::TextWidget::new(
//!                 teksilo_i18n::lit!(p.name.clone())
//!             )
//!         )))
//!     .add_column(Column::new("age", ColumnWidth::Fixed(60.0))
//!         .label(lit!("Age"))
//!         .cell(|p: &Person, _cx| Box::new(
//!             teksilo_widgets::primitives::TextWidget::new(
//!                 teksilo_i18n::lit!(p.age.to_string())
//!             )
//!         )))
//!     .alternating_rows(true)
//!     .row_height(32.0);
//! ```

pub mod a11y;
pub mod body;
pub mod body_pane;
pub mod column;
pub mod filter;
pub mod header;
pub mod imperative;
pub mod keyboard;
pub mod layout;
pub mod row_navigator;
pub mod selection;
#[cfg(test)]
mod tests;

use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::rc::Rc;
use std::time::Duration;

use teksilo_canvas::{Canvas, Point, Rect, Size, SizeProposal};

use teksilo_core::ObserverHandle;
use teksilo_core::accessibility::{AccessNodeBuilder, widget_id_to_node_id};
use teksilo_core::binding::BindingLevel;
use teksilo_core::build_context::BuildContext;
use teksilo_core::signal::{Prop, Signal};
use teksilo_core::widget::{LayoutContext, PaintContext, Widget, WidgetPlacement};
use teksilo_core::widget_builder::HandlerSet;
use teksilo_core::widget_id::WidgetId;
use teksilo_data::{
    DataChange, DropPosition, DropResponse, ItemKey, KeyedSelectionModel, ListDataSource,
    ListModel, SelectionModel,
};
use teksilo_i18n::LocalizedString;
use teksilo_tokens::{BorderRole, Easing, SurfaceRole};

use crate::styles::recipe_table_style as cp;

use crate::common::row_metrics::{HeightSource, RowMetrics, SharedRowMetrics};
use crate::common::scroll::OverscrollBehavior;
use crate::data_views::{
    DragTransferMode, RowDragData, RowSelection, ViewId, ViewKind, flat_insertion_target,
};
use crate::list_source::DndLazy;
use crate::scroll_area::ScrollBarMode;
use crate::scroll_bar::{ScrollBar, ScrollBarOrientation, ScrollBarVisual};

pub use self::column::{
    Alignment, CellContext, Column, ColumnContext, ColumnResizePolicy, ColumnWidth, EditTriggers,
    GridLines, PinnedSide, TabTraversal, TruncationPolicy,
};
pub use self::selection::{CellSelectionModel, TableSelectionMode};
pub use teksilo_data::SortDirection;

const BUFFER_ROWS: usize = 5;
const SCROLLBAR_THICKNESS: f32 = 12.0;

/// Pane partition produced by [`TableView::display_order`].
///
/// `leading_count` columns sit in the leading-pinned region, the next
/// `middle_end - leading_count` columns sit in the middle (scrollable
/// in future phases) region, and the remainder are trailing-pinned.
/// All counts are positions inside the display-order vector.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(crate) struct PaneBoundaries {
    pub leading_count: usize,
    pub middle_end: usize,
}

impl PaneBoundaries {
    pub(crate) fn new(leading_count: usize, middle_end: usize) -> Self {
        Self {
            leading_count,
            middle_end,
        }
    }
}

/// Drag payload for column reorder. Carried via `DragPayload::typed`.
#[derive(Debug, Clone)]
pub(crate) struct ColumnReorderDragData {
    pub col_id: String,
    /// Stable id of the source TableView, so dropping into a sibling
    /// table is rejected by the on_drop matcher.
    pub source_table_id: usize,
}

// ── Source erasure ─────────────────────────────────────────────────────────

type LenFn = Rc<dyn Fn() -> usize>;
type WithItemFn<T> = Rc<dyn Fn(usize, &dyn Fn(&T))>;
type ObserveFn = Rc<dyn Fn(Box<dyn Fn(&DataChange)>) -> ObserverHandle>;
/// Divergence side-channel for `DataChange::Reset`-emitting proxies
/// (`ListDataSource::first_changed_index`). Raw `ListModel`s report
/// `None` — their observers already get fine-grained variants.
type FirstChangedFn = Rc<dyn Fn() -> Option<usize>>;

/// The multi-cell read erasure. `TableView` reads each row's item once
/// per cell (each column's `cell` delegate), so it keeps the side-effect
/// `with_item_fn` form rather than `ListSource`'s single-widget reader.
/// The DnD + lazy protocol is shared from `DndLazy` (built separately in
/// the constructors). Returned alongside the `Rc<S>` source so the caller
/// can build a `DndLazy` from the same handle without re-wrapping.
fn erase_list_model<T: 'static>(
    model: ListModel<T>,
) -> (LenFn, WithItemFn<T>, ObserveFn, FirstChangedFn) {
    let m_len = model.clone();
    let m_read = model.clone();
    let m_obs = model;
    let len_fn: LenFn = Rc::new(move || m_len.len());
    let with_item_fn: WithItemFn<T> = Rc::new(move |idx, f| {
        m_read.with_item(idx, |item| f(item));
    });
    let observe_fn: ObserveFn =
        Rc::new(move |callback| m_obs.observe_changes(move |change| callback(change)));
    (len_fn, with_item_fn, observe_fn, Rc::new(|| None))
}

fn erase_data_source<S: ListDataSource<Item = T>, T: 'static>(
    s: Rc<S>,
) -> (LenFn, WithItemFn<T>, ObserveFn, FirstChangedFn) {
    let s_len = s.clone();
    let s_read = s.clone();
    let s_obs = s.clone();
    let s_changed = s;
    let len_fn: LenFn = Rc::new(move || s_len.len());
    let with_item_fn: WithItemFn<T> = Rc::new(move |idx, f| {
        s_read.with_item(idx, |item| f(item));
    });
    let observe_fn: ObserveFn =
        Rc::new(move |callback| s_obs.observe_changes(move |change| callback(change)));
    let first_changed_fn: FirstChangedFn = Rc::new(move || s_changed.first_changed_index());
    (len_fn, with_item_fn, observe_fn, first_changed_fn)
}

// `read_item` lived here for the inline body-row build; that loop now
// lives in `BodyPane` which has its own copy. Keeping it removed
// avoids dead-code drift between the two paths.

// ── Public widget ──────────────────────────────────────────────────────────

/// Generic, virtualized, accessible table with sortable / filterable / resizable columns.
///
/// Construct with [`TableView::new`] (from a [`ListModel<T>`](teksilo_data::ListModel))
/// or [`TableView::from_source`] (any [`ListDataSource`]), then chain builder methods
/// to configure columns, row heights, selection, and so on. See module docs for the full
/// feature list and row-height modes.
pub struct TableView<T: 'static> {
    // Source erasure (multi-cell read path; DnD + lazy live in `dnd`).
    len_fn: LenFn,
    with_item_fn: WithItemFn<T>,
    observe_fn: ObserveFn,
    first_changed_fn: FirstChangedFn,
    /// Source-owned DnD validation + lazy windowing, erased from the
    /// backing `ListDataSource`. A `ListModel` reorders in place via its
    /// `accept_drop`; an external source routes the move to its store and
    /// can forbid a drop by returning `DropResponse::Reject` (the view
    /// then paints no insertion line).
    dnd: DndLazy,
    /// Resolve a row index to a movement-proof handle (see `RowAnchor`).
    anchor_fn: Rc<dyn Fn(usize) -> crate::data_views::RowAnchor>,
    /// Anchor for the row with an open cell editor, so the editor follows its
    /// row instead of its index. See `reconcile_editing_row`.
    editing_anchor: Rc<RefCell<Option<crate::data_views::RowAnchor>>>,

    // Configuration
    columns: Vec<Column<T>>,
    row_height: Option<f32>,
    /// Height-mode selection (uniform / exact callback / auto-measure).
    height_source: HeightSource,
    /// Row geometry — shared with `BodyPane` and the keyboard handler.
    row_metrics: SharedRowMetrics,
    header_height: Option<f32>,
    show_header: bool,
    selection_mode: TableSelectionMode,
    /// Row selection — index-based `SelectionModel` or keyed
    /// `KeyedSelectionModel<K>`, unified behind the index-facing facade.
    row_selection: Option<RowSelection>,
    cell_selection: Option<CellSelectionModel>,
    alternating_rows: bool,
    grid_lines: GridLines,
    a11y_label: Option<LocalizedString>,
    show_internal_scrollbars: bool,
    empty_view: Option<Rc<dyn Fn() -> Box<dyn Widget>>>,
    column_resize_policy: ColumnResizePolicy,

    /// Animate wheel scrolling instead of snapping to the new offset.
    /// Enabled by default — mirrors `ScrollArea`. Without it, each wheel
    /// notch jumps by `row_height` per delivered line (typically 3),
    /// which reads as a coarse multi-row jump rather than a smooth glide.
    smooth_scrolling: bool,
    /// Duration of the smooth scroll animation.
    smooth_scroll_duration: Duration,

    /// How the scroll bar is displayed. Defaults to `Permanent` — a
    /// layout sibling that reserves its own width. `Overlay` / `Thin`
    /// float over the content instead, like `ScrollArea`.
    scroll_bar_style: ScrollBarMode,

    // Public reactive signals
    scroll_y: Signal<f32>,
    max_scroll_y: Signal<f32>,
    /// Scroll-chaining behavior at the boundary (default `Chain`).
    overscroll_behavior: OverscrollBehavior,
    viewport_ratio_y: Signal<f32>,
    /// Horizontal scroll offset of the Middle (unpinned) pane — see
    /// `PaneBoundaries`. Leading/Trailing-pinned columns never move; the
    /// Middle pane's content shifts by `-scroll_x`.
    scroll_x: Signal<f32>,
    /// Maximum `scroll_x` — `middle_content_width − middle_viewport_width`.
    max_scroll_x: Signal<f32>,
    /// Middle-pane viewport-to-content width ratio, for the horizontal
    /// scroll bar's thumb.
    viewport_ratio_x: Signal<f32>,
    sort_signal: Signal<Option<(String, SortDirection)>>,
    column_widths_signal: Signal<HashMap<String, f32>>,
    /// Column ids in display order. Empty means "use declaration order".
    column_order_signal: Signal<Vec<String>>,
    /// Per-id override for `Column::pinned`. Missing keys mean "use the
    /// declared pinning". The drag-to-reorder UI updates this when a
    /// column crosses a pane boundary.
    column_pinning_signal: Signal<HashMap<String, PinnedSide>>,
    /// Currently keyboard-focused cell `(row_index, display_col)`, or
    /// `None` when no cell is focused.
    focused_cell: Signal<Option<(usize, usize)>>,
    /// Type-ahead ("type to jump") label extractor — opt-in via
    /// [`type_ahead_label`](Self::type_ahead_label).
    #[allow(clippy::type_complexity)]
    type_ahead_label: Option<Rc<dyn Fn(&T) -> String>>,
    /// Reset window for the type-ahead search term.
    type_ahead_timeout: Duration,
    /// Persistent type-ahead buffer (survives the per-keystroke rebuild).
    type_ahead: Rc<crate::common::type_ahead::TypeAheadState>,
    tab_traversal: TabTraversal,
    /// Cell currently in edit mode, or `None` when no editor is open.
    /// Cell delegates inspect this through `CellContext::is_editing` to
    /// swap in an editor widget.
    editing_cell: Signal<Option<(usize, usize)>>,
    edit_triggers: EditTriggers,
    /// User callback invoked when an edit trigger fires on the focused
    /// cell.
    #[allow(clippy::type_complexity)]
    on_cell_edit_request: Option<Rc<dyn Fn(usize, &str, &mut teksilo_core::widget::EventContext)>>,
    #[allow(clippy::type_complexity)]
    on_cell_edit_dismissed:
        Option<Rc<dyn Fn(usize, &str, &mut teksilo_core::widget::EventContext)>>,
    /// Per-column filter text. Updated by filter affordances in the
    /// header, by `set_filter` / `clear_filters`, and by
    /// downstream consumers binding it (e.g., `SortFilterListModel`).
    filters_signal: Signal<HashMap<String, String>>,
    /// User callback invoked on every row activation (Enter on the
    /// focused row).
    #[allow(clippy::type_complexity)]
    on_row_activate: Option<Rc<dyn Fn(usize, &mut teksilo_core::widget::EventContext)>>,
    reorderable: bool,
    /// Active row-drop insertion indicator `(body_local_y, width)` —
    /// `body_local_y` is measured from the body band top (below the
    /// header). Set by `on_drag_hover` when the source accepts the
    /// hovered position, cleared on leave / drop, read by `paint`.
    /// Reactive (`RepaintOnly`) so a `set(...)` dirties the table.
    drop_feedback: Signal<Option<(f32, f32)>>,

    /// Whether activation is a single or double click (default `DoubleClick`).
    activate_on: crate::data_views::ActivateOn,

    /// `true` while this view — its root or any descendant (e.g. a cell
    /// editor) — holds keyboard focus. Captured at build from
    /// [`BuildContext::view_focus_active`] and bound `RepaintOnly`. Drives
    /// **focus-aware selection**: the selection band paints with the active
    /// `Selected` chrome while focused and the muted `SelectedInactive` chrome
    /// once focus leaves the table — the standard desktop affordance.
    view_focused: Signal<bool>,
    /// Input-modality `:focus-visible` — `true` after keyboard input, `false`
    /// after a pointer press. Gates the cell focus ring so it shows only
    /// during keyboard navigation, never on a mouse click. Bound `RepaintOnly`.
    focus_visible: Signal<bool>,

    // Build state
    header_row_id: Option<WidgetId>,
    body_pane_id: Option<WidgetId>,
    scrollbar_id: Option<WidgetId>,
    /// Horizontal scroll bar along the bottom of the Middle pane only —
    /// built whenever `show_internal_scrollbars` is set, placed/sized (and
    /// hidden at zero size, mirroring the vertical bar) in `place_children`.
    h_scrollbar_id: Option<WidgetId>,
    empty_id: Option<WidgetId>,
    /// Pane-local rebuild trigger + buffered range, owned here so they
    /// survive `TableView` rebuilds (each rebuild constructs a fresh
    /// `BodyPane` struct that inherits these handles).
    pane_version: Signal<u64>,
    pane_built_start: Rc<Cell<usize>>,
    pane_built_end: Rc<Cell<usize>>,
    /// Bumped by the pane when a measure pass changes the content
    /// total; bound at `Relayout` on this root so `max_scroll_y` / the
    /// thumb ratio are recomputed with the corrected total next frame.
    pane_total_refresh: Signal<u64>,

    // Layout state
    /// Resolved widths in **display order** (parallel to
    /// `display_indices`).
    column_widths: Rc<RefCell<Vec<f32>>>,
    /// Display-order indices into `self.columns`. Recomputed each
    /// `build()`; read by `place_children` and `paint`.
    display_indices: Rc<RefCell<Vec<usize>>>,
    /// `(row, display_pos) -> WidgetId` for every cell realized by the
    /// body pane's latest `build()`. Shared with `BodyPane` (the GridView
    /// `tile_map` pattern — two holders across the sibling-of-scrollbar
    /// split): the pane overwrites it wholesale each time it rebuilds, so
    /// a cell that scrolled out of the realized buffer simply isn't in
    /// the map. `accessibility()` reads it to point `active_descendant`
    /// at the keyboard-focused cell's own AT node.
    cell_map: Rc<RefCell<Vec<((usize, usize), WidgetId)>>>,
    /// Counts of (leading-pinned, middle, trailing-pinned) columns —
    /// used by paint to draw pane dividers and by the drop-zone math
    /// to classify a drop position.
    pane_boundaries: Rc<RefCell<PaneBoundaries>>,
    viewport_height: Rc<Cell<f32>>,
    /// Middle-pane viewport width, snapshotted by `place_children` — the
    /// horizontal analogue of `viewport_height`. Read by the keyboard
    /// handler's ensure-column-visible follow.
    middle_viewport_width: Rc<Cell<f32>>,
    /// Set on the first `place_children`. Until then `viewport_height` still
    /// holds its construction placeholder, so viewport-relative imperatives
    /// (`ensure_row_visible`) would scroll against a size that was never real.
    laid_out: Rc<Cell<bool>>,
    /// The row-area's absolute (window) rect (below the header), cached by
    /// `place_children`. Threaded into the keyboard handler so it can chase the
    /// focused row into any *enclosing* scroll area via
    /// [`EventContext::ensure_visible`](teksilo_core::widget::EventContext::ensure_visible).
    body_bounds: Rc<Cell<Rect>>,
    /// Width of the header strip (= the column band) snapshotted by
    /// `place_children`. The reorder-drop handler needs it to mirror the
    /// drop x under RTL, where the column content is right-anchored in
    /// the band (`local.x` is measured from the strip's physical left).
    header_strip_width: Rc<Cell<f32>>,

    // Header-cell shared state — tracked across the table so the
    // pointer-capture'd resize delivers PointerMove events back to the
    // active HeaderCell.
    resize_state: header::ResizeStateHandle,
    /// Display slot of the column under an active resize drag, or `None`.
    /// Shared with every `HeaderCell` so the *target* column shows the
    /// "resizing" chrome — which is not always the cell holding the pointer
    /// capture, since a grip straddles the divider between two cells.
    resize_target: Signal<Option<usize>>,
    /// Window x of the prospective divider while a
    /// [`ColumnResizePolicy::OnRelease`] drag is in flight. Painted as a
    /// guide line by `paint`; `None` at rest. Under `Live` the columns
    /// themselves move, so nothing is published here.
    resize_preview_x: Signal<Option<f32>>,

    /// Stable id used by the column-reorder drag payload to disambiguate
    /// inter-table drops. Unrelated to row DnD — a wholly separate
    /// mechanism (`ColumnReorderDragData` + header handlers).
    table_id: usize,

    /// Stable, kind-tagged ID for this TableView instance's **row** DnD
    /// (identifies its own row reorder vs. a foreign row drop, even across
    /// widget kinds / windows). Distinct from `table_id` above, which only
    /// disambiguates the separate column-reorder mechanism.
    model_id: ViewId,

    /// Cross-widget export / foreign-receive machinery — the builders
    /// (`.exportable`, `.export_external`, `.accept_foreign_rows`,
    /// `.on_rows_received`, `.on_rows_transferred_out`), the drag-start payload
    /// build, and the move-out completion, shared by all four data views.
    export: crate::data_views::RowExport<T>,

    /// Whole-view enabled state, statically or reactively. Forwarded to the
    /// arena via `ctx.enabled_when(self_id, self.enabled.clone())` at build
    /// time; a disabled view greys out and stops accepting focus /
    /// selection / keyboard input (arena-gated).
    enabled: Prop<bool>,
}

/// Build the anchor factory for a keyed source: capture the row's key now,
/// resolve its current index later. Keyless sources fall back to a fixed anchor.
fn anchor_factory<S: ListDataSource<Item = T> + 'static, T: 'static>(
    s: Rc<S>,
) -> Rc<dyn Fn(usize) -> crate::data_views::RowAnchor> {
    Rc::new(move |index| match s.key_at(index) {
        Some(key) => {
            let src = s.clone();
            crate::data_views::RowAnchor::new(Rc::new(move || {
                if src.key_at(index).as_ref() == Some(&key) {
                    return Some(index);
                }
                src.index_of(&key)
            }))
        }
        None => crate::data_views::RowAnchor::fixed(index),
    })
}

impl<T: 'static> TableView<T> {
    /// Wrap a `ListModel<T>`.
    pub fn new(model: ListModel<T>) -> Self {
        let dnd = DndLazy::from_source(Rc::new(model.clone()));
        let (len_fn, with_item_fn, observe_fn, first_changed_fn) = erase_list_model(model);
        // A bare `ListModel` exposes no row identity.
        let anchor_fn = Rc::new(crate::data_views::RowAnchor::fixed) as Rc<dyn Fn(usize) -> _>;
        Self::create(
            len_fn,
            with_item_fn,
            observe_fn,
            first_changed_fn,
            dnd,
            anchor_fn,
        )
    }

    /// Wrap any `ListDataSource<Item = T>` (e.g. a
    /// [`SortFilterListModel<T>`](teksilo_data::SortFilterListModel)).
    ///
    /// The source owns DnD validation (`can_accept` / `accept_drop`) and
    /// lazy windowing (`row_state` / `request_window` / `fetch_more`); a
    /// read-only source leaves the defaults inert.
    pub fn from_source<S: ListDataSource<Item = T>>(source: S) -> Self {
        let s = Rc::new(source);
        let dnd = DndLazy::from_source(s.clone());
        let anchor_fn = anchor_factory::<S, T>(s.clone());
        let (len_fn, with_item_fn, observe_fn, first_changed_fn) = erase_data_source::<S, T>(s);
        Self::create(
            len_fn,
            with_item_fn,
            observe_fn,
            first_changed_fn,
            dnd,
            anchor_fn,
        )
    }

    /// Wrap any `ListDataSource<Item = T>` with **keyed** row selection. The
    /// `KeyedSelectionModel<S::Key>` tracks selection by source identity, so it
    /// survives reorders / filters / lazy window-slides and stays consistent
    /// across two views of the same source. The view stays `TableView<T>` — the
    /// index↔key mapping is captured from the concrete source here. Equivalent
    /// to `from_source(..)` plus an identity-based replacement for
    /// [`selection`](Self::selection).
    pub fn from_source_keyed<S: ListDataSource<Item = T>>(
        source: S,
        keyed: KeyedSelectionModel<S::Key>,
    ) -> Self
    where
        S::Key: ItemKey,
    {
        let s = Rc::new(source);
        let dnd = DndLazy::from_source(s.clone());
        let key_at = {
            let s = s.clone();
            Rc::new(move |i| s.key_at(i)) as Rc<dyn Fn(usize) -> Option<S::Key>>
        };
        let len = {
            let s = s.clone();
            Rc::new(move || s.len()) as Rc<dyn Fn() -> usize>
        };
        let contains = {
            let s = s.clone();
            Rc::new(move |k: &S::Key| (0..s.len()).any(|i| s.key_at(i).as_ref() == Some(k)))
                as Rc<dyn Fn(&S::Key) -> bool>
        };
        let row_selection = RowSelection::from_keyed(keyed, key_at, len, contains);
        let anchor_fn = anchor_factory::<S, T>(s.clone());
        let (len_fn, with_item_fn, observe_fn, first_changed_fn) = erase_data_source::<S, T>(s);
        let mut view = Self::create(
            len_fn,
            with_item_fn,
            observe_fn,
            first_changed_fn,
            dnd,
            anchor_fn,
        );
        view.row_selection = Some(row_selection);
        view
    }

    fn create(
        len_fn: LenFn,
        with_item_fn: WithItemFn<T>,
        observe_fn: ObserveFn,
        first_changed_fn: FirstChangedFn,
        dnd: DndLazy,
        anchor_fn: Rc<dyn Fn(usize) -> crate::data_views::RowAnchor>,
    ) -> Self {
        use std::sync::atomic::{AtomicUsize, Ordering};
        static NEXT_ID: AtomicUsize = AtomicUsize::new(1);
        let table_id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
        Self {
            len_fn,
            with_item_fn,
            observe_fn,
            first_changed_fn,
            dnd,
            anchor_fn,
            editing_anchor: Rc::new(RefCell::new(None)),
            columns: Vec::new(),
            row_height: None,
            height_source: HeightSource::Uniform,
            row_metrics: Rc::new(RefCell::new(RowMetrics::uniform(cp::ROW_HEIGHT, 0.0))),
            header_height: None,
            show_header: true,
            selection_mode: TableSelectionMode::default(),
            row_selection: None,
            cell_selection: None,
            alternating_rows: false,
            grid_lines: GridLines::None,
            a11y_label: None,
            show_internal_scrollbars: true,
            empty_view: None,
            column_resize_policy: ColumnResizePolicy::default(),
            smooth_scrolling: true,
            smooth_scroll_duration: Duration::from_millis(150),
            scroll_bar_style: ScrollBarMode::Permanent,
            overscroll_behavior: OverscrollBehavior::default(),
            scroll_y: Signal::new_animated(0.0),
            max_scroll_y: Signal::new(0.0),
            viewport_ratio_y: Signal::new(1.0),
            scroll_x: Signal::new_animated(0.0),
            max_scroll_x: Signal::new(0.0),
            viewport_ratio_x: Signal::new(1.0),
            sort_signal: Signal::new(None),
            column_widths_signal: Signal::new(HashMap::new()),
            column_order_signal: Signal::new(Vec::new()),
            column_pinning_signal: Signal::new(HashMap::new()),
            focused_cell: Signal::new(None),
            type_ahead_label: None,
            type_ahead_timeout: crate::common::type_ahead::DEFAULT_TYPE_AHEAD_TIMEOUT,
            type_ahead: crate::common::type_ahead::TypeAheadState::new(),
            // Replaced at build with the live tree signals; the defaults are
            // only the pre-build values (treat as focused, pointer modality).
            view_focused: Signal::new(true),
            focus_visible: Signal::new(false),
            tab_traversal: TabTraversal::default(),
            editing_cell: Signal::new(None),
            edit_triggers: EditTriggers::default(),
            on_cell_edit_request: None,
            on_cell_edit_dismissed: None,
            filters_signal: Signal::new(HashMap::new()),
            on_row_activate: None,
            reorderable: false,
            drop_feedback: Signal::new(None),
            activate_on: crate::data_views::ActivateOn::default(),
            header_row_id: None,
            body_pane_id: None,
            scrollbar_id: None,
            h_scrollbar_id: None,
            empty_id: None,
            pane_version: Signal::new(0_u64),
            pane_built_start: Rc::new(Cell::new(0)),
            pane_built_end: Rc::new(Cell::new(0)),
            pane_total_refresh: Signal::new(0_u64),
            column_widths: Rc::new(RefCell::new(Vec::new())),
            display_indices: Rc::new(RefCell::new(Vec::new())),
            cell_map: Rc::new(RefCell::new(Vec::new())),
            pane_boundaries: Rc::new(RefCell::new(PaneBoundaries::default())),
            viewport_height: Rc::new(Cell::new(600.0)),
            middle_viewport_width: Rc::new(Cell::new(600.0)),
            laid_out: Rc::new(Cell::new(false)),
            body_bounds: Rc::new(Cell::new(Rect::ZERO)),
            header_strip_width: Rc::new(Cell::new(0.0)),
            resize_state: Rc::new(std::cell::RefCell::new(None)),
            resize_target: Signal::new(None),
            resize_preview_x: Signal::new(None),
            table_id,
            model_id: ViewId::next(ViewKind::Table),
            export: crate::data_views::RowExport::default(),
            enabled: Prop::Static(true),
        }
    }

    // ── Builder ────────────────────────────────────────────────────────

    /// Enable or disable the whole view. A disabled view greys out and stops
    /// accepting focus / selection / keyboard input (arena-gated).
    pub fn enabled(mut self, enabled: impl Into<Prop<bool>>) -> Self {
        self.enabled = enabled.into();
        self
    }

    /// Set the scroll-chaining behavior at the boundary (default
    /// [`OverscrollBehavior::Chain`]; [`Contain`](OverscrollBehavior::Contain)
    /// disables chaining to an ancestor scrollable).
    pub fn overscroll_behavior(mut self, behavior: OverscrollBehavior) -> Self {
        self.overscroll_behavior = behavior;
        self
    }

    /// Enable or disable animated wheel scrolling (enabled by default).
    /// When disabled, wheel events snap immediately to the new offset.
    pub fn smooth_scrolling(mut self, enabled: bool) -> Self {
        self.smooth_scrolling = enabled;
        self
    }

    /// Enable **type-ahead** ("type to jump"): typing a printable character
    /// while the table has keyboard focus jumps the focused row to the next
    /// row whose label starts with the accumulated search term, wrapping
    /// around (Qt `keyboardSearch` / macOS & Windows type-select).
    /// `label(&item)` yields the searchable text for a row; matching is
    /// ASCII-case-insensitive. A pause longer than the
    /// [`type_ahead_timeout`](Self::type_ahead_timeout) starts a fresh term.
    ///
    /// On an editable column whose [`EditTriggers`] is type-to-edit, typing
    /// starts an edit instead — type-ahead applies on non-editable columns
    /// (or when no type-to-edit trigger is configured).
    pub fn type_ahead_label(mut self, label: impl Fn(&T) -> String + 'static) -> Self {
        self.type_ahead_label = Some(Rc::new(label));
        self
    }

    /// Reset window between keystrokes before the type-ahead search term
    /// clears (default 500 ms). A zero duration disables type-ahead.
    pub fn type_ahead_timeout(mut self, timeout: Duration) -> Self {
        self.type_ahead_timeout = timeout;
        self
    }

    /// Duration of the smooth scroll animation (default 150 ms).
    pub fn smooth_scroll_duration(mut self, duration: Duration) -> Self {
        self.smooth_scroll_duration = duration;
        self
    }

    /// How the scroll bar is displayed (default `Permanent`). `Overlay`
    /// and `Thin` float the bar over the content instead of reserving a
    /// layout column for it, mirroring `ScrollArea::scroll_bar_style`.
    pub fn scroll_bar_style(mut self, style: ScrollBarMode) -> Self {
        self.scroll_bar_style = style;
        self
    }

    /// Append a single [`Column<T>`] definition to the table.
    pub fn add_column(mut self, col: Column<T>) -> Self {
        self.columns.push(col);
        self
    }

    /// Append multiple [`Column<T>`] definitions from an iterator.
    pub fn columns(mut self, cols: impl IntoIterator<Item = Column<T>>) -> Self {
        self.columns.extend(cols);
        self
    }

    /// Re-materialize `self.row_metrics` after a height-mode /
    /// row-height builder call.
    fn remake_metrics(&self) {
        *self.row_metrics.borrow_mut() = self
            .height_source
            .make_metrics(self.effective_row_height(), 0.0);
    }

    /// Fixed row height (default: the table style's 28 px) — the
    /// uniform fast path. Mutually exclusive with
    /// [`row_height_fn`](Self::row_height_fn) and
    /// [`auto_row_height`](Self::auto_row_height); the last mode setter
    /// wins.
    pub fn row_height(mut self, height: f32) -> Self {
        self.row_height = Some(height);
        self.height_source = HeightSource::Uniform;
        self.remake_metrics();
        self
    }

    /// Per-row heights from a callback over the visible row index. The
    /// callback must be pure (same index + same data → same height); it
    /// is re-swept from the first changed index on every model change
    /// (a `SortFilterListModel` source reports that index through
    /// `first_changed_index`, so sort/filter/append keep the valid
    /// prefix). No measurement pass runs.
    pub fn row_height_fn(mut self, f: impl Fn(usize) -> f32 + 'static) -> Self {
        self.height_source = HeightSource::Exact(Rc::new(f));
        self.remake_metrics();
        self
    }

    /// Auto-measured row heights: each realized row reports the height
    /// of its tallest cell measured at the cell's column width
    /// (height-for-width), unrealized rows assume `estimated`. Scroll
    /// anchoring keeps content above the viewport stationary as
    /// estimates are corrected; the scrollbar settles one frame after a
    /// measurement change.
    pub fn auto_row_height(mut self, estimated: f32) -> Self {
        self.height_source = HeightSource::Auto { estimated };
        self.remake_metrics();
        self
    }

    /// Override the column header row height in logical pixels. Default: the table style's `HEADER_HEIGHT`.
    pub fn header_height(mut self, height: f32) -> Self {
        self.header_height = Some(height);
        self
    }

    /// Show or hide the column header row. Default: visible.
    pub fn show_header(mut self, visible: bool) -> Self {
        self.show_header = visible;
        self
    }

    /// Set how column widths are redistributed when columns are
    /// added, resized, or the table's own width changes. See
    /// [`ColumnResizePolicy`].
    pub fn column_resize_policy(mut self, policy: ColumnResizePolicy) -> Self {
        self.column_resize_policy = policy;
        self
    }

    /// Control how Tab / Shift+Tab navigate between cells. See
    /// [`TabTraversal`].
    pub fn tab_traversal(mut self, mode: TabTraversal) -> Self {
        self.tab_traversal = mode;
        self
    }

    /// Set which user action opens a cell editor. See [`EditTriggers`].
    pub fn edit_triggers(mut self, trigger: EditTriggers) -> Self {
        self.edit_triggers = trigger;
        self
    }

    /// Hook fired by the keyboard handler when an edit trigger fires
    /// on the focused cell. Receives `(row_index, col_id, ctx)`.
    pub fn on_cell_edit_request(
        mut self,
        f: impl Fn(usize, &str, &mut teksilo_core::widget::EventContext) + 'static,
    ) -> Self {
        self.on_cell_edit_request = Some(Rc::new(f));
        self
    }

    /// Callback invoked when an **open** cell editor should end because the
    /// pointer went somewhere else: a press that lands on any cell other than
    /// the one being edited. Receives the editing cell's flat row index and
    /// column id, so the owner can commit (or discard) whatever is in its
    /// buffer, then clear its own editing state.
    ///
    /// The counterpart of [`on_cell_edit_request`](Self::on_cell_edit_request),
    /// and the view cannot do it alone: the framework owns *which* cell is being
    /// edited, but only the owner knows what an ended edit means — commit,
    /// discard, or refuse a value that will not parse.
    ///
    /// **Why a press and not a focus change.** "The editor lost focus" is the
    /// obvious signal and it cannot be used: a body pane rebuilds constantly —
    /// selection, filtering, scroll, a reload from elsewhere — and every rebuild
    /// destroys and re-creates the open editor, so focus leaves it many times
    /// during an edit the writer never interrupted. A press on another cell is
    /// unambiguous and happens exactly once.
    pub fn on_cell_edit_dismissed(
        mut self,
        f: impl Fn(usize, &str, &mut teksilo_core::widget::EventContext) + 'static,
    ) -> Self {
        self.on_cell_edit_dismissed = Some(Rc::new(f));
        self
    }

    /// Hook fired when the user presses Enter on the focused row.
    pub fn on_row_activate(
        mut self,
        f: impl Fn(usize, &mut teksilo_core::widget::EventContext) + 'static,
    ) -> Self {
        self.on_row_activate = Some(Rc::new(f));
        self
    }

    /// Enable drag-to-reorder of **rows** (pointer drag + keyboard
    /// Alt+ArrowUp/Down). Distinct from
    /// [`Column::reorderable`](crate::Column::reorderable), which reorders
    /// *columns* and defaults to `true`; this defaults to `false`.
    ///
    /// The move is routed through the backing source's `accept_drop`: a
    /// `ListModel` reorders in place, an external source routes the move to
    /// its store. Per-hover the source's `can_accept` decides whether the
    /// drop is allowed — a forbidden position shows no insertion line and
    /// the drop is refused. A row may also be forbidden from dragging at
    /// all (the source's `drag` gate). Cross-table / external drops arrive
    /// at `accept_drop` as `DragSource::Foreign`; a bare `ListModel`
    /// rejects them, an external source decides.
    pub fn reorderable(mut self, enabled: bool) -> Self {
        self.reorderable = enabled;
        self
    }

    /// Renamed to [`reorderable`](Self::reorderable), matching `ListView`,
    /// `GridView`, `TreeView` and `TreeTableView` — this was the only view in
    /// the family spelling it differently.
    #[deprecated(since = "0.6.3", note = "renamed to `reorderable`")]
    pub fn reorderable_rows(self, enabled: bool) -> Self {
        self.reorderable(enabled)
    }

    /// Make rows **droppable outside this view** — on a
    /// [`DropTarget`](crate::DropTarget), another data view, or the OS.
    ///
    /// A dragged row (or the whole selection, when the pressed row is part of a
    /// multi-selection) carries clones of its items in a public
    /// [`RowDragData<T>`](crate::RowDragData), so a foreign receiver can pull
    /// them out with `payload.get_typed::<RowDragData<T>>()` /
    /// `DropTarget::on_drop_typed::<RowDragData<T>>()` — no serialization. This
    /// also makes rows a drag source even without [`reorderable`](Self::reorderable).
    ///
    /// `mode` chooses what happens to the origin rows once a *foreign* target
    /// accepts them: [`DragTransferMode::Move`] removes them (via the source's
    /// `on_drag_out`, or [`on_rows_transferred_out`](Self::on_rows_transferred_out)),
    /// [`DragTransferMode::Copy`] leaves them. A same-view reorder is never a
    /// transfer, so `mode` never affects it. Requires `T: Clone`.
    pub fn exportable(mut self, mode: DragTransferMode) -> Self
    where
        T: Clone,
    {
        self.export.set_exportable(mode);
        self
    }

    /// Additionally advertise the dragged rows as MIME data so they can be
    /// dropped on a [`DropZone`](crate::DropZone) or exported to another
    /// application / window via the OS. `f` maps the dragged items to
    /// `(mime_type, bytes)` pairs (e.g. `text/plain`, `text/uri-list`, an
    /// app-specific `application/x-…`). Implies [`exportable`](Self::exportable)
    /// (defaulting to [`DragTransferMode::Move`] if not already set). Requires
    /// `T: Clone`.
    pub fn export_external(mut self, f: impl Fn(&[T]) -> Vec<(String, Vec<u8>)> + 'static) -> Self
    where
        T: Clone,
    {
        self.export.set_export_external(f);
        self
    }

    /// Override how rows moved out to a foreign target are removed from this
    /// view. Receives the dragged rows' indices (descending-safe) and the live
    /// context. Without this, an [`exportable`](Self::exportable)
    /// [`Move`](DragTransferMode::Move) drag removes them through the source's
    /// `on_drag_out` (works out of the box for a `ListModel`).
    pub fn on_rows_transferred_out(
        mut self,
        f: impl Fn(&[usize], &mut teksilo_core::widget::EventContext) + 'static,
    ) -> Self {
        self.export.set_on_rows_transferred_out(f);
        self
    }

    /// Accept exported rows dropped from a **different** view or source without
    /// writing a custom `ListDataSource`. Pair with
    /// [`on_rows_received`](Self::on_rows_received), which is handed the dropped
    /// items and the insertion index. (Same-view reorder is
    /// [`reorderable`](Self::reorderable); a custom `ListDataSource` can still
    /// accept foreign drops through its `can_accept`/`accept_drop` instead.)
    pub fn accept_foreign_rows(mut self, accept: bool) -> Self {
        self.export.accept_foreign_rows = accept;
        self
    }

    /// Handler for rows accepted via [`accept_foreign_rows`](Self::accept_foreign_rows):
    /// `(items, insertion_index, ctx)`. Insert them into your model at the
    /// index.
    pub fn on_rows_received(
        mut self,
        f: impl Fn(Vec<T>, usize, &mut teksilo_core::widget::EventContext) + 'static,
    ) -> Self {
        self.export.set_on_rows_received(f);
        self
    }

    /// Choose single- vs double-click activation for `on_row_activate` (default
    /// [`ActivateOn::DoubleClick`](crate::ActivateOn)). Enter/Space activates in
    /// either mode.
    pub fn activate_on(mut self, mode: crate::data_views::ActivateOn) -> Self {
        self.activate_on = mode;
        self
    }

    /// Choose the row-selection granularity (None / Single / Multi).
    /// See [`TableSelectionMode`].
    pub fn selection_mode(mut self, mode: TableSelectionMode) -> Self {
        self.selection_mode = mode;
        self
    }

    /// Set the index-based row selection model (positions). For identity-based
    /// selection that survives reorder / filter / window-slide, build the view
    /// with [`from_source_keyed`](Self::from_source_keyed) instead.
    pub fn selection(mut self, sel: SelectionModel) -> Self {
        self.row_selection = Some(RowSelection::from_index(sel));
        self
    }

    /// Install an independent cell-selection model on top of row selection.
    /// See [`CellSelectionModel`].
    pub fn cell_selection(mut self, sel: CellSelectionModel) -> Self {
        self.cell_selection = Some(sel);
        self
    }

    /// Paint every other row with a tinted background. Default: off.
    pub fn alternating_rows(mut self, enabled: bool) -> Self {
        self.alternating_rows = enabled;
        self
    }

    /// Draw horizontal and/or vertical grid lines between cells.
    /// See [`GridLines`].
    pub fn grid_lines(mut self, kind: GridLines) -> Self {
        self.grid_lines = kind;
        self
    }

    /// Provide an accessible label for the table (`aria-label`). Required
    /// when the page hosts more than one table so screen readers can
    /// distinguish them.
    pub fn a11y_label(mut self, label: impl Into<LocalizedString>) -> Self {
        self.a11y_label = Some(label.into());
        self
    }

    /// Show or hide the built-in vertical scroll bar. Default: visible. Set to
    /// `false` when an external scroll bar is wired to [`scroll_y_signal`](Self::scroll_y_signal).
    pub fn show_internal_scrollbars(mut self, show: bool) -> Self {
        self.show_internal_scrollbars = show;
        self
    }

    /// Widget shown when the source is empty.
    pub fn empty_view(mut self, f: impl Fn() -> Box<dyn Widget> + 'static) -> Self {
        self.empty_view = Some(Rc::new(f));
        self
    }

    // ── Public reactive signals ────────────────────────────────────────

    /// Current vertical scroll offset in logical pixels.
    pub fn scroll_y_signal(&self) -> &Signal<f32> {
        &self.scroll_y
    }

    /// Maximum vertical scroll offset — `total_content_height − viewport_height`.
    pub fn max_scroll_y_signal(&self) -> &Signal<f32> {
        &self.max_scroll_y
    }

    /// Viewport-to-content height ratio, used by external scroll bar thumbs.
    pub fn viewport_ratio_y_signal(&self) -> &Signal<f32> {
        &self.viewport_ratio_y
    }

    /// Current horizontal scroll offset of the Middle (unpinned) pane, in
    /// logical pixels. Leading/Trailing-pinned columns are unaffected —
    /// see [`Column::pinned`].
    pub fn scroll_x_signal(&self) -> &Signal<f32> {
        &self.scroll_x
    }

    /// Maximum horizontal scroll offset — `middle_content_width −
    /// middle_viewport_width`.
    pub fn max_scroll_x_signal(&self) -> &Signal<f32> {
        &self.max_scroll_x
    }

    /// Middle-pane viewport-to-content width ratio, used by external
    /// horizontal scroll bar thumbs.
    pub fn viewport_ratio_x_signal(&self) -> &Signal<f32> {
        &self.viewport_ratio_x
    }

    /// Active sort: `Some((col_id, dir))` or `None` when unsorted.
    /// Mutated by header clicks (cycle: None → Asc → Desc → None) and by
    /// [`set_sort`](Self::set_sort) / [`clear_sort`](Self::clear_sort).
    /// Bind a [`SortFilterListModel`](teksilo_data::SortFilterListModel) to
    /// drive a re-sort of the underlying data:
    ///
    /// ```ignore
    /// let proxy = SortFilterListModel::new(model)
    ///     .with_comparator("name", |a, b| a.name.cmp(&b.name));
    /// proxy.sort_signal(table.sort_signal().clone());
    /// ```
    pub fn sort_signal(&self) -> &Signal<Option<(String, SortDirection)>> {
        &self.sort_signal
    }

    /// Map of column id → user-overridden width. A column id appears in
    /// this map only after the user resizes that column; missing keys
    /// mean "use the declared width policy".
    pub fn column_widths_signal(&self) -> &Signal<HashMap<String, f32>> {
        &self.column_widths_signal
    }

    /// Column ids in display order. Updated when the user drags a
    /// header to reorder, or imperatively via
    /// [`set_column_order`](Self::set_column_order). When empty, the
    /// declared order applies. Pinned-side groups (Leading / None /
    /// Trailing) are *always* honored — the entries inside this signal
    /// only re-sort within each group.
    pub fn column_order_signal(&self) -> &Signal<Vec<String>> {
        &self.column_order_signal
    }

    /// Per-id pinning override map. A key here pins the column to that
    /// side; missing keys fall back to the declared `Column::pinned`.
    /// Updated when the user drags a column across a pane boundary.
    pub fn column_pinning_signal(&self) -> &Signal<HashMap<String, PinnedSide>> {
        &self.column_pinning_signal
    }

    /// Currently keyboard-focused cell, as `(row_index, display_col)`,
    /// or `None` when no cell is focused. Mutated by the keyboard
    /// handler (Arrow keys / Tab / Home / End / PgUp / PgDn /
    /// Ctrl-Home / Ctrl-End / Escape) and by direct
    /// [`set_focused_cell`](Self::set_focused_cell) /
    /// [`clear_focused_cell`](Self::clear_focused_cell) calls.
    pub fn focused_cell_signal(&self) -> &Signal<Option<(usize, usize)>> {
        &self.focused_cell
    }

    /// Move the focused cell. Out-of-range values are silently clamped
    /// when the next layout runs.
    pub fn set_focused_cell(&self, row: usize, col: usize) {
        self.focused_cell.set(Some((row, col)));
    }

    /// Remove keyboard focus from any cell (equivalent to pressing Escape).
    pub fn clear_focused_cell(&self) {
        self.focused_cell.set(None);
    }

    /// Cell currently in edit mode, or `None` when no editor is open.
    /// Cell delegates inspect this via `CellContext::is_editing` and
    /// swap in an editor widget when matched.
    pub fn editing_cell_signal(&self) -> &Signal<Option<(usize, usize)>> {
        &self.editing_cell
    }

    /// Begin editing the cell `(row, col_id)`. Silently no-ops if `col_id`
    /// isn't a currently-displayed column, or if `row` is outside the visible
    /// range — an out-of-range target would otherwise strand `editing_cell` on
    /// a row nothing can match.
    ///
    /// Callable **before the view is mounted**, which is the only point at
    /// which a consumer can seed a freshly constructed view with an edit
    /// target it already holds. `display_indices` is a cache `build()` fills,
    /// so a pre-mount call finds it empty; the order is recomputed on demand
    /// in that case rather than resolving against nothing and no-opping for a
    /// third, undocumented reason.
    pub fn begin_edit(&self, row: usize, col_id: &str) {
        let cached = self.display_indices.borrow();
        let recomputed;
        let display: &[usize] = if cached.is_empty() {
            recomputed = self.display_order();
            &recomputed
        } else {
            &cached
        };
        if let Some(target) =
            imperative::resolve_edit_target(row, col_id, &self.columns, display, (self.len_fn)())
        {
            drop(cached);
            self.editing_cell.set(Some(target));
        }
    }

    /// Close the active cell editor without committing (the field's `on_blur` still fires).
    pub fn end_edit(&self) {
        self.editing_cell.set(None);
    }

    /// Per-column filter text. Updated by filter affordances in
    /// header cells and by
    /// [`set_filter`](Self::set_filter) / [`clear_filters`](Self::clear_filters).
    /// Bind a `SortFilterListModel<T>` to drive the upstream data:
    ///
    /// ```ignore
    /// let proxy = SortFilterListModel::new(model)
    ///     .with_predicate("name", |t| {
    ///         let needle = t.to_string();
    ///         Box::new(move |r: &Row| r.name.contains(&needle))
    ///     });
    /// proxy.filters_signal(table.filters_signal().clone());
    /// ```
    pub fn filters_signal(&self) -> &Signal<HashMap<String, String>> {
        &self.filters_signal
    }

    /// Set or clear the filter text for a single column. An empty `text` removes
    /// the entry for `col_id` (same as clearing the filter for that column).
    pub fn set_filter(&self, col_id: &str, text: &str) {
        imperative::set_filter(&self.filters_signal, col_id, text);
    }

    /// Remove all active column filters.
    pub fn clear_filters(&self) {
        imperative::set_if_changed(&self.filters_signal, HashMap::new());
    }

    // ── Imperative API ─────────────────────────────────────────────────

    /// Scroll so that `row` is aligned to the top of the viewport. A no-op
    /// before the first layout pass.
    pub fn scroll_to_row(&self, row: usize) {
        imperative::scroll_to_row(row, &self.row_metrics, &self.scroll_y, &self.max_scroll_y);
    }

    /// Set the active sort imperatively. Equivalent to writing to
    /// [`sort_signal`](Self::sort_signal) directly, except that an unchanged
    /// value neither writes nor notifies — see
    /// [`set_column_widths`](Self::set_column_widths).
    pub fn set_sort(&self, col_id: Option<&str>, dir: SortDirection) {
        let next = col_id.map(|c| (c.to_string(), dir));
        imperative::set_if_changed(&self.sort_signal, next);
    }

    /// Clear the active sort.
    pub fn clear_sort(&self) {
        imperative::set_if_changed(&self.sort_signal, None);
    }

    /// Set or remove a single column's user-resized width override.
    /// A non-positive `width` removes the entry (the column reverts to
    /// its declared width policy).
    pub fn set_column_width(&self, col_id: &str, width: f32) {
        imperative::set_column_width(&self.column_widths_signal, col_id, width);
    }

    /// Replace the full width-override map (typically used to restore
    /// a persisted layout).
    ///
    /// A no-op when the map is unchanged, so the documented
    /// settings-round-trip wiring (see docs/table-view.md, "Persistence")
    /// terminates instead of recursing: `Signal::set` has no equality check of
    /// its own, and a live resize writes a width on every pointer move.
    pub fn set_column_widths(&self, widths: HashMap<String, f32>) {
        imperative::set_column_widths(&self.column_widths_signal, widths);
    }

    /// Replace the column-order list. Ids not declared on this table
    /// are silently dropped on the next layout pass.
    pub fn set_column_order(&self, order: Vec<String>) {
        imperative::set_if_changed(&self.column_order_signal, order);
    }

    /// Pin or unpin a single column.
    pub fn set_column_pinning(&self, col_id: &str, side: PinnedSide) {
        imperative::set_column_pinning(&self.column_pinning_signal, col_id, side);
    }

    /// Effective pinning for a column — `column_pinning_signal` wins
    /// over the declared `Column::pinned`.
    fn effective_pinning(&self, col: &Column<T>) -> PinnedSide {
        self.column_pinning_signal
            .get()
            .get(&col.id)
            .copied()
            .unwrap_or(col.pinned)
    }

    /// Compute the visible column display order: a flat list of indices
    /// into `self.columns`. Columns are partitioned by effective
    /// pinning (Leading first, then None, then Trailing); within each
    /// pane they appear in `column_order_signal` order, with any
    /// columns missing from the signal appended in declaration order.
    fn display_order(&self) -> Vec<usize> {
        let order_signal = self.column_order_signal.get();
        let mut order_map: HashMap<&str, usize> = HashMap::new();
        for (i, id) in order_signal.iter().enumerate() {
            order_map.insert(id.as_str(), i);
        }
        let mut leading: Vec<usize> = Vec::new();
        let mut middle: Vec<usize> = Vec::new();
        let mut trailing: Vec<usize> = Vec::new();
        for (i, col) in self.columns.iter().enumerate() {
            match self.effective_pinning(col) {
                PinnedSide::Leading => leading.push(i),
                PinnedSide::None => middle.push(i),
                PinnedSide::Trailing => trailing.push(i),
            }
        }
        // Sort key: explicit `column_order_signal` positions win (low
        // values); columns missing from the signal fall back to their
        // declaration index, offset by a huge constant so they always
        // sort after any explicitly-ordered column.
        const FALLBACK_BASE: usize = usize::MAX / 2;
        let sort_pane = |bucket: &mut Vec<usize>, cols: &[Column<T>]| {
            bucket.sort_by_key(|&i| {
                order_map
                    .get(cols[i].id.as_str())
                    .copied()
                    .unwrap_or(FALLBACK_BASE + i)
            });
        };
        sort_pane(&mut leading, &self.columns);
        sort_pane(&mut middle, &self.columns);
        sort_pane(&mut trailing, &self.columns);
        let mut out = Vec::with_capacity(leading.len() + middle.len() + trailing.len());
        out.extend(leading);
        let leading_count = out.len();
        out.extend(middle);
        let middle_end = out.len();
        out.extend(trailing);
        // Stash the boundaries so paint / drop-zone math can read them.
        *self.pane_boundaries.borrow_mut() = PaneBoundaries::new(leading_count, middle_end);
        out
    }

    /// Scroll the minimum distance needed to make `row` visible. A no-op
    /// before the first layout pass, when the viewport height is not yet known.
    pub fn ensure_row_visible(&self, row: usize) {
        imperative::ensure_row_visible(
            row,
            &self.row_metrics,
            &self.scroll_y,
            &self.max_scroll_y,
            self.viewport_height.get(),
            self.laid_out.get(),
        );
    }

    // ── Internals ──────────────────────────────────────────────────────

    /// The configured row height (override) or the table style's 28 px
    /// fallback. In the non-uniform modes this is the seed estimate;
    /// real geometry lives in `row_metrics`.
    fn effective_row_height(&self) -> f32 {
        self.row_height.unwrap_or(cp::ROW_HEIGHT)
    }

    fn effective_header_height(&self) -> f32 {
        if !self.show_header {
            0.0
        } else {
            self.header_height.unwrap_or(cp::HEADER_HEIGHT)
        }
    }

    fn total_content_height(&self) -> f32 {
        self.row_metrics.borrow_mut().total_height((self.len_fn)())
    }

    fn visible_range(&self) -> (usize, usize) {
        self.row_metrics.borrow_mut().visible_range(
            self.scroll_y.get(),
            self.viewport_height.get(),
            (self.len_fn)(),
            BUFFER_ROWS,
        )
    }

    fn clamp_scroll(&self) {
        let max = self.max_scroll_y.get();
        let current = self.scroll_y.get();
        let clamped = current.clamp(0.0, max);
        if (clamped - current).abs() > 0.001 {
            self.scroll_y.set(clamped);
        }
    }
}

impl<T: 'static> std::fmt::Debug for TableView<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TableView")
            .field("rows", &(self.len_fn)())
            .field("columns", &self.columns.len())
            .field("scroll_y", &self.scroll_y.get())
            .field("selection_mode", &self.selection_mode)
            .field("scroll_bar_style", &self.scroll_bar_style)
            .finish()
    }
}

impl<T: 'static> Widget for TableView<T> {
    fn build(&mut self, ctx: &mut BuildContext) -> Vec<WidgetId> {
        let self_id = ctx.self_id();
        ctx.enabled_when(self_id, self.enabled.clone());

        let row_h = self.effective_row_height();
        let header_h = self.effective_header_height();

        // Version signal — bumps drive a rebuild.
        let version = ctx.signal(0_u64);
        version.bind_to(ctx.self_id(), ctx.binding_registry(), BindingLevel::Rebuild);

        // Scroll-y at Relayout: place_children re-runs without rebuild.
        self.scroll_y.bind_to(
            ctx.self_id(),
            ctx.binding_registry(),
            BindingLevel::Relayout,
        );
        ctx.register_animated_signal(&self.scroll_y);

        // Scroll-x mirrors scroll-y: Relayout re-places the header + body
        // bands (and any pane-aware root decorations) without a rebuild.
        self.scroll_x.bind_to(
            ctx.self_id(),
            ctx.binding_registry(),
            BindingLevel::Relayout,
        );
        ctx.register_animated_signal(&self.scroll_x);

        // Row-drop insertion indicator at RepaintOnly so on_drag_hover /
        // on_drag_leave `set(...)` calls dirty paint without a rebuild.
        self.drop_feedback.bind_to(
            ctx.self_id(),
            ctx.binding_registry(),
            BindingLevel::RepaintOnly,
        );

        // Pane → root total refresh (auto-measure mode): re-place this
        // root when the body pane's measurements changed the content
        // total, so `max_scroll_y` / the thumb ratio pick up the
        // corrected value.
        self.pane_total_refresh.bind_to(
            ctx.self_id(),
            ctx.binding_registry(),
            BindingLevel::Relayout,
        );

        // Column width overrides: any change re-runs place_children
        // (which calls ColumnSolver with the latest map). No rebuild
        // needed — widths flow through `column_widths` Rc into rows.
        self.column_widths_signal.bind_to(
            ctx.self_id(),
            ctx.binding_registry(),
            BindingLevel::Relayout,
        );

        // `OnRelease` resize guide line — paint-only, nothing moves until the
        // button comes up.
        self.resize_preview_x.bind_to(
            ctx.self_id(),
            ctx.binding_registry(),
            BindingLevel::RepaintOnly,
        );

        // A resize drag that loses the window never gets its PointerUp: the
        // user Alt-Tabs (or a native dialog steals focus) with the button
        // down, releases it over another window, and the OS delivers the Up
        // nowhere. Abandon the gesture on deactivation, or the state outlives
        // it and the next bare PointerMove drags the column with no button
        // held. Nothing is committed — an interrupted drag leaves the column
        // wherever the last delivered move put it, which is what the user last
        // saw.
        {
            let resize_state = self.resize_state.clone();
            let resize_target = self.resize_target.clone();
            let resize_preview_x = self.resize_preview_x.clone();
            ctx.effect(&ctx.window_active_signal(), move |active| {
                if !*active && resize_state.borrow().is_some() {
                    *resize_state.borrow_mut() = None;
                    resize_target.set(None);
                    resize_preview_x.set(None);
                }
            });
        }

        // Column order + pinning: changes require a rebuild because the
        // header cells and row cells must be re-emitted in the new order
        // (each cell captures its display-position-based 1-based index).
        let v_for_order = version.clone();
        let order_ver = Rc::new(Cell::new(0_u64));
        ctx.effect(&self.column_order_signal, move |_| {
            let next = order_ver.get() + 1;
            order_ver.set(next);
            v_for_order.set(next);
        });
        let v_for_pin = version.clone();
        let pin_ver = Rc::new(Cell::new(0_u64));
        ctx.effect(&self.column_pinning_signal, move |_| {
            let next = pin_ver.get() + 1;
            pin_ver.set(next);
            v_for_pin.set(next);
        });
        let v_for_edit = version.clone();
        let edit_ver = Rc::new(Cell::new(0_u64));
        ctx.effect(&self.editing_cell, move |_| {
            let next = edit_ver.get() + 1;
            edit_ver.set(next);
            v_for_edit.set(next);
        });
        let v_for_filter = version.clone();
        let filter_ver = Rc::new(Cell::new(0_u64));
        ctx.effect(&self.filters_signal, move |_| {
            let next = filter_ver.get() + 1;
            filter_ver.set(next);
            v_for_filter.set(next);
        });

        // Sort signal: a change requires a rebuild because each header
        // cell's chevron child is added/removed conditionally and the
        // AccessKit `set_sort_direction` is captured at build time.
        let v_for_sort = version.clone();
        let sort_ver = Rc::new(Cell::new(0_u64));
        ctx.effect(&self.sort_signal, move |_| {
            let next = sort_ver.get() + 1;
            sort_ver.set(next);
            v_for_sort.set(next);
        });

        // Observe model changes -> bump version.
        let v_for_data = version.clone();
        let data_ver = Rc::new(Cell::new(0_u64));
        let upstream = (self.observe_fn)(Box::new({
            let dv = data_ver.clone();
            let sel_for_adjust = self.row_selection.clone();
            let cell_sel_for_adjust = self.cell_selection.clone();
            let metrics_for_data = self.row_metrics.clone();
            let len_for_data = self.len_fn.clone();
            let first_changed = self.first_changed_fn.clone();
            move |change| {
                // Keep row metrics in step with the data: rows before
                // the first changed index keep their heights, the rest
                // re-derive. A `SortFilterListModel` source collapses
                // everything to `Reset` — its real divergence comes
                // through the side-channel, which is what lets an
                // append keep the measured prefix.
                let divergence = match change {
                    DataChange::ItemsInserted { range } | DataChange::ItemsRemoved { range } => {
                        Some(range.start)
                    }
                    DataChange::ItemUpdated { index } => Some(*index),
                    DataChange::ItemsMoved { from, to, .. } => Some((*from).min(*to)),
                    DataChange::WindowLoaded { range } => Some(range.start),
                    DataChange::Reset => (first_changed)(),
                };
                metrics_for_data
                    .borrow_mut()
                    .apply_divergence(divergence, (len_for_data)());
                // Keep row selection in step: index-shift (index model) or
                // prune orphaned keys (keyed model). Cell selection (always
                // index-based) is adjusted separately below.
                if let Some(ref rs) = sel_for_adjust {
                    rs.on_data_change(change);
                }
                if let Some(ref s) = cell_sel_for_adjust {
                    match change {
                        DataChange::ItemsInserted { range } => {
                            s.adjust_for_row_insert(range.start, range.end - range.start);
                        }
                        DataChange::ItemsRemoved { range } => {
                            s.adjust_for_row_remove(range.start, range.end - range.start);
                        }
                        DataChange::ItemsMoved { from, to, count } => {
                            s.adjust_for_row_move(*from, *to, *count);
                        }
                        DataChange::Reset => s.clear(),
                        _ => {}
                    }
                }
                let next = dv.get() + 1;
                dv.set(next);
                v_for_data.set(next);
            }
        }));
        ctx.own_handle(upstream);

        // Observe selection changes -> bump version (rebuild updates the
        // `is_selected` arg passed to cell delegates).
        if let Some(ref rs) = self.row_selection {
            let v_for_sel = version.clone();
            let sel_ver = Rc::new(Cell::new(0_u64));
            let handle = rs.observe_for_rebuild(move || {
                let next = sel_ver.get() + 1;
                sel_ver.set(next);
                v_for_sel.set(next);
            });
            ctx.own_handle(handle);
        }
        if let Some(ref cs) = self.cell_selection {
            let v_for_csel = version.clone();
            let csel_ver = Rc::new(Cell::new(0_u64));
            ctx.effect(&cs.selection_signal(), move |_| {
                let next = csel_ver.get() + 1;
                csel_ver.set(next);
                v_for_csel.set(next);
            });
        }

        // Observe scroll position — only rebuild when visible range exits
        // the buffered window. The Relayout binding above handles
        // intra-buffer scrolls without a rebuild.
        let vp_h = self.viewport_height.clone();
        let len_for_scroll = self.len_fn.clone();
        let (built_start, built_end) = self.visible_range();
        let prev_built_start = Rc::new(Cell::new(built_start));
        let prev_built_end = Rc::new(Cell::new(built_end));
        let v_for_scroll = version.clone();
        let scroll_ver = Rc::new(Cell::new(0_u64));
        let scroll_handle = self.scroll_y.observe({
            let pbs = prev_built_start.clone();
            let pbe = prev_built_end.clone();
            let sv = scroll_ver.clone();
            let metrics = self.row_metrics.clone();
            move |y| {
                let count = (len_for_scroll)();
                let (visible_start, visible_end) =
                    metrics.borrow_mut().visible_range(*y, vp_h.get(), count, 0);
                if visible_start < pbs.get() || visible_end > pbe.get() {
                    let new_start = visible_start.saturating_sub(BUFFER_ROWS);
                    let new_end = (visible_end + BUFFER_ROWS).min(count);
                    pbs.set(new_start);
                    pbe.set(new_end);
                    let next = sv.get() + 1;
                    sv.set(next);
                    v_for_scroll.set(next);
                }
            }
        });
        ctx.own_handle(scroll_handle);

        // Compute display order eagerly — the keyboard handler needs
        // the column count, and the header / body builds below also
        // need it. We re-write `self.display_indices` here; later
        // build steps read it.
        let display_indices_now = self.display_order();

        // Remap any `(row, display_pos)` pairs the *previous* order left in
        // `focused_cell` / `editing_cell` / `cell_selection` onto their
        // column's position under the order just computed, before it
        // overwrites `self.display_indices` below. A column reorder drag or
        // a pin toggle only bumps `version` (see the `column_order_signal` /
        // `column_pinning_signal` effects above) — display position is
        // recomputed here on every rebuild regardless of cause, so this map
        // is the identity (a no-op) unless THIS rebuild's cause was an
        // order/pinning change.
        {
            let old_display = self.display_indices.borrow();
            if !old_display.is_empty() {
                let old_to_new: Vec<Option<usize>> = old_display
                    .iter()
                    .map(|&decl_idx| {
                        let id = &self.columns[decl_idx].id;
                        display_indices_now
                            .iter()
                            .position(|&new_decl_idx| self.columns[new_decl_idx].id == *id)
                    })
                    .collect();
                drop(old_display);
                imperative::remap_cell_state(
                    &self.focused_cell,
                    &self.editing_cell,
                    self.cell_selection.as_ref(),
                    &old_to_new,
                );
            }
        }
        *self.display_indices.borrow_mut() = display_indices_now.clone();

        // Self handlers: scroll wheel + keyboard + clip + focusable.
        let scroll_y_for_wheel = self.scroll_y.clone();
        let max_scroll_for_wheel = self.max_scroll_y.clone();
        let scroll_x_for_wheel = self.scroll_x.clone();
        let max_scroll_x_for_wheel = self.max_scroll_x.clone();
        let line_height = row_h;
        let overscroll_behavior = self.overscroll_behavior;
        let smooth_scrolling = self.smooth_scrolling;
        let smooth_scroll_duration = self.smooth_scroll_duration;

        // Bind focused_cell at RepaintOnly — its update redraws the
        // focus ring without rebuilding the row tree. Also at
        // AccessibilityOnly (orthogonal — see `BindingLevel`) so a
        // keyboard focus move re-walks the AT tree and re-resolves
        // `active_descendant` in `accessibility()` below, even though
        // nothing about the cell's own node changed.
        self.focused_cell.bind_to(
            ctx.self_id(),
            ctx.binding_registry(),
            BindingLevel::RepaintOnly,
        );
        self.focused_cell.bind_to(
            ctx.self_id(),
            ctx.binding_registry(),
            BindingLevel::AccessibilityOnly,
        );

        // Focus-aware selection + modality-gated focus ring. `begin_view_focus`
        // keys the scope signal on this root id directly — the same id the body
        // pane uses for its row scope (`drag_anchor = ctx.self_id()`), and
        // independent of the arena focusable flag (not yet wired here). A plain
        // `view_focus_active()` here would find no focusable ancestor and fall
        // back to the constant-`true` "outside any scope" signal — `true`
        // whenever ANY widget holds focus, lighting every table's ring at once.
        // The signal is `true` whenever the table or any descendant holds focus,
        // so the selection band dims to `SelectedInactive` on focus-out. Pop
        // straight back; the body pane re-pushes the same cached signal.
        // `focus_visible` gates the cell ring to keyboard navigation. Both bound
        // `RepaintOnly`: a focus/modality change redraws without a rebuild.
        self.view_focused = ctx.begin_view_focus();
        ctx.end_view_focus();
        self.focus_visible = ctx.focus_visible();
        self.view_focused.bind_to(
            ctx.self_id(),
            ctx.binding_registry(),
            BindingLevel::RepaintOnly,
        );
        self.focus_visible.bind_to(
            ctx.self_id(),
            ctx.binding_registry(),
            BindingLevel::RepaintOnly,
        );

        // Build the navigator + key handler. The keyboard module is
        // generic over RowNavigator so TreeTableView can plug in its own
        // tree-aware navigator.
        let navigator: Rc<dyn row_navigator::RowNavigator> =
            Rc::new(row_navigator::FlatNavigator::new(self.len_fn.clone()));
        // display_col_to_id resolves a display position back to its
        // column id, so the keyboard module doesn't need a `Column<T>`
        // reference. Snapshotted at build; rebuilds re-issue this.
        let column_ids_in_display_order: Vec<String> = display_indices_now
            .iter()
            .map(|&i| self.columns[i].id.clone())
            .collect();
        let display_col_to_id: Rc<dyn Fn(usize) -> Option<String>> = {
            let ids = column_ids_in_display_order;
            Rc::new(move |pos| ids.get(pos).cloned())
        };
        // The effective trigger set per display column: the view's, overridden
        // by the column's own, and `NONE` for a non-editable one. Resolved here
        // so the keyboard handler never has to reach a `Column<T>`.
        let display_col_triggers: Rc<dyn Fn(usize) -> EditTriggers> = {
            let view_triggers = self.edit_triggers;
            let per_display_column: Vec<EditTriggers> = display_indices_now
                .iter()
                .map(|&i| self.columns[i].effective_edit_triggers(view_triggers))
                .collect();
            Rc::new(move |pos| {
                per_display_column
                    .get(pos)
                    .copied()
                    .unwrap_or(EditTriggers::NONE)
            })
        };

        // Type-ahead label resolver (row -> Some(text)) built from the user's
        // `Fn(&T) -> String` + the side-effect source read: the closure only
        // fires for a resident row, so unloaded (lazy) rows resolve to `None`
        // and the search skips them.
        let type_ahead_label: Option<Rc<dyn Fn(usize) -> Option<String>>> =
            self.type_ahead_label.clone().map(|user| {
                let with_item = self.with_item_fn.clone();
                Rc::new(move |i: usize| {
                    let out = std::cell::RefCell::new(None);
                    (with_item)(i, &|item| {
                        *out.borrow_mut() = Some(user(item));
                    });
                    out.into_inner()
                }) as Rc<dyn Fn(usize) -> Option<String>>
            });

        let key_cfg = keyboard::KeyHandlerConfig {
            navigator,
            col_count: display_indices_now.len().max(1),
            // Flat table: no tree column exists. `FlatNavigator` reports no
            // children and never expands, so this value is inert — it only has
            // to be a position the cursor can actually occupy.
            tree_column_display_pos: 0,
            focused_cell: self.focused_cell.clone(),
            selection_mode: self.selection_mode,
            selection: self.row_selection.clone(),
            cell_selection: self.cell_selection.clone(),
            scroll_y: self.scroll_y.clone(),
            max_scroll_y: self.max_scroll_y.clone(),
            viewport_height: self.viewport_height.clone(),
            body_bounds: self.body_bounds.clone(),
            row_metrics: self.row_metrics.clone(),
            tab_traversal: self.tab_traversal,
            editing_cell: self.editing_cell.clone(),
            display_col_to_id,
            display_col_triggers,
            on_cell_edit_request: self.on_cell_edit_request.clone(),
            on_row_activate: self.on_row_activate.clone(),
            type_ahead: self.type_ahead.clone(),
            type_ahead_label,
            type_ahead_timeout: self.type_ahead_timeout,
            column_widths: self.column_widths.clone(),
            pane_boundaries: *self.pane_boundaries.borrow(),
            scroll_x: self.scroll_x.clone(),
            max_scroll_x: self.max_scroll_x.clone(),
            middle_viewport_width: self.middle_viewport_width.clone(),
        };

        // Row DnD is owned by the backing source. The view computes the
        // geometric (target_row, position) and asks the source: `can_accept`
        // on hover gates the insertion line (forbidden → no affordance),
        // `accept_drop` on release commits the move (in-place for a
        // `ListModel`, routed for an external source). Same-view reorders and
        // foreign / cross-table drops both flow through `accept_drop` — the
        // erased closures recover SameView-vs-Foreign from the payload.
        let view_id = self.model_id;
        let can_accept_hover = self.dnd.can_accept_fn.clone();
        let scroll_for_hover = self.scroll_y.clone();
        let metrics_for_hover = self.row_metrics.clone();
        let len_for_hover = self.len_fn.clone();
        let header_h_for_hover = header_h;
        let band_width_for_hover = self.header_strip_width.clone();
        let feedback_for_hover = self.drop_feedback.clone();
        let export_for_hover = self.export.clone();

        let accept_drop_for_drop = self.dnd.accept_drop_fn.clone();
        let scroll_y_for_drop = self.scroll_y.clone();
        let header_h_for_drop = header_h;
        let metrics_for_drop = self.row_metrics.clone();
        let len_fn_for_drop = self.len_fn.clone();
        let feedback_for_drop = self.drop_feedback.clone();
        let export_for_drop = self.export.clone();
        let reorderable_for_drop = self.reorderable;

        let feedback_for_leave = self.drop_feedback.clone();
        let scroll_for_tick = self.scroll_y.clone();
        let max_scroll_for_tick = self.max_scroll_y.clone();
        let viewport_for_tick = self.viewport_height.clone();
        let header_h_for_tick = header_h;

        // Alt+Arrow reorder wraps the shared key handler: the move is a
        // synthetic same-view `RowDragData` through the source's
        // `accept_drop`, so it travels exactly the pointer-drop path. Every
        // other key falls through to the shared navigator (cell/row
        // movement, edit, etc.).
        let mut shared_key = keyboard::build_key_handler(key_cfg);
        let reorderable_kbd = self.reorderable;
        let accept_drop_kbd = self.dnd.accept_drop_fn.clone();
        let stash_kbd = self.dnd.stash_drag_keys_fn.clone();
        let focused_kbd = self.focused_cell.clone();
        let sel_kbd = self.row_selection.clone();
        let len_kbd = self.len_fn.clone();
        let key_handler = move |event: &teksilo_core::event::WidgetEvent,
                                ctx: &mut teksilo_core::widget::EventContext|
              -> teksilo_core::event::EventResponse {
            use teksilo_core::event::{EventResponse, Key, WidgetEvent};
            if reorderable_kbd
                && let WidgetEvent::KeyDown { key, modifiers, .. } = event
                && modifiers.alt()
            {
                let count = (len_kbd)();
                if count > 0 {
                    let cur = focused_kbd.get().map(|(r, _)| r).or_else(|| {
                        sel_kbd
                            .as_ref()
                            .and_then(|s| s.selected_indices().first().copied())
                    });
                    if let Some(idx) = cur {
                        let mv = match key {
                            Key::ArrowUp if idx > 0 => {
                                Some((idx - 1, DropPosition::Before, idx - 1))
                            }
                            Key::ArrowDown if idx + 1 < count => {
                                Some((idx + 1, DropPosition::After, idx + 1))
                            }
                            _ => None,
                        };
                        if let Some((target, position, dest)) = mv {
                            // Synthetic same-view payloads must stash the
                            // dragged row's key at construction — the accept
                            // path resolves identity from the stash, never
                            // from `rows`.
                            (stash_kbd)(&[idx]);
                            let payload =
                                teksilo_core::drag_payload::DragPayload::typed(RowDragData::<T> {
                                    source: view_id,
                                    rows: vec![idx],
                                    items: None,
                                });
                            if (accept_drop_kbd)(&payload, target, position, view_id) {
                                if let Some(ref s) = sel_kbd {
                                    s.select(dest);
                                }
                                let col = focused_kbd.get().map(|(_, c)| c).unwrap_or(0);
                                focused_kbd.set(Some((dest, col)));
                            }
                            return EventResponse::Handled;
                        }
                    }
                }
            }
            shared_key(event, ctx)
        };

        let mut handlers = HandlerSet::new()
            .on_scroll(move |event, _ctx| match event {
                teksilo_core::event::WidgetEvent::Scroll { delta, modifiers } => {
                    let (raw_dx, raw_dy) = match delta {
                        teksilo_core::event::ScrollDelta::Lines { x, y } => {
                            (x * line_height, y * line_height)
                        }
                        teksilo_core::event::ScrollDelta::Pixels { x, y } => (*x, *y),
                    };
                    // Shift+wheel remaps a vertical-only wheel to horizontal
                    // scroll (the `TabBar` precedent) — a genuine two-axis
                    // trackpad delta (both native `dx` and `dy` nonzero)
                    // passes through unremapped either way.
                    let (dx, dy) = if modifiers.shift() && raw_dx.abs() < f32::EPSILON {
                        (raw_dy, 0.0)
                    } else {
                        (raw_dx, raw_dy)
                    };

                    let mut moved_any = false;
                    if dy.abs() > 0.0 {
                        let current = scroll_y_for_wheel.get();
                        let max = max_scroll_for_wheel.get();
                        // Base off the animation target (not the rendered
                        // offset) so a mid-fling boundary correctly chains
                        // and successive notches accumulate instead of
                        // restarting from the partway-animated position.
                        let base = scroll_y_for_wheel.animation_target().unwrap_or(current);
                        let (new_y, moved) =
                            crate::common::scroll::scroll_clamp_axis(base, dy, max);
                        if moved {
                            if smooth_scrolling {
                                scroll_y_for_wheel.animate_to(
                                    new_y,
                                    smooth_scroll_duration,
                                    Easing::EaseOut,
                                );
                            } else {
                                scroll_y_for_wheel.set(new_y);
                            }
                        }
                        moved_any |= moved;
                    }
                    if dx.abs() > 0.0 {
                        let current = scroll_x_for_wheel.get();
                        let max = max_scroll_x_for_wheel.get();
                        let base = scroll_x_for_wheel.animation_target().unwrap_or(current);
                        let (new_x, moved) =
                            crate::common::scroll::scroll_clamp_axis(base, dx, max);
                        if moved {
                            if smooth_scrolling {
                                scroll_x_for_wheel.animate_to(
                                    new_x,
                                    smooth_scroll_duration,
                                    Easing::EaseOut,
                                );
                            } else {
                                scroll_x_for_wheel.set(new_x);
                            }
                        }
                        moved_any |= moved;
                    }
                    // Chain to an ancestor scrollable when fully clamped on
                    // every axis touched (unless Contain), otherwise consume.
                    crate::common::scroll::scroll_response(
                        moved_any,
                        overscroll_behavior == OverscrollBehavior::Contain,
                    )
                }
                _ => teksilo_core::event::EventResponse::Ignored,
            })
            .clips_children(true)
            .focusable(true);

        handlers = handlers.on_key(key_handler);

        // Row-level drop target: registered only when this table can
        // reorder its own rows or accept foreign ones (mirrors ListView).
        // Column reorder lives entirely on the header strip
        // (`attach_header_reorder_handlers`) and is untouched by this gate.
        if self.export.is_drop_target(self.reorderable) {
            handlers = handlers
                .on_drag_hover(move |payload, position, _ctx| {
                    // Column reorder is handled by the header strip; only
                    // row-level drops (same-view `RowDragData` or a foreign
                    // payload the source accepts) get an insertion line here.
                    if payload.has_typed::<ColumnReorderDragData>() {
                        feedback_for_hover.set(None);
                        return teksilo_core::DropFeedback::NoFeedback;
                    }
                    let body_y = position.y - header_h_for_hover;
                    let scroll = scroll_for_hover.get();
                    let content_y = body_y + scroll;
                    let len = (len_for_hover)();
                    let (ins, line_y) = {
                        let mut m = metrics_for_hover.borrow_mut();
                        m.resize(len);
                        let ins = m.insertion_index(content_y);
                        (ins, m.row_top(ins) - scroll)
                    };
                    let width = band_width_for_hover.get();
                    // Source-owned validation: paint the line only when the
                    // source does not reject the hovered position. A foreign
                    // exported row is allowed when `accept_foreign_rows` is on
                    // even though a bare `ListModel`'s `can_accept` rejects
                    // the `Foreign` branch.
                    let allowed = flat_insertion_target(ins, len).is_some_and(|(target, pos)| {
                        !matches!(
                            (can_accept_hover)(payload, target, pos, view_id),
                            DropResponse::Reject
                        ) || export_for_hover.accepts_foreign_export(payload, view_id)
                    });
                    if allowed {
                        feedback_for_hover.set(Some((line_y, width)));
                        teksilo_core::DropFeedback::InsertionLine { y: line_y, width }
                    } else {
                        feedback_for_hover.set(None);
                        teksilo_core::DropFeedback::NoFeedback
                    }
                })
                .on_drop(move |mut payload, position, ctx| {
                    feedback_for_drop.set(None);
                    if payload.has_typed::<ColumnReorderDragData>() {
                        return false;
                    }
                    let body_y = position.y - header_h_for_drop;
                    let scroll = scroll_y_for_drop.get();
                    let content_y = body_y + scroll;
                    let len = (len_fn_for_drop)();
                    let ins = {
                        let mut m = metrics_for_drop.borrow_mut();
                        m.resize(len);
                        m.insertion_index(content_y)
                    };
                    let is_same_view = payload
                        .get_typed::<RowDragData<T>>()
                        .is_some_and(|rd| rd.source == view_id);
                    // Route the drop to the source's accept_drop first. A
                    // same-view reorder only happens when the table is
                    // `reorderable`; a foreign payload is the source's
                    // call (a bare ListModel rejects it).
                    if (reorderable_for_drop || !is_same_view)
                        && let Some((target, position_kind)) = flat_insertion_target(ins, len)
                        && (accept_drop_for_drop)(&payload, target, position_kind, view_id)
                    {
                        // Only suppress our OWN move-out for a genuine
                        // same-view drop.
                        if is_same_view {
                            export_for_drop.note_self_reorder();
                        }
                        return true;
                    }
                    // Otherwise, the shared foreign-receive sugar
                    // (peek-before-take).
                    export_for_drop.foreign_receive(&mut payload, view_id, ins, ctx)
                })
                .on_drag_leave(move |_ctx| {
                    feedback_for_leave.set(None);
                })
                .on_drag_tick(move |pos, _ctx| {
                    // Auto-scroll when the pointer lingers within 32 px of the
                    // body band's top/bottom edge during a drag (body-relative
                    // so the header doesn't count as the top edge).
                    const EDGE: f32 = 32.0;
                    const MAX_VELOCITY: f32 = 12.0;
                    let body_h = (viewport_for_tick.get() - header_h_for_tick).max(0.0);
                    let y = pos.y - header_h_for_tick;
                    let above = (EDGE - y).max(0.0);
                    let below = (y - (body_h - EDGE)).max(0.0);
                    let delta = if above > 0.0 {
                        -(above / EDGE) * MAX_VELOCITY
                    } else if below > 0.0 {
                        (below / EDGE) * MAX_VELOCITY
                    } else {
                        0.0
                    };
                    if delta.abs() > 0.01 {
                        let max = max_scroll_for_tick.get();
                        let new_y = (scroll_for_tick.get() + delta).clamp(0.0, max);
                        scroll_for_tick.set(new_y);
                    }
                });
        }

        // Export completion (move-out): fires on the drag source — this
        // table's root id, the stable id `start_drag` was given.
        handlers = self.export.install_completion(handlers);

        ctx.apply_self_handlers(handlers);

        // ── Build children ────────────────────────────────────────────
        self.header_row_id = None;
        self.body_pane_id = None;
        self.scrollbar_id = None;
        self.h_scrollbar_id = None;
        self.empty_id = None;

        // Display order was already computed above (before the
        // keyboard handler was wired); pull it back into a local for
        // the header / body loops.
        let display_indices = display_indices_now;

        // Header strip: build first so it sits above the body in the
        // child order (place_children iterates in this order).
        if self.show_header {
            // A rebuild destroys (and re-creates) every header cell, which
            // drops the pointer capture an in-flight resize depends on. Clear
            // the shared drag state with it: a `ResizeState` that outlived its
            // anchor would otherwise let the next bare PointerMove over the
            // same column resize it with no button held.
            *self.resize_state.borrow_mut() = None;
            self.resize_target.set(None);
            self.resize_preview_x.set(None);

            let boundaries = *self.pane_boundaries.borrow();
            let resize_columns: header::ColumnResizeTable = Rc::new(
                display_indices
                    .iter()
                    .map(|&i| {
                        let c = &self.columns[i];
                        header::ColumnResizeInfo {
                            id: c.id.clone(),
                            min_width: c.min_width.unwrap_or(cp::MIN_COLUMN_WIDTH_DEFAULT),
                            max_width: c.max_width,
                            resizable: c.resizable,
                        }
                    })
                    .collect(),
            );
            let mut cell_ids: Vec<WidgetId> = Vec::with_capacity(display_indices.len());
            let active_sort = self.sort_signal.get();
            for (display_pos, &col_idx) in display_indices.iter().enumerate() {
                let col = &self.columns[col_idx];
                let current_sort = active_sort
                    .as_ref()
                    .and_then(|(id, dir)| if id == &col.id { Some(*dir) } else { None });
                // Filter zone width: indicator glyph + a small horizontal
                // padding for tap tolerance. Mirrors the layout of the
                // HStack inside HeaderCell::build.
                let filter_zone_width = cp::FILTER_INDICATOR_SIZE + cp::CELL_PADDING_HORIZONTAL;
                let cell = header::HeaderCell::new(header::HeaderCellSpec {
                    col_id: col.id.clone(),
                    label: col.header_label.resolve_now(),
                    col_index_1based: display_pos + 1,
                    sortable: col.sortable,
                    reorderable: col.reorderable,
                    filterable: col.filterable,
                    resize_grip: cp::RESIZE_HANDLE_WIDTH,
                    filter_zone_width,
                    current_sort,
                    width_index: display_pos,
                    pane_boundaries: boundaries,
                    resize_columns: resize_columns.clone(),
                    resize_policy: self.column_resize_policy,
                    resize_state: self.resize_state.clone(),
                    resize_target: self.resize_target.clone(),
                    resize_preview_x: self.resize_preview_x.clone(),
                    table_id: self.table_id,
                    sort_signal: self.sort_signal.clone(),
                    column_widths_signal: self.column_widths_signal.clone(),
                    column_widths: self.column_widths.clone(),
                    filters_signal: self.filters_signal.clone(),
                });
                cell_ids.push(ctx.add(cell));
            }
            let header_row = header::HeaderRow::new(
                cell_ids,
                self.column_widths.clone(),
                cp::GRID_LINE_THICKNESS,
                *self.pane_boundaries.borrow(),
                self.scroll_x.clone(),
            );
            // Wire reorder drag-target handlers on the header strip.
            let header_row_id = ctx.add(header_row);
            header::attach_header_reorder_handlers(
                ctx,
                header_row_id,
                self.table_id,
                self.column_widths.clone(),
                self.display_indices.clone(),
                self.pane_boundaries.clone(),
                self.column_order_signal.clone(),
                self.column_pinning_signal.clone(),
                self.columns.iter().map(|c| c.id.clone()).collect(),
                self.header_strip_width.clone(),
                self.scroll_x.clone(),
            );
            self.header_row_id = Some(header_row_id);
        }

        let row_count = (self.len_fn)();

        // Lazy: nudge the source to load the realized window, and fetch the
        // next page as the viewport nears the end (append-only sources). A
        // fully-resident source leaves these inert.
        let (vis_start, vis_end) = self.visible_range();
        (self.dnd.request_window_fn)(vis_start..vis_end);
        if (self.dnd.can_fetch_more_fn)() && vis_end + BUFFER_ROWS >= row_count {
            (self.dnd.fetch_more_fn)();
        }

        if row_count == 0 {
            // Empty state.
            if let Some(ref f) = self.empty_view {
                let id = ctx.add_boxed(f());
                self.empty_id = Some(id);
            }
        } else {
            // Hoist the row pane into its own widget so that
            // scroll-buffer-exit rebuilds (which happen mid-thumb-drag
            // when the user scrolls past the buffered range) target a
            // sibling of the scrollbar rather than the scrollbar's
            // ancestor. Rebuilding the ancestor would be deferred by
            // the framework (to preserve the captured drag), leaving
            // the body empty until the user released the thumb.
            let pane = body_pane::BodyPane::<T> {
                len_fn: self.len_fn.clone(),
                with_item_fn: self.with_item_fn.clone(),
                drag_fn: self.dnd.drag_fn.clone(),
                row_state_fn: self.dnd.row_state_fn.clone(),
                columns: self.columns.clone(),
                display_indices: self.display_indices.clone(),
                column_widths: self.column_widths.clone(),
                pane_boundaries: *self.pane_boundaries.borrow(),
                scroll_x: self.scroll_x.clone(),
                row_metrics: self.row_metrics.clone(),
                selection_mode: self.selection_mode,
                selection: self.row_selection.clone(),
                cell_selection: self.cell_selection.clone(),
                scroll_y: self.scroll_y.clone(),
                viewport_height: self.viewport_height.clone(),
                editing_cell: self.editing_cell.clone(),
                focused_cell: self.focused_cell.clone(),
                reorderable: self.reorderable,
                export: self.export.clone(),
                snapshot_out_fn: self.dnd.snapshot_out_fn.clone(),
                anchor_fn: self.anchor_fn.clone(),
                editing_anchor: self.editing_anchor.clone(),
                view_id: self.model_id,
                drag_anchor: ctx.self_id(),
                on_row_activate: self.on_row_activate.clone(),
                activate_on: self.activate_on,
                edit_triggers: self.edit_triggers,
                on_cell_edit_request: self.on_cell_edit_request.clone(),
                on_cell_edit_dismissed: self.on_cell_edit_dismissed.clone(),
                version: self.pane_version.clone(),
                prev_built_start: self.pane_built_start.clone(),
                prev_built_end: self.pane_built_end.clone(),
                total_refresh: self.pane_total_refresh.clone(),
                row_entries: Vec::new(),
                cell_map: self.cell_map.clone(),
            };
            self.body_pane_id = Some(ctx.add(pane));
            // An open cell editor also ends on a press that lands on no cell at
            // all — the empty band under the last row. Mounted here rather than
            // on the pane because the pane is not the hit target there.
            if let Some(handlers) = body_pane::root_edit_dismiss_handler(
                &self.on_cell_edit_dismissed,
                &self.editing_cell,
                &Rc::new(
                    display_indices
                        .iter()
                        .map(|&i| self.columns[i].id.clone())
                        .collect::<Vec<_>>(),
                ),
            ) {
                ctx.apply_self_handlers(handlers);
            }
        }

        // Scrollbar (single internal vertical bar).
        if self.show_internal_scrollbars {
            let sb = ScrollBar::new(
                ScrollBarOrientation::Vertical,
                self.scroll_y.clone(),
                self.max_scroll_y.clone(),
                self.viewport_ratio_y.clone(),
            )
            .visual(match self.scroll_bar_style {
                ScrollBarMode::Permanent => ScrollBarVisual::Permanent,
                ScrollBarMode::Overlay => ScrollBarVisual::Overlay,
                ScrollBarMode::Thin => ScrollBarVisual::Thin,
            });
            self.scrollbar_id = Some(ctx.add(sb));

            // Horizontal bar — the Middle pane only. Visibility (max_scroll_x
            // > 0) and geometry (band_left + pinned-pane offsets) are decided
            // in `place_children`, same as the vertical bar's `needs_scrollbar`
            // gate; here we just build it unconditionally so it exists to be
            // placed (zero-sized and skipped when not needed).
            let hsb = ScrollBar::new(
                ScrollBarOrientation::Horizontal,
                self.scroll_x.clone(),
                self.max_scroll_x.clone(),
                self.viewport_ratio_x.clone(),
            )
            .visual(match self.scroll_bar_style {
                ScrollBarMode::Permanent => ScrollBarVisual::Permanent,
                ScrollBarMode::Overlay => ScrollBarVisual::Overlay,
                ScrollBarMode::Thin => ScrollBarVisual::Thin,
            });
            self.h_scrollbar_id = Some(ctx.add(hsb));
        }

        // Z-order: body rows first, then empty/scrollbar, then header
        // last. The header band overlaps the top of the body region
        // when `scroll_y > 0` (rows positioned at `body_origin_y +
        // row_idx * row_h - scroll_y` can extend above
        // `body_origin_y` on overscroll). Painting the header last
        // means it sits on top of any row that bleeds into the
        // header band — without this fix, scrolled-out rows would
        // visibly draw over the header label.
        let mut children: Vec<WidgetId> = Vec::new();
        if let Some(id) = self.body_pane_id {
            children.push(id);
        }
        if let Some(id) = self.empty_id {
            children.push(id);
        }
        if let Some(id) = self.scrollbar_id {
            children.push(id);
        }
        if let Some(id) = self.h_scrollbar_id {
            children.push(id);
        }
        if let Some(id) = self.header_row_id {
            children.push(id);
        }
        // Suppress the unused-binding warning on header_h while the
        // value is consumed by `place_children` via the same helper.
        let _ = header_h;
        children
    }

    fn layout_response(
        &self,
        proposal: SizeProposal,
        _ctx: &LayoutContext,
    ) -> teksilo_core::widget::LayoutResponse {
        // Only an allocation may seed the cached viewport (`common::viewport`);
        // the body pane shares this very cell, so a measurement's fallback
        // would desync its realization window.
        let size = crate::common::viewport::viewport_size(
            proposal,
            &self.viewport_height,
            Size::new(400.0, 300.0),
        );
        if proposal.height.is_some() {
            // Viewport-relative imperatives are meaningful from here on — but
            // only once a real height has landed, for the reason `laid_out`
            // exists at all.
            self.laid_out.set(true);
        }
        size.into()
    }

    fn place_children(
        &self,
        bounds: Rect,
        _proposal: SizeProposal,
        children: &mut [WidgetPlacement],
        ctx: &LayoutContext,
    ) {
        if children.is_empty() {
            return;
        }
        let rtl = ctx.is_rtl();
        let header_h = self.effective_header_height();
        // Provisional — the vertical scrollbar's own need is decided
        // against this (a possible tiny inaccuracy if reserving room for
        // the horizontal bar below would itself flip that decision; not
        // worth a fixed-point iteration for a dual-scrollbar corner case).
        let body_height_provisional = (bounds.height - header_h).max(0.0);

        // Parent-before-child layout order means this runs before the
        // body pane's measure pass — in auto-measure mode the scrollbar
        // totals settle one frame after a measurement change.
        let total_height = self.total_content_height();
        let needs_v_scrollbar =
            self.show_internal_scrollbars && total_height > body_height_provisional + 0.5;
        // Permanent reserves a column for the bar; Overlay / Thin float
        // over the content, so rows span the full width.
        let reserves_v_bar = needs_v_scrollbar && self.scroll_bar_style == ScrollBarMode::Permanent;
        let body_width = if reserves_v_bar {
            (bounds.width - SCROLLBAR_THICKNESS).max(0.0)
        } else {
            bounds.width
        };
        // Under RTL the vertical scrollbar moves to the physical left
        // (matching `ScrollArea`), so the body/header band shifts right
        // by its thickness. `band_left` is the shared origin for the
        // body pane, empty state, and header; `scrollbar_x` is the
        // scrollbar's own physical x. The paint pass derives the same
        // content region from these conventions so the two never drift.
        let band_left = if rtl && reserves_v_bar {
            bounds.x + SCROLLBAR_THICKNESS
        } else {
            bounds.x
        };
        let scrollbar_x = if rtl {
            bounds.x
        } else {
            bounds.x + bounds.width - SCROLLBAR_THICKNESS
        };
        // The header strip spans the band; snapshot its width for the
        // reorder-drop handler's RTL mirror.
        self.header_strip_width.set(body_width);

        // Resolve column widths in display order, honoring any
        // user-resize overrides from `column_widths_signal`.
        let overrides = self.column_widths_signal.get();
        let display = self.display_indices.borrow().clone();
        let widths = layout::ColumnSolver::resolve_in_order(
            &self.columns,
            &display,
            body_width,
            cp::MIN_COLUMN_WIDTH_DEFAULT,
            &overrides,
        );

        // Pane geometry: the Middle pane's viewport (`body_width` minus the
        // pinned panes) and the horizontal scroll headroom it implies.
        let boundaries = *self.pane_boundaries.borrow();
        let (leading_w, middle_content_w, trailing_w) = layout::pane_widths(&widths, boundaries);
        let middle_viewport_w = (body_width - leading_w - trailing_w).max(0.0);
        let max_x = (middle_content_w - middle_viewport_w).max(0.0);
        self.max_scroll_x.set(max_x);
        self.middle_viewport_width.set(middle_viewport_w);
        let x_ratio = if middle_content_w > 0.0 {
            (middle_viewport_w / middle_content_w).clamp(0.0, 1.0)
        } else {
            1.0
        };
        self.viewport_ratio_x.set(x_ratio);
        // Clamp scroll_x — a pane shrink (window narrowed, a column grew)
        // must not leave scroll_x stranded past the new max (mirrors
        // `clamp_scroll` for scroll_y).
        {
            let current = self.scroll_x.get();
            let clamped = current.clamp(0.0, max_x);
            if (clamped - current).abs() > 0.001 {
                self.scroll_x.set(clamped);
            }
        }

        *self.column_widths.borrow_mut() = widths;

        let needs_h_scrollbar = self.show_internal_scrollbars && max_x > 0.5;
        let reserves_h_bar = needs_h_scrollbar && self.scroll_bar_style == ScrollBarMode::Permanent;
        let body_height = if reserves_h_bar {
            (body_height_provisional - SCROLLBAR_THICKNESS).max(0.0)
        } else {
            body_height_provisional
        };

        // Vertical scrollbar totals, against the FINAL body_height (after
        // any horizontal-bar reservation) so the range stays accurate when
        // both bars show at once.
        let max_y = (total_height - body_height).max(0.0);
        self.max_scroll_y.set(max_y);
        let y_ratio = if total_height > 0.0 {
            (body_height / total_height).clamp(0.0, 1.0)
        } else {
            1.0
        };
        self.viewport_ratio_y.set(y_ratio);
        self.clamp_scroll();

        let body_origin_y = bounds.y + header_h;
        // Cache the row-area rect for the keyboard handler's outer-scroll chase.
        self.body_bounds
            .set(Rect::new(band_left, body_origin_y, body_width, body_height));

        let mut next = 0;

        // BodyPane fills the body region. It positions its rows
        // internally using its own scroll signal and clips them to
        // its own bounds.
        if self.body_pane_id.is_some() {
            if let Some(child) = children.get_mut(next) {
                child.origin = Point::new(band_left, body_origin_y);
                child.size = Size::new(body_width, body_height);
            }
            next += 1;
        }

        // Empty-state child fills the body region (below the header).
        if self.empty_id.is_some() {
            if let Some(child) = children.get_mut(next) {
                child.origin = Point::new(band_left, body_origin_y);
                child.size = Size::new(body_width, body_height);
            }
            next += 1;
        }

        // Scrollbar — alongside the body, below the header. Physical
        // left under RTL, physical right under LTR.
        if self.scrollbar_id.is_some() {
            if let Some(child) = children.get_mut(next) {
                if needs_v_scrollbar {
                    child.origin = Point::new(scrollbar_x, body_origin_y);
                    child.size = Size::new(SCROLLBAR_THICKNESS, body_height);
                } else {
                    child.origin = bounds.origin();
                    child.size = Size::ZERO;
                }
            }
            next += 1;
        }

        // Horizontal scrollbar — the Middle pane's own band, below the
        // body, never overlapping a pinned pane.
        if self.h_scrollbar_id.is_some() {
            if let Some(child) = children.get_mut(next) {
                if needs_h_scrollbar {
                    let h_x = if rtl {
                        band_left + trailing_w
                    } else {
                        band_left + leading_w
                    };
                    child.origin = Point::new(h_x, body_origin_y + body_height);
                    child.size = Size::new(middle_viewport_w, SCROLLBAR_THICKNESS);
                } else {
                    child.origin = bounds.origin();
                    child.size = Size::ZERO;
                }
            }
            next += 1;
        }

        // Header strip last — placed at top y but emitted last so paint
        // z-order draws it above any overscrolled body rows.
        if self.header_row_id.is_some()
            && let Some(child) = children.get_mut(next)
        {
            child.origin = Point::new(band_left, bounds.y);
            child.size = Size::new(body_width, header_h);
        }
    }

    fn paint(&self, bounds: Rect, canvas: &mut Canvas, ctx: &PaintContext) {
        let header_h = self.effective_header_height();
        let colors = &ctx.theme.colors;

        let scroll_y = self.scroll_y.get();
        let body_origin_y = bounds.y + header_h;
        let body_height = (bounds.height - header_h).max(0.0);
        let widths = self.column_widths.borrow();
        let body_width = widths.iter().sum::<f32>();
        let body_width_for_paint = if body_width > 0.0 {
            body_width.min(bounds.width)
        } else {
            bounds.width
        };
        // Physical left edge of the column content. Under RTL the band is
        // right-aligned within `bounds` (the scrollbar took the left), so
        // content runs from `bounds.right() - body_width` leftward —
        // exactly where `place_children` reverse-placed the cells.
        let rtl = ctx.layout_direction == teksilo_core::environment::LayoutDirection::RightToLeft;
        let content_left = if rtl {
            bounds.x + bounds.width - body_width_for_paint
        } else {
            bounds.x
        };

        // Visible row window for the paint passes — offset-table-driven
        // so variable heights paint correctly. One metrics borrow per
        // pass; nothing inside re-enters the metrics.
        let row_count = (self.len_fn)();
        let (first_visible, last_visible) =
            self.row_metrics
                .borrow_mut()
                .visible_range(scroll_y, body_height, row_count, 0);

        // Clip the root-painted row decorations (alt-row stripes,
        // selection bands, grid lines, focus ring) to the body band.
        // `clips_children` only clips child WIDGETS — this widget's own
        // paint would otherwise bleed past the table's bottom edge for
        // the partially visible last row (its stripe/grid-line rect
        // spans the full row height).
        canvas.set_clip(Rect::new(
            content_left,
            body_origin_y,
            body_width_for_paint,
            body_height,
        ));

        // Alt-row backgrounds — paint odd visible rows. Parity keys on
        // the row index, not on y, so stripes stay stable under
        // variable heights.
        if self.alternating_rows {
            let mut m = self.row_metrics.borrow_mut();
            for row_idx in first_visible..last_visible {
                if row_idx % 2 == 1 {
                    let y = body_origin_y + m.row_top(row_idx) - scroll_y;
                    let h = m.row_height(row_idx);
                    let rect = Rect::new(content_left, y, body_width_for_paint, h);
                    canvas.fill_rect(rect, SurfaceRole::AltRow.resolve(colors));
                }
            }
        }

        // Selection highlights — row selection modes only.
        if let Some(ref sel) = self.row_selection
            && matches!(
                self.selection_mode,
                TableSelectionMode::SingleRow | TableSelectionMode::MultiRow
            )
        {
            // Focus- and window-aware: vivid `Selected` while the table holds
            // keyboard focus AND the host window is active; muted
            // `SelectedInactive` once focus moves elsewhere or the window goes
            // inactive (the same desaturation serves both states).
            let bg = if self.view_focused.get() && ctx.window_active {
                SurfaceRole::Selected.resolve(colors)
            } else {
                SurfaceRole::SelectedInactive.resolve(colors)
            };
            let mut m = self.row_metrics.borrow_mut();
            for row_idx in sel.selected_indices() {
                let y = body_origin_y + m.row_top(row_idx) - scroll_y;
                let h = m.row_height(row_idx);
                if y + h < body_origin_y || y > body_origin_y + body_height {
                    continue;
                }
                let rect = Rect::new(content_left, y, body_width_for_paint, h);
                canvas.fill_rect(rect, bg);
            }
        }

        // Grid lines.
        let line_color = BorderRole::Divider.resolve(colors);
        let line_w = cp::GRID_LINE_THICKNESS.max(1.0);

        if matches!(self.grid_lines, GridLines::Horizontal | GridLines::Both) {
            let mut m = self.row_metrics.borrow_mut();
            for row_idx in first_visible..last_visible {
                let bottom = m.row_top(row_idx) + m.row_height(row_idx);
                let y = body_origin_y + bottom - scroll_y - line_w;
                let rect = Rect::new(content_left, y, body_width_for_paint, line_w);
                canvas.fill_rect(rect, line_color);
            }
        }

        // Pane geometry for the two column-position-dependent decorations
        // below (vertical grid lines, the cell focus ring): both must clip
        // to the target column's OWN pane, or a scrolled Middle-pane
        // decoration could paint over a pinned Leading/Trailing column
        // within the same row band (the outer body clip above only bounds
        // the row's outer edges, not the seam between panes).
        let boundaries = *self.pane_boundaries.borrow();
        let scroll_x = self.scroll_x.get();
        let content_bounds = Rect::new(
            content_left,
            body_origin_y,
            body_width_for_paint,
            body_height,
        );
        let (leading_rect, middle_rect, trailing_rect) =
            layout::band_rects(content_bounds, &widths, boundaries, rtl);

        if matches!(self.grid_lines, GridLines::Vertical | GridLines::Both) {
            let leading_end = boundaries.leading_count.min(widths.len());
            let middle_end = boundaries.middle_end.min(widths.len()).max(leading_end);
            draw_pane_dividers(
                canvas,
                leading_rect,
                &widths[..leading_end],
                0.0,
                rtl,
                line_color,
                line_w,
            );
            draw_pane_dividers(
                canvas,
                middle_rect,
                &widths[leading_end..middle_end],
                scroll_x,
                rtl,
                line_color,
                line_w,
            );
            draw_pane_dividers(
                canvas,
                trailing_rect,
                &widths[middle_end..],
                0.0,
                rtl,
                line_color,
                line_w,
            );
        }

        // Focus ring on the currently-focused cell — keyboard-only
        // (`:focus-visible`) and only while the table itself holds focus, so a
        // mouse click never leaves a ring and an unfocused table shows none.
        if self.view_focused.get()
            && self.focus_visible.get()
            && let Some((focus_row, focus_col)) = self.focused_cell.get()
            && focus_col < widths.len()
            && let Some(x_off) = layout::column_logical_x(
                &widths,
                boundaries,
                scroll_x,
                body_width_for_paint,
                focus_col,
            )
        {
            let cell_w = widths[focus_col];
            let (focus_top, focus_h) = {
                let mut m = self.row_metrics.borrow_mut();
                (m.row_top(focus_row), m.row_height(focus_row))
            };
            let y = body_origin_y + focus_top - scroll_y;
            if y + focus_h >= body_origin_y && y <= body_origin_y + body_height {
                let pane_rect = if focus_col < boundaries.leading_count {
                    leading_rect
                } else if focus_col >= boundaries.middle_end {
                    trailing_rect
                } else {
                    middle_rect
                };
                canvas.set_clip(pane_rect);
                let inset = cp::FOCUS_RING_INSET;
                let stroke = cp::GRID_LINE_THICKNESS.max(1.5);
                let ring_color = BorderRole::Focused.resolve(colors);
                // `x_off` is the leading-side offset (sum of widths before
                // the focused column). Under RTL that offset is measured
                // from the right edge of the content band.
                let rx = if rtl {
                    content_left + body_width_for_paint - x_off - cell_w + inset
                } else {
                    content_left + x_off + inset
                };
                let ry = y + inset;
                let rw = (cell_w - inset * 2.0).max(0.0);
                let rh = (focus_h - inset * 2.0).max(0.0);
                // Top
                canvas.fill_rect(Rect::new(rx, ry, rw, stroke), ring_color);
                // Bottom
                canvas.fill_rect(Rect::new(rx, ry + rh - stroke, rw, stroke), ring_color);
                // Left
                canvas.fill_rect(Rect::new(rx, ry, stroke, rh), ring_color);
                // Right
                canvas.fill_rect(Rect::new(rx + rw - stroke, ry, stroke, rh), ring_color);
                canvas.clear_clip();
            }
        }

        // Row-drop insertion indicator (source-accepted positions only —
        // a forbidden hover clears the signal, so no line shows). `y` is
        // stored body-local; the band clip is already active.
        if let Some((y, _width)) = self.drop_feedback.get() {
            let line_color = BorderRole::Focused.resolve(colors);
            let thickness = 2.0_f32;
            let line_y = body_origin_y + y - thickness * 0.5;
            canvas.fill_rect(
                Rect::new(content_left, line_y, body_width_for_paint, thickness),
                line_color,
            );
        }

        canvas.clear_clip();

        // Container focus ring — the table holds keyboard focus but nothing
        // indicates where: no current cell (no cell ring) and no selection (no
        // band). Outline the whole view so Tab has a visible landing point
        // before the user navigates (mirrors TreeView / ListView).
        let nothing_indicated = self.focused_cell.get().is_none()
            && self
                .row_selection
                .as_ref()
                .is_none_or(|s| s.selected_indices().is_empty())
            && self.cell_selection.as_ref().is_none_or(|s| s.count() == 0);
        if self.view_focused.get() && self.focus_visible.get() && nothing_indicated {
            let inset = 1.0_f32;
            let rect = Rect::new(
                bounds.x + inset,
                bounds.y + inset,
                (bounds.width - inset * 2.0).max(0.0),
                (bounds.height - inset * 2.0).max(0.0),
            );
            canvas.stroke_rect(rect, BorderRole::Focused.resolve(colors), 1.5);
        }

        // `OnRelease` column-resize guide. Under that policy no column moves
        // until the button comes up, so this line is the *only* feedback the
        // gesture has — the same full-height rubber band Qt / Excel draw.
        if let Some(x) = self.resize_preview_x.get() {
            let thickness = cp::GRID_LINE_THICKNESS.max(1.5);
            canvas.fill_rect(
                Rect::new(x - thickness * 0.5, bounds.y, thickness, bounds.height),
                BorderRole::Focused.resolve(colors),
            );
        }
    }

    fn accessibility(&self, builder: &mut AccessNodeBuilder) {
        builder.set_role(teksilo_core::accesskit::Role::Table);
        if let Some(ref label) = self.a11y_label {
            builder.set_name(label.resolve_now());
        }
        // AccessKit's `row_count` includes the header row when present —
        // matches ARIA `aria-rowcount` semantics.
        let row_count = (self.len_fn)() + if self.show_header { 1 } else { 0 };
        let col_count = self.columns.len();
        let n = builder.inner_mut();
        n.set_row_count(row_count);
        n.set_column_count(col_count);

        // Roving focus: point active_descendant at the focused cell's own
        // AT node so a screen reader follows arrow-key cell navigation
        // (only the table root is otherwise focusable — the ring is
        // visual-only). `cell_map` is a snapshot of the body pane's last
        // realized cells; a focused cell that scrolled out of the
        // realized buffer simply isn't in it, so no stale id is emitted.
        if let Some(target) = self.focused_cell.get() {
            let map = self.cell_map.borrow();
            if let Some(&(_, cell_id)) = map.iter().find(|&&(pos, _)| pos == target) {
                builder.set_active_descendant(widget_id_to_node_id(cell_id));
            }
        }
    }

    fn as_any(&self) -> Option<&dyn std::any::Any> {
        Some(self)
    }

    fn children(&self) -> Vec<WidgetId> {
        // Same order as `build()` — body pane first, header last so
        // it paints on top of any overscrolled rows.
        let mut out: Vec<WidgetId> = Vec::new();
        if let Some(id) = self.body_pane_id {
            out.push(id);
        }
        if let Some(id) = self.empty_id {
            out.push(id);
        }
        if let Some(id) = self.scrollbar_id {
            out.push(id);
        }
        if let Some(id) = self.h_scrollbar_id {
            out.push(id);
        }
        if let Some(id) = self.header_row_id {
            out.push(id);
        }
        out
    }

    fn accessibility_children(&self) -> Option<Vec<WidgetId>> {
        // WCAG 1.3.2 (audit G17): read the column-header row FIRST, then the
        // body, even though `build()` / `children()` list the body first so it
        // paints beneath the header. Same id set as `children()`, reordered.
        let out: Vec<WidgetId> = [
            self.header_row_id,
            self.body_pane_id,
            self.empty_id,
            self.scrollbar_id,
            self.h_scrollbar_id,
        ]
        .into_iter()
        .flatten()
        .collect();
        if out.is_empty() { None } else { Some(out) }
    }

    fn clips_children(&self) -> bool {
        true
    }
}

/// Draw the internal vertical grid-line dividers for one pane band —
/// `slice.len() - 1` lines between adjacent columns, clipped to `rect` so a
/// scrolled Middle-pane line can't bleed past its own viewport into a
/// pinned neighbour. `scroll` is nonzero only for the Middle pane.
///
/// Shared by `TableView`/`TreeTableView`'s `paint()`, which are otherwise
/// near-identical for this decoration.
#[allow(clippy::too_many_arguments)]
pub(crate) fn draw_pane_dividers(
    canvas: &mut Canvas,
    rect: Rect,
    slice: &[f32],
    scroll: f32,
    rtl: bool,
    color: teksilo_tokens::Color,
    line_w: f32,
) {
    if slice.len() < 2 || rect.width <= 0.0 {
        return;
    }
    canvas.set_clip(rect);
    if rtl {
        let mut x = rect.right() + scroll;
        for &w in &slice[..slice.len() - 1] {
            x -= w;
            canvas.fill_rect(Rect::new(x, rect.y, line_w, rect.height), color);
        }
    } else {
        let mut x = rect.x - scroll;
        for &w in &slice[..slice.len() - 1] {
            x += w;
            canvas.fill_rect(Rect::new(x - line_w, rect.y, line_w, rect.height), color);
        }
    }
    canvas.clear_clip();
}

// Reorder drag-target plumbing (hover + drop on the header strip) lives in
// `header::attach_header_reorder_handlers` — shared with `TreeTableView`,
// which builds its header out of the same `HeaderCell`/`HeaderRow` pair.