oriel-iced 0.1.0

iced integrator for the oriel headless data grid: satisfies the data and render seams for iced 0.14.
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
//! The grid widget — [`VirtualGrid`], everything it emits and accepts, and
//! its public style defaults.
//!
//! New here? Start at the [crate root](crate) for the runnable quickstart,
//! the wiring contract, and the "where do I…?" map. This module holds the
//! working surface: [`Message`] (forward every one to
//! [`VirtualGrid::update`] and run the returned tasks), the imperative
//! methods (ingest, specs, scrolling, navigation, selection), the chrome
//! knobs, and the style hooks whose defaults are public `default_*`
//! functions — wrap them or replace them.
//!
//! # Fetch traffic (what a custom store should expect)
//!
//! The grid keeps one contiguous **fetch window** of up to 256 rows
//! (visible slice + margin), refetched when scrolling approaches the
//! window's edge, after every [`transact`](VirtualGrid::transact), and on
//! every spec change. Results are generation-guarded: only the newest
//! in-flight fetch may fill the window; superseded results are discarded.
//! While a fetch is pending, affected rows render as dimmed placeholders.
//! There is no built-in debounce — a store behind a slow query should
//! cache or coalesce on its side.
//!
//! # Design notes
//!
//! A virtualized, multi-column grid over the [`DataSource`] seam: a
//! resizable, scroll-synced header, store-executed sort/filter,
//! identity-keyed selection/focus with keyboard nav, and imperative
//! transactional ingest with tail-follow/freeze.
//!
//! Fetches rows **through the trait** and materializes only the visible slice.
//! Columns render via the [`Column`] seam ([`oriel_core::columns`]), laid out
//! by a shared [`ColumnLayout`]; the header scrollable is kept horizontally
//! aligned with the body via programmatic `scroll_to`.
//!
//! Ingest goes through [`VirtualGrid::transact`]: the app mutates the store
//! imperatively (append/drop/upsert — store semantics, not seam surface) and
//! the grid reacts — count, tail-follow or re-anchor **by row identity**,
//! window refetch. The per-frame rebuild never touches more than the
//! visible slice, no matter the ingest rate.
//!
//! The visible slice is keyed by a **`RowId`-derived hash**: on
//! count-changing rebuilds (ingest appends/drops), `keyed`'s key-driven
//! splice hands each surviving row its own retained widget-tree state
//! instead of whichever slot's state happens to line up. Equal-length
//! rebuilds still diff positionally regardless of key (an upstream iced
//! behavior, pinned by canary tests) — which is why per-row *derived*
//! state stays data-side.

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

use iced::alignment::Vertical;
use iced::widget::{column, container, keyed_column, mouse_area, row, scrollable, space, text};
use iced::widget::scrollable::{AbsoluteOffset, Direction, Scrollbar, Viewport};
use iced::{Color, Element, Length, Padding, Task};
use oriel_core::columns::{Column, ColumnId, ColumnLayout};
use oriel_core::data::DataSource;
use oriel_core::query::{QuerySpec, SortDirection, SortSpec};
use oriel_core::selection::Selection;
use oriel_core::viewport::{RowVirtualizer, ScrollAnchor};

/// ODD on purpose (a measured calibration, not arithmetic): digit/cap ink at 13 px is 9 px tall
/// (odd), and only an odd row height can center odd ink with integer gaps —
/// see `column.rs`'s optical text box. Even heights put every centered cell on
/// a half pixel. (With a [row divider](VirtualGrid::set_row_divider), pick an
/// EVEN height instead — the divider takes the extra pixel.)
pub const DEFAULT_ROW_HEIGHT: f32 = 25.0;
/// Default header-band height.
pub const DEFAULT_HEADER_HEIGHT: f32 = 28.0;
/// Default footer-band height.
pub const DEFAULT_FOOTER_HEIGHT: f32 = 28.0;
/// Width of the resize grab strip on the right of each resizable header cell.
const DEFAULT_HANDLE_WIDTH: f32 = 6.0;
/// Horizontal padding inside each cell.
pub const DEFAULT_CELL_PAD: f32 = 6.0;
/// Scrollbar clearance. Bottom: reserved past the last row so
/// fully-scrolled content clears iced's OVERLAY horizontal bar (its
/// embedded mode is only honored for single-direction scrollables — the
/// `Direction::Both` layout branch ignores `Scrollbar::spacing`,
/// iced_widget-0.14.2/src/scrollable.rs:475-503). Right: the strip hosting
/// the grid's OWN vertical bar ([`crate::scrollbar::VScrollbar`] — iced's
/// has a hardcoded 2 px minimum thumb, useless at data-grid scale; the
/// scrollable's vertical bar is hidden and this one drives it). Matches the
/// default `Scrollbar` breadth (width 10, margin 0).
const SCROLLBAR_GUTTER: f32 = 10.0;
/// Default reorder-flight duration (ag-grid v30 parity again: `animateRows`
/// defaults on there too). `Duration::ZERO` opts out.
const DEFAULT_REORDER_ANIMATION: Duration = Duration::from_millis(250);
const FETCH_ROWS: usize = 256;
const FETCH_MARGIN: usize = 32;
const MAX_VISIBLE_ROWS: usize = 128;
const EDGE: usize = 8;

/// The (owned) element type every column in this grid produces.
///
/// Cells render **display content** of arbitrary richness, but the element
/// is closed over the grid's own [`Message`] type: a cell cannot host a
/// widget that emits *your application's* messages (in-cell buttons/links
/// are deliberately unshipped until a consumer exists). The supported
/// pattern for row-level actions is the row click: match
/// [`Message::RowPressed`] in your `update` before forwarding.
///
/// Cell box contract: each cell is laid out in a fixed box — the column's
/// current width by the grid's row height (minus 1 px when a row divider
/// is set) — vertically centered, **clipped** (grid content never wraps or
/// overflows), with the grid's horizontal `cell_padding` applied outside
/// your element. Content taller than the row is clipped top/bottom. For
/// auto-size, width is measured through
/// [`Column::measure`] — content that `Fill`s has no natural width and
/// opts the column out.
pub type CellElement<Row> = Element<'static, Message<Row>>;
/// A boxed column for this grid — all columns share one `Element` and `Row`.
pub type BoxedColumn<Row> = Box<dyn Column<Element = CellElement<Row>, Row = Row>>;

/// Everything a style hook may key chrome off for one row: its position, its
/// data (`None` = placeholder, not fetched yet), and its interaction state.
/// `Copy`, so hooks can stash it in per-frame closures freely.
#[derive(Debug)]
pub struct RowContext<'a, Row> {
    /// The row's position in the current order.
    pub index: usize,
    /// The row's data — `None` while it is a placeholder.
    pub row: Option<&'a Row>,
    /// Whether the row is selected (identity-keyed).
    pub is_selected: bool,
    /// Whether the row holds the keyboard-nav focus (identity-keyed).
    pub is_focused: bool,
    /// Whether the cursor is over the row (positional, transient).
    pub is_hovered: bool,
}

impl<Row> Clone for RowContext<'_, Row> {
    fn clone(&self) -> Self {
        *self
    }
}
impl<Row> Copy for RowContext<'_, Row> {}

/// A row-chrome hook: full `container` styling per row (background, border,
/// text color). Return a [`Border`](iced::Border) to build row dividers the
/// grid doesn't ship — no fork needed.
pub type RowStyleFn<Row> =
    Box<dyn for<'a> Fn(&iced::Theme, &RowContext<'a, Row>) -> iced::widget::container::Style>;
/// A cell-chrome hook — same power per `(row, column)`; vertical dividers and
/// per-column tinting live here.
pub type CellStyleFn<Row> = Box<
    dyn for<'a> Fn(
        &iced::Theme,
        &RowContext<'a, Row>,
        ColumnId,
    ) -> iced::widget::container::Style,
>;
/// The header-band hook.
pub type HeaderStyleFn = Box<dyn Fn(&iced::Theme) -> iced::widget::container::Style>;
/// The sort-indicator hook: the element rendered beside the sorted column's
/// header label. Direction in, element out — swap in any widget.
pub type SortIndicatorFn<Row> =
    Box<dyn Fn(SortDirection) -> Element<'static, Message<Row>>>;

/// The built-in row chrome — a **public default** (no privileged internals):
/// wrap it and adjust, or replace it outright via
/// [`VirtualGrid::set_row_style`]. Precedence: selected (`primary.weak`) >
/// focused > hovered > zebra stripe, all derived from the theme palette.
pub fn default_row_style<Row>(
    theme: &iced::Theme,
    row: &RowContext<'_, Row>,
) -> iced::widget::container::Style {
    let palette = theme.extended_palette();
    let background = if row.is_selected {
        Some(palette.primary.weak.color.into())
    } else if row.is_focused {
        Some(Color { a: 0.45, ..palette.background.strong.color }.into())
    } else if row.is_hovered {
        Some(Color { a: 0.60, ..palette.background.weak.color }.into())
    } else if row.index % 2 == 1 {
        Some(Color { a: 0.30, ..palette.background.weak.color }.into())
    } else {
        None
    };
    iced::widget::container::Style {
        background,
        ..iced::widget::container::Style::default()
    }
}

/// The built-in cell chrome: none — rows carry the default look. Override via
/// [`VirtualGrid::set_cell_style`] for vertical dividers or column tints.
pub fn default_cell_style<Row>(
    _theme: &iced::Theme,
    _row: &RowContext<'_, Row>,
    _column: ColumnId,
) -> iced::widget::container::Style {
    iced::widget::container::Style::default()
}

/// The built-in header band: a `background.weak` fill. Override via
/// [`VirtualGrid::set_header_style`].
pub fn default_header_style(theme: &iced::Theme) -> iced::widget::container::Style {
    iced::widget::container::Style {
        background: Some(theme.extended_palette().background.weak.color.into()),
        ..iced::widget::container::Style::default()
    }
}

/// The built-in footer band — same fill as the header, bookending the body.
/// Override via [`VirtualGrid::set_footer_style`].
pub fn default_footer_style(theme: &iced::Theme) -> iced::widget::container::Style {
    default_header_style(theme)
}

/// The built-in sort indicator — ag-grid's chevron-headed arrow
/// ([`SortArrow`](crate::arrow::SortArrow), quad-drawn) in the inherited
/// text color, so it always matches the header label beside it. Public
/// like the other chrome defaults: wrap or replace via
/// [`VirtualGrid::set_sort_indicator`].
pub fn default_sort_indicator<Row: 'static>(
    direction: SortDirection,
) -> Element<'static, Message<Row>> {
    match direction {
        SortDirection::Ascending => crate::arrow::SortArrow::up(),
        SortDirection::Descending => crate::arrow::SortArrow::down(),
    }
    .into()
}

/// Messages the grid emits and consumes.
///
/// `#[non_exhaustive]`: new capabilities add variants, so match with a
/// wildcard arm. Most integrations never match at all — they forward
/// everything to [`VirtualGrid::update`].
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum Message<Row> {
    /// The body scrollable moved; carries its absolute offset (x and y).
    BodyScrolled(AbsoluteOffset),
    /// A fetch resolved: `rows` start at index `start`.
    Fetched {
        /// The fetch generation this result belongs to. Results from a
        /// superseded generation (an older scroll position or an older spec)
        /// are ignored instead of clobbering the window — the stale-fetch
        /// guard (a degenerate form of request coalescing).
        generation: u64,
        /// Index of the first fetched row.
        start: usize,
        /// The fetched rows.
        rows: Vec<Row>,
    },
    /// A body row was clicked; `index` is its position in the current order.
    ///
    /// On [`update`](VirtualGrid::update), a click on a fetched row
    /// **single-selects** it ([`Selection`] holds exactly that row) and
    /// moves keyboard focus to it; a click on a not-yet-fetched placeholder
    /// row does nothing. That is the whole v1 gesture policy — ctrl/shift
    /// multi-select gestures are unshipped (the underlying [`Selection`] is
    /// a set; drive multi-selection programmatically via
    /// [`selection_mut`](VirtualGrid::selection_mut)). To react to clicks
    /// yourself (master-detail panes), match this variant in your `update`
    /// before forwarding, or read
    /// [`selection`](VirtualGrid::selection)/[`focus`](VirtualGrid::focus)
    /// after forwarding.
    RowPressed {
        /// Positional index of the clicked row.
        index: usize,
    },
    /// The cursor entered a body row (drives the hover highlight).
    RowHovered {
        /// Positional index of the hovered row.
        index: usize,
    },
    /// The cursor left a body row.
    RowUnhovered {
        /// Positional index of the row the cursor left.
        index: usize,
    },
    /// A column is being resized: `delta` px from the drag origin.
    ColumnResizing {
        /// Positional index of the column.
        index: usize,
        /// Pixel delta from the drag origin.
        delta: f32,
    },
    /// A column resize ended; commit the width.
    ColumnResized {
        /// Positional index of the column.
        index: usize,
    },
    /// A resize grip was double-clicked: auto-size the column to its content.
    ColumnAutoSizeRequested {
        /// Positional index of the column.
        index: usize,
    },
    /// The grid's own vertical scrollbar (the min-thumb replacement for the
    /// scrollable's hidden one) was dragged or rail-clicked to an absolute
    /// y offset.
    ScrollbarDragged(f32),
    /// The phantom measurer reported a column's natural content width (the
    /// widest of its header — including the sort indicator when sorted —
    /// visible cells, and footer, without cell padding).
    ColumnMeasured {
        /// Positional index of the column.
        index: usize,
        /// Measured natural width, px.
        width: f32,
    },
    /// A sortable column's header was clicked; toggle sorting by it.
    HeaderPressed {
        /// Positional index of the column.
        index: usize,
    },
}

/// A virtualized, multi-column grid over a [`DataSource`].
pub struct VirtualGrid<S: DataSource> {
    store: S,
    columns: Vec<BoxedColumn<S::Row>>,
    layout: ColumnLayout,
    virt: RowVirtualizer,
    /// The current sort/filter spec — core-owned view state; the
    /// store executes it. Get/set via [`spec`](Self::spec)/[`set_spec`](Self::set_spec).
    spec: QuerySpec,
    /// Selected rows, by identity — survives re-sort/re-virtualization by
    /// construction. Settable from outside via
    /// [`selection_mut`](Self::selection_mut).
    selection: Selection<S::RowId>,
    /// The keyboard-nav cursor, by **identity** ("state lives on the
    /// `RowId`"), so re-sorting never leaves the cursor highlighting whatever
    /// row happens to occupy the old slot, and nav continues *from the focused
    /// row* in the new order when it is still within the fetch window. Its
    /// position is resolved opportunistically against the window
    /// ([`focus_index`](Self::focus_index)); when unresolvable, nav re-anchors
    /// at the top visible row — unless the app opts into off-window
    /// restoration ([`set_focus_restoration`](Self::set_focus_restoration)).
    focus: Option<S::RowId>,
    /// Opt-in: resolve an off-window focus through
    /// [`DataSource::index_of`] instead of re-anchoring nav at the top visible
    /// row. An **app choice**, never automatic — it makes nav jump the
    /// viewport to wherever the focused row went.
    focus_restoration: bool,
    total_rows: usize,
    /// Columns (positional indices) awaiting an auto-size measurement. For
    /// each pending column the view carries a phantom
    /// [`Measure`](crate::measure) over its header (with sort indicator
    /// when sorted) + visible cells + footer; each report commits through
    /// `ColumnLayout::set_width` and clears its entry. A grip double-click
    /// queues one column; [`auto_size_all`](Self::auto_size_all) queues
    /// every column — all measured in a single layout pass.
    auto_size: BTreeSet<usize>,
    /// The hovered row's position — deliberately **positional and transient**
    /// (it follows the cursor, not the data; a stale index self-corrects on
    /// the next cursor event). Never part of durable view state.
    hovered: Option<usize>,
    scroll_offset: f32,
    /// The last offset the body scrollable *reported* (as opposed to
    /// [`scroll_offset`](Self::scroll_offset), which is what the grid last
    /// commanded/synced). Reports are not only user scrolls — see the
    /// receding-report logic in `BodyScrolled`.
    last_scroll_report: f32,
    /// Accumulated upward drift across consecutive receding reports —
    /// precision touchpads recede in sub-pixel steps that a per-report
    /// 1 px test never sees. Reset by any non-receding
    /// report.
    recession: f32,
    /// The fetch generation whose result currently fills
    /// [`window_rows`](Self::window_rows). Flight scheduling waits until
    /// this catches [`fetch_generation`](Self::fetch_generation) — with a
    /// genuinely async store, scheduling against the pre-mutation window
    /// would compute every delta from stale indices.
    window_generation: u64,
    /// Bumped on every auto-size request; stamps the phantom measurers so a
    /// re-queue that lands in the same message batch as a drain still
    /// re-publishes (the one-shot flag alone needed an idle frame between —
    /// a wedge: the fit would stay pending forever).
    auto_size_epoch: u64,
    /// Tail-follow: when `true`, every [`transact`](Self::transact)
    /// auto-scrolls to the newest rows. Freeze = `set_follow(false)` — it halts
    /// the auto-scroll, never the ingest. A manual scroll away from the bottom
    /// freezes automatically (the grid must not fight the user for the scroll
    /// position); re-engaging is always explicit.
    follow: bool,
    /// Last body-viewport height observed during layout; drives page-nav and
    /// ensure-visible math. Interior-mutable because `view` is `&self`.
    viewport_height: Cell<f32>,
    /// Monotonic fetch generation — see [`Message::Fetched::generation`].
    fetch_generation: u64,
    window_start: usize,
    window_rows: Vec<S::Row>,
    header_id: iced::widget::Id,
    body_id: iced::widget::Id,
    footer_id: iced::widget::Id,
    /// Whether any column provides a footer — structural, checked once at
    /// construction; the footer strip renders (and scroll-syncs) only then.
    has_footer: bool,
    // Chrome knobs: geometry values plus the style hooks. The
    // hooks default to the public `default_*_style` functions — integrators
    // wrap or replace them (dividers, row tints, custom palettes) without
    // touching the grid.
    header_height: f32,
    footer_height: f32,
    cell_padding: f32,
    handle_width: f32,
    row_style: RowStyleFn<S::Row>,
    cell_style: CellStyleFn<S::Row>,
    header_style: HeaderStyleFn,
    footer_style: HeaderStyleFn,
    sort_indicator: SortIndicatorFn<S::Row>,
    /// A 1 px line under every row, carved OUT of the row height (pitch
    /// unchanged) — see [`set_row_divider`](Self::set_row_divider).
    row_divider: Option<Color>,
    /// A 1 px line at each body cell's right edge (except the last column),
    /// carved out of the cell width — see
    /// [`set_column_divider`](Self::set_column_divider).
    column_divider: Option<Color>,
    /// The frame rules' color (the 1 px separators under the header and
    /// above the footer). `None` = the ambient theme's rule style. This is
    /// what a [`GridTheme`](crate::theme::GridTheme)'s `border` drives.
    rule_color: Option<Color>,
    /// Reorder-flight duration; `ZERO` = off (see
    /// [`set_reorder_animation`](Self::set_reorder_animation)).
    reorder_animation: Duration,
    /// Live flights by row identity — screen-space offsets easing to zero.
    flights: HashMap<S::RowId, crate::slide::Flight>,
    /// Live enter-fades by row identity — rows that newly appeared in the
    /// viewport during an upheaval materialize from the background (only the
    /// timing of the [`Flight`](crate::slide::Flight) is used).
    fades: HashMap<S::RowId, crate::slide::Flight>,
    /// The flight easing curve (default: normalized low-pass; see
    /// [`set_reorder_easing`](Self::set_reorder_easing)).
    reorder_easing: crate::slide::Easing,
    /// Old on-screen positions captured before an upheaval, waiting for the
    /// re-derived window; tagged with the fetch generation that will fill it
    /// (a superseding fetch discards them).
    pending_flights: Option<(u64, Vec<(S::RowId, f32)>)>,
}

impl<S: DataSource> VirtualGrid<S> {
    /// Creates a grid over `store` rendered by `columns`, plus the initial fetch
    /// [`Task`]. Column widths/order come from the columns' sizing policies.
    pub fn new(store: S, columns: Vec<BoxedColumn<S::Row>>) -> (Self, Task<Message<S::Row>>) {
        let total_rows = store.row_count().lower_bound();
        let layout = ColumnLayout::new(columns.iter().map(|c| (c.id(), c.sizing())));
        let has_footer = columns.iter().any(|c| c.footer().is_some());
        let mut grid = Self {
            store,
            columns,
            layout,
            virt: RowVirtualizer::new(DEFAULT_ROW_HEIGHT),
            spec: QuerySpec::default(),
            selection: Selection::new(),
            focus: None,
            focus_restoration: false,
            total_rows,
            auto_size: BTreeSet::new(),
            hovered: None,
            scroll_offset: 0.0,
            last_scroll_report: 0.0,
            recession: 0.0,
            window_generation: 0,
            auto_size_epoch: 0,
            follow: false,
            viewport_height: Cell::new(0.0),
            fetch_generation: 0,
            window_start: 0,
            window_rows: Vec::new(),
            header_id: iced::widget::Id::unique(),
            body_id: iced::widget::Id::unique(),
            footer_id: iced::widget::Id::unique(),
            has_footer,
            header_height: DEFAULT_HEADER_HEIGHT,
            footer_height: DEFAULT_FOOTER_HEIGHT,
            cell_padding: DEFAULT_CELL_PAD,
            handle_width: DEFAULT_HANDLE_WIDTH,
            row_style: Box::new(default_row_style),
            cell_style: Box::new(default_cell_style),
            header_style: Box::new(default_header_style),
            footer_style: Box::new(default_footer_style),
            sort_indicator: Box::new(default_sort_indicator),
            row_divider: None,
            column_divider: None,
            rule_color: None,
            reorder_animation: DEFAULT_REORDER_ANIMATION,
            flights: HashMap::new(),
            fades: HashMap::new(),
            reorder_easing: Rc::new(crate::slide::low_pass_easing),
            pending_flights: None,
        };
        let init = grid.fetch_task(0);
        (grid, init)
    }

    /// The current selection (by row identity).
    #[must_use]
    pub fn selection(&self) -> &Selection<S::RowId> {
        &self.selection
    }

    /// Mutable access to the selection — the programmatic entry point (linked
    /// selection, presets, "select these rows from outside"). The next render
    /// reflects whatever is set here.
    pub fn selection_mut(&mut self) -> &mut Selection<S::RowId> {
        &mut self.selection
    }

    /// Read access to the underlying store — rows for a master-detail pane,
    /// `index_of` for app-side policies. All **mutation** goes through
    /// [`transact`](Self::transact), so the grid always observes the change.
    #[must_use]
    pub fn store(&self) -> &S {
        &self.store
    }

    /// Whether the grid is tail-following (auto-scrolling to the newest rows
    /// on every transaction).
    #[must_use]
    pub fn follow(&self) -> bool {
        self.follow
    }

    /// Enables or disables tail-follow. The **freeze toggle** is
    /// `set_follow(false)`: it halts the auto-scroll only — ingest keeps
    /// flowing through [`transact`](Self::transact) untouched. Enabling jumps
    /// to the tail immediately. The grid also freezes itself when the user
    /// scrolls away from the bottom (it never fights for the scroll position);
    /// scrolling back down does **not** re-engage — re-enabling is explicit,
    /// so watch [`follow`](Self::follow) to keep a toggle widget honest.
    pub fn set_follow(&mut self, follow: bool) -> Task<Message<S::Row>> {
        self.follow = follow;
        if follow {
            self.jump_to_tail()
        } else {
            Task::none()
        }
    }

    /// Applies an imperative transaction to the store — **the ingest entry
    /// point**, and the change-notification path:
    /// the grid owns the store, so routing every mutation through here is what
    /// lets it react without any subscription machinery.
    ///
    /// The closure gets `&mut S` and calls whatever transaction methods the
    /// store exposes (append/drop/upsert/clear — store semantics, not seam
    /// surface). The store must uphold the seam's post-mutation consistency
    /// contract (see [`DataSource`]); the grid then:
    ///
    /// - re-reads the row count;
    /// - if following, scrolls to the tail; otherwise **re-anchors by row
    ///   identity**: the first previously-visible row that still
    ///   exists keeps its on-screen position, so appends/drops above the
    ///   viewport never make visible content jump. When no visible row
    ///   survived (or the store's `index_of` can't answer), it degrades to the
    ///   old offset, clamped — which is continuous in the ring-drain case,
    ///   where the anchor index was already sliding toward zero;
    /// - refetches the window — synchronously when the store's future is
    ///   already ready (resident stores: no placeholder flicker at ingest
    ///   rates), falling back to the async task path otherwise.
    ///
    /// Selection and focus are **not** pruned: both are identity-keyed, so ids
    /// of departed rows simply stop resolving (and resolve again if the rows
    /// return). Pruning is app policy, built from the exposed primitives:
    /// `grid.selection_mut().retain(|id| grid.store().index_of(id).is_some())`.
    ///
    /// # Example
    ///
    /// ```
    /// # use oriel_core::{columns::ColumnId, data::VecStore};
    /// # use oriel_iced::grid::{BoxedColumn, VirtualGrid};
    /// # use oriel_iced::column::TextColumn;
    /// # #[derive(Clone, Debug)] struct Row { id: u64, name: String }
    /// # fn key(r: &Row) -> u64 { r.id }
    /// # let store = VecStore::new(
    /// #     (0..100u64).map(|id| Row { id, name: format!("row {id}") }).collect(),
    /// #     key as fn(&Row) -> u64,
    /// # );
    /// # let columns: Vec<BoxedColumn<Row>> =
    /// #     vec![Box::new(TextColumn::new(ColumnId(1), "Name", 200.0, |r: &Row| r.name.clone()))];
    /// # let (mut grid, _init) = VirtualGrid::new(store, columns);
    /// // One ingest tick = ONE transaction; mutate the store through its own
    /// // API (the grid never learns mutation shapes):
    /// let task = grid.transact(|store| {
    ///     store.append(vec![Row { id: 100, name: "fresh".into() }]);
    ///     store.drop_front(1); // ring semantics, if the app wants them
    /// });
    /// // …return `task` (mapped into your message type) from `update`.
    /// # assert_eq!(grid.total_rows(), 100);
    /// ```
    pub fn transact(&mut self, mutate: impl FnOnce(&mut S)) -> Task<Message<S::Row>> {
        let snapshot = self.flight_snapshot();
        let task = self.transact_inner(mutate);
        self.pending_flights = snapshot.map(|s| (self.fetch_generation, s));
        self.try_schedule_flights();
        task
    }

    fn transact_inner(&mut self, mutate: impl FnOnce(&mut S)) -> Task<Message<S::Row>> {
        // Capture the anchor BEFORE the mutation: the top visible row's
        // identity, plus the rows visible below it as fallback candidates.
        let anchor = self.virt.anchor_at(self.scroll_offset);
        let candidates: Vec<S::RowId> = if self.follow {
            Vec::new()
        } else {
            let visible = self.virt.rows_spanned(self.viewport_height.get());
            (anchor.row..anchor.row.saturating_add(visible))
                .filter_map(|i| self.cached_row(i).map(|row| self.store.row_id(row)))
                .collect()
        };

        mutate(&mut self.store);
        self.total_rows = self.store.row_count().lower_bound();

        if self.follow {
            return self.jump_to_tail();
        }

        let new_offset = candidates
            .iter()
            .find_map(|id| self.store.index_of(id))
            .map(|index| {
                self.virt.flat_offset_of(ScrollAnchor { row: index, offset_px: anchor.offset_px })
            })
            .unwrap_or(self.scroll_offset)
            .clamp(0.0, self.max_scroll());
        let scroll = (new_offset != self.scroll_offset).then(|| {
            self.scroll_offset = new_offset;
            iced::widget::operation::scroll_to(
                self.body_id.clone(),
                AbsoluteOffset { x: self.layout.h_scroll(), y: new_offset },
            )
        });
        // Unconditional refetch: even at an unchanged anchor the rows under
        // the window may have changed (updates, shifted indices).
        let fetch = self.fetch_now(self.virt.anchor_at(new_offset).row);
        match scroll {
            Some(scroll) => Task::batch([scroll, fetch]),
            None => fetch,
        }
    }

    /// The keyboard-nav cursor — the focused row's identity, if any.
    #[must_use]
    pub fn focus(&self) -> Option<&S::RowId> {
        self.focus.as_ref()
    }

    /// The focused row's position in the current order, resolved against the
    /// fetch window. `None` means the cursor exists but its row is currently
    /// beyond the window (e.g. sorted far away) — nav will re-anchor at the
    /// top visible row. With
    /// [`set_focus_restoration(true)`](Self::set_focus_restoration) the miss
    /// falls back to [`DataSource::index_of`], so an off-window focus still
    /// resolves (and nav continues from it) whenever the store can answer.
    #[must_use]
    pub fn focus_index(&self) -> Option<usize> {
        let focus = self.focus.as_ref()?;
        self.window_rows
            .iter()
            .position(|row| self.store.row_id(row) == *focus)
            .map(|offset| self.window_start + offset)
            .or_else(|| self.focus_restoration.then(|| self.store.index_of(focus)).flatten())
    }

    /// Opts into **focus restoration** — "the viewport chases the focused
    /// row" (default: off). When enabled:
    ///
    /// - a focus that lies outside the fetch window (sorted far away, slid
    ///   along by ingest) still resolves through [`DataSource::index_of`],
    ///   and keyboard nav continues *from it*, jumping the viewport to
    ///   wherever the row went (instead of re-anchoring at the top visible
    ///   row);
    /// - a spec change keeps a surviving focused row in view across the
    ///   reorder (instead of the default leave-the-scrollbar-alone).
    ///
    /// This is an integrator/app **choice**, never automatic: the
    /// chase is right for master-detail-style flows and wrong for others, and
    /// for stores whose `index_of` stays the tolerant default `None` it
    /// simply never fires.
    pub fn set_focus_restoration(&mut self, enabled: bool) {
        self.focus_restoration = enabled;
    }

    /// Whether off-window focus restoration is enabled.
    #[must_use]
    pub fn focus_restoration(&self) -> bool {
        self.focus_restoration
    }

    // --- chrome knobs (a knob for everything that makes sense;
    // the style hooks are the no-cliffs escape hatch — dividers, row tints,
    // custom palettes all land integrator-side without forking the grid) ---

    /// Sets the row height, logical px (default 25 — deliberately **ODD**;
    /// see `DEFAULT_ROW_HEIGHT`'s parity note. Themes with a row divider use
    /// EVEN heights: the 1 px line is carved out, leaving an odd content
    /// box). The viewport **re-anchors by row** across the change: the rows
    /// on screen stay the rows on screen — a density change must never
    /// teleport the user (the row-space anchor is the position of truth;
    /// the pixel offset is derived). While tail-following, the tail stays
    /// pinned instead. Returns the follow-up [`Task`] — feed it to iced.
    pub fn set_row_height(&mut self, px: f32) -> Task<Message<S::Row>> {
        if px == self.virt.row_height() {
            return Task::none();
        }
        let anchor = self.scroll_anchor();
        // The sub-row offset is in OLD-height pixels; scale it so the
        // anchor row keeps its on-screen fraction.
        let scale = px / self.virt.row_height();
        self.virt = RowVirtualizer::new(px);
        if self.follow {
            return self.jump_to_tail();
        }
        let target = ScrollAnchor { row: anchor.row, offset_px: anchor.offset_px * scale };
        let offset = self.virt.flat_offset_of(target).clamp(0.0, self.max_scroll());
        let scroll = (offset != self.scroll_offset).then(|| {
            self.scroll_offset = offset;
            iced::widget::operation::scroll_to(
                self.body_id.clone(),
                AbsoluteOffset { x: self.layout.h_scroll(), y: offset },
            )
        });
        let fetch = self.fetch_now(self.virt.anchor_at(offset).row);
        match scroll {
            Some(scroll) => Task::batch([scroll, fetch]),
            None => fetch,
        }
    }

    /// Sets the header height, logical px (default 28).
    pub fn set_header_height(&mut self, px: f32) {
        self.header_height = px;
    }

    /// Sets the footer height, logical px (default 28; only rendered when a
    /// column provides a footer).
    pub fn set_footer_height(&mut self, px: f32) {
        self.footer_height = px;
    }

    /// Sets the horizontal cell padding, logical px (default 6).
    pub fn set_cell_padding(&mut self, px: f32) {
        self.cell_padding = px;
    }

    /// Sets the resize grab-strip width, logical px (default 6).
    pub fn set_handle_width(&mut self, px: f32) {
        self.handle_width = px;
    }

    /// Replaces the row-chrome hook (default: [`default_row_style`]). Wrap
    /// the default to keep the built-in precedence and adjust on top, or
    /// replace it outright — this is the no-cliffs escape for any row look
    /// the grid doesn't ship.
    ///
    /// # Example — a data-driven tint over the default chrome
    ///
    /// ```
    /// # use oriel_core::{columns::ColumnId, data::VecStore};
    /// # use oriel_iced::grid::{self, BoxedColumn, VirtualGrid};
    /// # use oriel_iced::column::TextColumn;
    /// # #[derive(Clone, Debug)] struct Row { id: u64, alarming: bool }
    /// # fn key(r: &Row) -> u64 { r.id }
    /// # let store = VecStore::new(
    /// #     (0..100u64).map(|id| Row { id, alarming: id % 7 == 0 }).collect(),
    /// #     key as fn(&Row) -> u64,
    /// # );
    /// # let columns: Vec<BoxedColumn<Row>> =
    /// #     vec![Box::new(TextColumn::new(ColumnId(1), "#", 80.0, |r: &Row| r.id.to_string()))];
    /// # let (mut grid, _init) = VirtualGrid::new(store, columns);
    /// grid.set_row_style(|theme, ctx| {
    ///     // Keep selection/focus/hover/zebra precedence, tint on top.
    ///     let mut style = grid::default_row_style(theme, ctx);
    ///     if !ctx.is_selected && ctx.row.is_some_and(|r| r.alarming) {
    ///         let danger = theme.extended_palette().danger.base.color;
    ///         style.background = Some(iced::Color { a: 0.08, ..danger }.into());
    ///     }
    ///     style
    /// });
    /// ```
    pub fn set_row_style(
        &mut self,
        style: impl for<'a> Fn(&iced::Theme, &RowContext<'a, S::Row>) -> iced::widget::container::Style
        + 'static,
    ) {
        self.row_style = Box::new(style);
    }

    /// Replaces the cell-chrome hook (default: [`default_cell_style`], which
    /// is no chrome at all). Vertical dividers and per-column tints go here.
    pub fn set_cell_style(
        &mut self,
        style: impl for<'a> Fn(
            &iced::Theme,
            &RowContext<'a, S::Row>,
            ColumnId,
        ) -> iced::widget::container::Style
        + 'static,
    ) {
        self.cell_style = Box::new(style);
    }

    /// Replaces the header-band hook (default: [`default_header_style`]).
    pub fn set_header_style(
        &mut self,
        style: impl Fn(&iced::Theme) -> iced::widget::container::Style + 'static,
    ) {
        self.header_style = Box::new(style);
    }

    /// Replaces the footer-band hook (default: [`default_footer_style`]).
    pub fn set_footer_style(
        &mut self,
        style: impl Fn(&iced::Theme) -> iced::widget::container::Style + 'static,
    ) {
        self.footer_style = Box::new(style);
    }

    /// Replaces the sort-indicator hook (default: [`default_sort_indicator`]).
    /// The returned element is placed right of the sorted column's header
    /// label, vertically centered.
    pub fn set_sort_indicator(
        &mut self,
        indicator: impl Fn(SortDirection) -> Element<'static, Message<S::Row>> + 'static,
    ) {
        self.sort_indicator = Box::new(indicator);
    }

    /// Sets the horizontal **row divider**: a single 1 px line under every
    /// row (default: `None` — no line; the built-in look separates rows by
    /// zebra stripes instead). The line is carved OUT of the row height, so
    /// the row pitch — and all virtualization math — is unchanged. Parity
    /// note: with a divider, pick an **even** row height so the remaining
    /// content box stays odd and cell ink centers on integer pixels (the
    /// same chain that makes the default height odd).
    pub fn set_row_divider(&mut self, color: Option<Color>) {
        self.row_divider = color;
    }

    /// Sets the vertical **column divider**: a single 1 px line at the right
    /// edge of every body cell except the last column's (default: `None`).
    /// Carved out of the cell's width, so column positions stay aligned with
    /// the header. Full spreadsheet-style gridlines = both dividers set.
    pub fn set_column_divider(&mut self, color: Option<Color>) {
        self.column_divider = color;
    }

    /// Auto-sizes **every** column to its content (ag-grid's
    /// `autoSizeAllColumns`): queues a measurement per column; all are
    /// measured in the next layout pass and commit through the same
    /// policy-clamped path as a grip double-click. Columns whose cells ask
    /// to `Fill` have no natural width and are left alone; fixed columns
    /// clamp back to their fixed width. [`GridTheme`](crate::theme::GridTheme)
    /// application calls this — a theme changes the metrics columns were
    /// fitted under (padding, density), so the fit re-derives.
    pub fn auto_size_all(&mut self) {
        self.auto_size.extend(0..self.columns.len());
        self.auto_size_epoch += 1;
    }

    /// Sets the color of the grid's **frame rules** — the 1 px separators
    /// under the header band and above the footer strip (default: `None`,
    /// the ambient theme's rule style). Themes drive this from their
    /// structural border color.
    pub fn set_rule_color(&mut self, color: Option<Color>) {
        self.rule_color = color;
    }

    /// The current row height, logical px.
    #[must_use]
    pub fn row_height(&self) -> f32 {
        self.virt.row_height()
    }

    /// The current header-band height, logical px.
    #[must_use]
    pub fn header_height(&self) -> f32 {
        self.header_height
    }

    /// The current footer-strip height, logical px.
    #[must_use]
    pub fn footer_height(&self) -> f32 {
        self.footer_height
    }

    /// The current horizontal cell padding, logical px.
    #[must_use]
    pub fn cell_padding(&self) -> f32 {
        self.cell_padding
    }

    /// The current resize grab-strip width, logical px.
    #[must_use]
    pub fn handle_width(&self) -> f32 {
        self.handle_width
    }

    /// Sets the row-animation duration (ag-grid's `animateRows` pair):
    /// rows visible before AND after an upheaval **glide** from their old
    /// on-screen position; rows that newly entered the viewport **fade in**
    /// from the background. **Default: 250 ms, on** (v30 parity);
    /// `Duration::ZERO` disables both.
    ///
    /// Flights are computed in **screen space** against a resting viewport:
    /// frozen-anchor ingest holds rows at constant screen positions (zero
    /// delta — nothing animates, even at 60 Hz), and while **tail-following,
    /// flights are suppressed** — there the viewport itself moves with the
    /// stream, and animating that would smear every visible row every tick.
    /// The enter-fade is motion-free, so it stays on under follow: appended
    /// rows materialize at the tail.
    pub fn set_reorder_animation(&mut self, duration: Duration) {
        self.reorder_animation = duration;
        if duration.is_zero() {
            self.flights.clear();
            self.fades.clear();
            self.pending_flights = None;
        }
    }

    /// Replaces the flight easing curve — any `f(t)` with `f(0) = 0` and
    /// `f(1) = 1` (the deadline contract: every flight lands at exactly
    /// `t[N]`, whatever the curve does before it). Default:
    /// [`slide::low_pass_easing`](crate::slide::low_pass_easing) — a
    /// normalized first-order low-pass response;
    /// [`slide::ease_out_cubic`](crate::slide::ease_out_cubic) is provided
    /// as an alternative.
    pub fn set_reorder_easing(&mut self, easing: impl Fn(f32) -> f32 + 'static) {
        self.reorder_easing = Rc::new(easing);
    }

    /// Whether any row animation (flight or enter-fade) is in progress.
    #[must_use]
    pub fn animating(&self) -> bool {
        let now = Instant::now();
        self.flights.values().any(|f| f.is_live(now))
            || self.fades.values().any(|f| f.is_live(now))
    }

    /// Captures visible rows' current on-screen y — the "before" half of
    /// row-animation scheduling. `None` when animation is off or nothing is
    /// cached (a boot fill therefore never animates: there is no prior
    /// visible state to animate FROM).
    fn flight_snapshot(&self) -> Option<Vec<(S::RowId, f32)>> {
        if self.reorder_animation.is_zero() {
            return None;
        }
        let anchor = self.virt.anchor_at(self.scroll_offset);
        let visible = self.virt.rows_spanned(self.viewport_height.get());
        let mut snapshot = Vec::new();
        for i in anchor.row..anchor.row.saturating_add(visible) {
            if let Some(row) = self.cached_row(i) {
                snapshot.push((self.store.row_id(row), self.virt.screen_y(i, self.scroll_offset)));
            }
        }
        (!snapshot.is_empty()).then_some(snapshot)
    }

    /// The "after" half: once the re-derived window is filled (synchronously
    /// by a transaction, or by the matching [`Message::Fetched`] for spec
    /// changes; a superseding fetch, e.g. a scroll, discards the capture):
    ///
    /// - rows present on BOTH sides get a **flight** from their old screen
    ///   position — unless tail-following, where the viewport itself moves
    ///   with the stream and per-tick re-flighting would smear every row
    ///   (observed on-screen with feed + follow both live);
    /// - rows that newly ENTERED the viewport get an **enter-fade**,
    ///   materializing from the background — motion-free, so it composes
    ///   with a moving viewport: the tail's soft edge under feed+follow.
    fn try_schedule_flights(&mut self) {
        let Some((generation, _)) = self.pending_flights.as_ref() else {
            return;
        };
        if *generation != self.fetch_generation {
            self.pending_flights = None;
            return;
        }
        if self.window_generation != self.fetch_generation {
            // The fill for THIS generation hasn't landed (async store, or a
            // spec change awaiting its fetch) — scheduling now would compute
            // every delta from the stale pre-mutation window. The matching
            // `Fetched` re-enters here.
            return;
        }
        let Some((_, old)) = self.pending_flights.take() else {
            return;
        };
        let old: HashMap<S::RowId, f32> = old.into_iter().collect();
        let now = Instant::now();
        let duration = self.reorder_animation;
        let anchor = self.virt.anchor_at(self.scroll_offset);
        let visible = self.virt.rows_spanned(self.viewport_height.get());
        self.flights.retain(|_, f| f.is_live(now));
        self.fades.retain(|_, f| f.is_live(now));
        for i in anchor.row..anchor.row.saturating_add(visible) {
            if let Some(row) = self.cached_row(i) {
                let id = self.store.row_id(row);
                match old.get(&id) {
                    Some(old_y) if !self.follow => {
                        let delta = old_y - self.virt.screen_y(i, self.scroll_offset);
                        if delta.abs() >= 0.5 {
                            self.flights.insert(
                                id,
                                crate::slide::Flight { from: delta, started: now, duration },
                            );
                        }
                    }
                    Some(_) => {} // both-sides row while following: no motion
                    None => {
                        // Newly visible: materialize from the background.
                        self.fades.insert(
                            id,
                            crate::slide::Flight { from: 0.0, started: now, duration },
                        );
                    }
                }
            }
        }
    }

    /// The current fetch generation (matches [`Message::Fetched::generation`]
    /// for the newest in-flight fetch). Exposed for integrations and tests
    /// that construct `Fetched` messages themselves.
    #[must_use]
    pub fn fetch_generation(&self) -> u64 {
        self.fetch_generation
    }

    /// The contiguous range of row indices currently held in the fetch window.
    #[must_use]
    pub fn window_range(&self) -> core::ops::Range<usize> {
        self.window_start..self.window_start + self.window_rows.len()
    }

    /// The current sort/filter spec — the value presets get/persist. This
    /// **includes header-click sorts**, so it is also the observation point
    /// for user-driven sort changes: compare `spec().sort` across `update`
    /// calls, or match [`Message::HeaderPressed`] before forwarding and
    /// predict the outcome with
    /// [`QuerySpec::cycled_sort`](oriel_core::query::QuerySpec::cycled_sort).
    #[must_use]
    pub fn spec(&self) -> &QuerySpec {
        &self.spec
    }

    /// The current (post-filter) row count.
    #[must_use]
    pub fn total_rows(&self) -> usize {
        self.total_rows
    }

    /// The column layout — widths, order, horizontal scroll — the
    /// persistable value. Read it to persist; restore through
    /// [`column_layout_mut`](Self::column_layout_mut).
    ///
    /// Note: the shipped grid **owns** its layout — two grids cannot yet
    /// share one handle (held open for split views); until then, keep
    /// sibling grids in lockstep by forwarding each one's
    /// [`ColumnResizing`](Message::ColumnResizing)/[`ColumnResized`](Message::ColumnResized)
    /// messages to the other.
    #[must_use]
    pub fn column_layout(&self) -> &ColumnLayout {
        &self.layout
    }

    /// Mutable access to the column layout — the programmatic entry point
    /// for **restoring persisted widths**
    /// ([`ColumnLayout::set_width`] is policy-clamped per column) or
    /// driving widths from outside. The next render reflects whatever is
    /// set here.
    ///
    /// ```
    /// # use oriel_core::{columns::ColumnId, data::VecStore};
    /// # use oriel_iced::grid::{BoxedColumn, VirtualGrid};
    /// # use oriel_iced::column::TextColumn;
    /// # #[derive(Clone, Debug)] struct Row { id: u64 }
    /// # fn key(r: &Row) -> u64 { r.id }
    /// # let store = VecStore::new((0..10).map(|id| Row { id }).collect(), key as fn(&Row) -> u64);
    /// # let columns: Vec<BoxedColumn<Row>> =
    /// #     vec![Box::new(TextColumn::new(ColumnId(1), "#", 80.0, |r: &Row| r.id.to_string()))];
    /// # let (mut grid, _init) = VirtualGrid::new(store, columns);
    /// // Persist…
    /// let widths: Vec<f32> = grid.column_layout().placements().iter().map(|p| p.width).collect();
    /// // …restore (e.g. next session):
    /// for (index, width) in widths.iter().enumerate() {
    ///     grid.column_layout_mut().set_width(index, *width);
    /// }
    /// ```
    pub fn column_layout_mut(&mut self) -> &mut ColumnLayout {
        &mut self.layout
    }

    /// The scroll position of truth, in row space: the first
    /// row the viewport's top edge touches plus the sub-row pixel offset.
    /// Exposed state — hold it to observe anchoring, persist it and restore
    /// via [`scroll_to_anchor`](Self::scroll_to_anchor).
    ///
    /// # Example — a bookmark that survives churn
    ///
    /// ```
    /// # use oriel_core::{columns::ColumnId, data::VecStore};
    /// # use oriel_iced::grid::{BoxedColumn, VirtualGrid};
    /// # use oriel_iced::column::TextColumn;
    /// # #[derive(Clone, Debug)] struct Row { id: u64, name: String }
    /// # fn key(r: &Row) -> u64 { r.id }
    /// # let store = VecStore::new(
    /// #     (0..1000u64).map(|id| Row { id, name: format!("row {id}") }).collect(),
    /// #     key as fn(&Row) -> u64,
    /// # );
    /// # let columns: Vec<BoxedColumn<Row>> =
    /// #     vec![Box::new(TextColumn::new(ColumnId(1), "Name", 200.0, |r: &Row| r.name.clone()))];
    /// # let (mut grid, _init) = VirtualGrid::new(store, columns);
    /// let bookmark = grid.scroll_anchor(); // ROW-space, not pixels
    /// // …the stream appends thousands of rows, the user wanders off…
    /// let task = grid.scroll_to_anchor(bookmark); // back to the same row
    /// # let _ = task;
    /// ```
    #[must_use]
    pub fn scroll_anchor(&self) -> ScrollAnchor {
        self.virt.anchor_at(self.scroll_offset)
    }

    /// Jumps the viewport so `anchor`'s row sits at the top edge with its
    /// sub-row offset — the **restore** half of scroll persistence
    /// ([`scroll_anchor`](Self::scroll_anchor) is the read half), and the
    /// "jump to row" primitive in general. Clamped to the scrollable range;
    /// refetches the window (synchronously when the store is ready). Freezes
    /// tail-follow: an explicit jump is the app taking the viewport
    /// somewhere, and the grid never fights that. Returns the follow-up
    /// [`Task`].
    pub fn scroll_to_anchor(&mut self, anchor: ScrollAnchor) -> Task<Message<S::Row>> {
        self.follow = false;
        let offset = self.virt.flat_offset_of(anchor).clamp(0.0, self.max_scroll());
        let scroll = (offset != self.scroll_offset).then(|| {
            self.scroll_offset = offset;
            iced::widget::operation::scroll_to(
                self.body_id.clone(),
                AbsoluteOffset { x: self.layout.h_scroll(), y: offset },
            )
        });
        let fetch = self.fetch_now(self.virt.anchor_at(offset).row);
        match scroll {
            Some(scroll) => Task::batch([scroll, fetch]),
            None => fetch,
        }
    }

    /// Jumps so the row at `index` sits at the viewport top — see
    /// [`scroll_to_anchor`](Self::scroll_to_anchor).
    pub fn scroll_to_row(&mut self, index: usize) -> Task<Message<S::Row>> {
        self.scroll_to_anchor(ScrollAnchor { row: index, offset_px: 0.0 })
    }

    /// Sets the sort/filter spec: the store executes it and the row window is
    /// invalidated and refetched. Viewport policy:
    ///
    /// - **default — the scrollbar does not move.** A re-sort/re-filter
    ///   changes the rows, not the user's place; the offset is clamped only
    ///   when the new row set ends above it.
    /// - while tail-following, the view follows the tail of the NEW row set
    ///   (a filter edit mid-stream must not silently stop the follow);
    /// - with [`set_focus_restoration(true)`](Self::set_focus_restoration), a
    ///   focused row that survives the spec change is kept in view across the
    ///   reorder — the same focus-chase the opt-in buys keyboard nav.
    ///
    /// **Selection/focus policy** (v1 default, prune-on-filter): a change to
    /// the **filter** clears the selection and the focus — through the async
    /// seam the grid cannot cheaply ask which selected ids survive an
    /// arbitrary predicate, so pruning degenerates to clearing. A
    /// **sort-only** change keeps both: identity survives reordering.
    /// (Contrast [`transact`](Self::transact), which never prunes.)
    ///
    /// Returns the follow-up [`Task`] — feed it to iced.
    ///
    /// # Example — a filter box that preserves header-click sorting
    ///
    /// ```
    /// # use oriel_core::{columns::ColumnId, data::VecStore};
    /// # use oriel_iced::grid::{BoxedColumn, VirtualGrid};
    /// # use oriel_iced::column::TextColumn;
    /// # use oriel_core::query::FilterValue;
    /// # #[derive(Clone, Debug)] struct Row { id: u64, name: String }
    /// # fn key(r: &Row) -> u64 { r.id }
    /// # let store = VecStore::new(
    /// #     (0..100u64).map(|id| Row { id, name: format!("row {id}") }).collect(),
    /// #     key as fn(&Row) -> u64,
    /// # ).with_fields(|r, col| match col {
    /// #     ColumnId(1) => Some(FilterValue::Text(r.name.clone())),
    /// #     _ => None,
    /// # });
    /// # let columns: Vec<BoxedColumn<Row>> =
    /// #     vec![Box::new(TextColumn::new(ColumnId(1), "Name", 200.0, |r: &Row| r.name.clone()))];
    /// # let (mut grid, _init) = VirtualGrid::new(store, columns);
    /// use oriel_core::query::{FilterSpec, Predicate};
    ///
    /// // The app owns the filter; header clicks own the sort — compose by
    /// // reading the CURRENT spec instead of building one from scratch:
    /// let mut spec = grid.spec().clone();
    /// spec.filter = FilterSpec {
    ///     clauses: vec![Predicate::Contains { column: ColumnId(1), needle: "7".into() }],
    /// };
    /// let task = grid.set_spec(spec); // the scrollbar stays put (clamp only)
    /// # let _ = task;
    /// # assert_eq!(grid.total_rows(), 19);
    /// ```
    pub fn set_spec(&mut self, spec: QuerySpec) -> Task<Message<S::Row>> {
        let snapshot = self.flight_snapshot();
        let task = self.set_spec_inner(spec);
        self.pending_flights = snapshot.map(|s| (self.fetch_generation, s));
        self.try_schedule_flights();
        task
    }

    fn set_spec_inner(&mut self, spec: QuerySpec) -> Task<Message<S::Row>> {
        // Prune-on-filter (the accepted default). Through the async seam
        // the grid cannot cheaply ask which selected ids survive an arbitrary
        // predicate, so pruning degenerates to clearing when the *filter*
        // changes. A sort change keeps the selection — identity survives
        // reordering by construction.
        if spec.filter != self.spec.filter {
            self.selection.clear();
            self.focus = None;
        }
        self.store.apply_spec(&spec);
        self.spec = spec;
        self.total_rows = self.store.row_count().lower_bound();
        self.window_start = 0;
        self.window_rows.clear();
        if self.follow {
            return self.jump_to_tail();
        }
        // Opt-in focus chase: keep a surviving focused row in view across the
        // reorder (minimal scroll — no movement at all if it's still visible).
        if self.focus_restoration {
            if let Some(index) = self.focus.as_ref().and_then(|id| self.store.index_of(id)) {
                return self.reveal_after_invalidate(index);
            }
        }
        // Default: the scrollbar does not move — a spec change swaps the rows
        // under the viewport, it doesn't take the user anywhere. Clamp only
        // if the new row set ends above the current offset, and refetch the
        // window around the kept position (async, like the scroll path).
        let offset = self.scroll_offset.clamp(0.0, self.max_scroll());
        let scroll = (offset != self.scroll_offset).then(|| {
            self.scroll_offset = offset;
            iced::widget::operation::scroll_to(
                self.body_id.clone(),
                AbsoluteOffset { x: self.layout.h_scroll(), y: offset },
            )
        });
        let fetch = self.fetch_task(self.virt.anchor_at(offset).row);
        match scroll {
            Some(scroll) => Task::batch([scroll, fetch]),
            None => fetch,
        }
    }

    /// Scrolls just enough to keep row `target` in view (nothing if it
    /// already is) and refetches around it — the spec-change variant of
    /// [`ensure_visible`](Self::ensure_visible): the window has just been
    /// invalidated, so the refetch is unconditional (and synchronous when the
    /// store is ready — no placeholder flash at the revealed position).
    fn reveal_after_invalidate(&mut self, target: usize) -> Task<Message<S::Row>> {
        let offset = self
            .virt
            .reveal_offset(self.scroll_offset, self.viewport_height.get(), target)
            .unwrap_or(self.scroll_offset)
            .clamp(0.0, self.max_scroll());
        let scroll = (offset != self.scroll_offset).then(|| {
            self.scroll_offset = offset;
            iced::widget::operation::scroll_to(
                self.body_id.clone(),
                AbsoluteOffset { x: self.layout.h_scroll(), y: offset },
            )
        });
        let fetch = self.fetch_now(self.virt.anchor_at(offset).row);
        match scroll {
            Some(scroll) => Task::batch([scroll, fetch]),
            None => fetch,
        }
    }

    /// The spec that results from clicking `column`'s header — the core's
    /// three-state cycle ([`QuerySpec::cycled_sort`]).
    fn toggled_sort(&self, column: ColumnId) -> Option<SortSpec> {
        self.spec.cycled_sort(column)
    }

    fn fetch_task(&mut self, anchor_row: usize) -> Task<Message<S::Row>> {
        self.fetch_generation += 1;
        let generation = self.fetch_generation;
        let start = anchor_row.saturating_sub(FETCH_MARGIN);
        let end = anchor_row.saturating_add(FETCH_ROWS).min(self.total_rows).max(start);
        Task::perform(self.store.fetch(start..end), move |rows| Message::Fetched {
            generation,
            start,
            rows,
        })
    }

    /// Like [`fetch_task`](Self::fetch_task), but fills the window
    /// **synchronously** when the store's future is already ready (resident
    /// stores) — used on the transaction paths, where the async round-trip
    /// would flash a placeholder frame at the tail on every ingest tick. A
    /// pending future falls back to the async task path unchanged. One
    /// non-blocking poll: the grid still spawns nothing and blocks nowhere.
    fn fetch_now(&mut self, anchor_row: usize) -> Task<Message<S::Row>> {
        use core::future::Future;
        use core::task::{Context, Poll, Waker};
        self.fetch_generation += 1;
        let generation = self.fetch_generation;
        let start = anchor_row.saturating_sub(FETCH_MARGIN);
        let end = anchor_row.saturating_add(FETCH_ROWS).min(self.total_rows).max(start);
        let mut future = Box::pin(self.store.fetch(start..end));
        match future.as_mut().poll(&mut Context::from_waker(Waker::noop())) {
            Poll::Ready(rows) => {
                self.window_start = start;
                self.window_rows = rows;
                self.window_generation = generation;
                Task::none()
            }
            // Re-polling from a fresh context is within the `Future` contract
            // (poll must re-register its waker each call), so the once-polled
            // future can be handed to the executor as usual.
            Poll::Pending => Task::perform(future, move |rows| Message::Fetched {
                generation,
                start,
                rows,
            }),
        }
    }

    /// The largest meaningful scroll offset: content height minus the viewport
    /// (0 before the first layout measures one — the scrollable clamps its own
    /// state, and the next real scroll event corrects ours).
    fn max_scroll(&self) -> f32 {
        (self.virt.total_height(self.total_rows) - self.viewport_height.get()).max(0.0)
    }

    /// Scrolls to the very bottom (the newest rows) and refetches around it.
    fn jump_to_tail(&mut self) -> Task<Message<S::Row>> {
        let offset = self.max_scroll();
        let moved = offset != self.scroll_offset;
        self.scroll_offset = offset;
        let fetch = self.fetch_now(self.virt.anchor_at(offset).row);
        if moved {
            let scroll = iced::widget::operation::scroll_to(
                self.body_id.clone(),
                AbsoluteOffset { x: self.layout.h_scroll(), y: offset },
            );
            Task::batch([scroll, fetch])
        } else {
            fetch
        }
    }

    /// The cached row at position `index` in the current order, if fetched.
    fn cached_row(&self, index: usize) -> Option<&S::Row> {
        index
            .checked_sub(self.window_start)
            .and_then(|offset| self.window_rows.get(offset))
    }

    // --- keyboard navigation (public *actions*; the integrator binds keys —
    // any input source can drive these, which is the no-cliffs seam) ---

    /// Moves the nav cursor down one row (single-selecting it) and keeps it
    /// visible. Returns the follow-up [`Task`].
    pub fn focus_next(&mut self) -> Task<Message<S::Row>> {
        self.move_focus(1)
    }

    /// Moves the nav cursor up one row (single-selecting it) and keeps it visible.
    pub fn focus_prev(&mut self) -> Task<Message<S::Row>> {
        self.move_focus(-1)
    }

    /// Moves the nav cursor down a page — the number of *fully visible* rows
    /// (partial rows don't count).
    pub fn page_down(&mut self) -> Task<Message<S::Row>> {
        self.move_focus(self.virt.page_len(self.viewport_height.get()) as isize)
    }

    /// Moves the nav cursor up a page.
    pub fn page_up(&mut self) -> Task<Message<S::Row>> {
        self.move_focus(-(self.virt.page_len(self.viewport_height.get()) as isize))
    }

    fn move_focus(&mut self, delta: isize) -> Task<Message<S::Row>> {
        if self.total_rows == 0 {
            return Task::none();
        }
        let last = self.total_rows - 1;
        let target = match self.focus_index() {
            // Continue from the focused row's position in the current order
            // (with focus restoration on, that may be an off-window position
            // resolved through the store).
            Some(index) => {
                (index as isize + delta).clamp(0, last as isize) as usize
            }
            // No cursor yet, or its row is beyond the fetch window and
            // restoration is off (or unanswerable): re-anchor at the top
            // visible row instead of pretending a stale position means
            // something.
            None => self.virt.anchor_at(self.scroll_offset).row.min(last),
        };
        // Scroll/refetch FIRST — the refetch is synchronous for resident
        // stores, so a target just outside the old window is selectable on
        // this very press. Only a genuinely pending fetch leaves selection to
        // catch up on the next press.
        let task = self.ensure_visible(target);
        if let Some(row) = self.cached_row(target) {
            let id = self.store.row_id(row);
            self.selection.replace(id.clone());
            self.focus = Some(id);
        }
        task
    }

    /// Scrolls just enough to bring row `target` fully into view (no-op when it
    /// already is), then refetches if the window no longer covers the anchor.
    fn ensure_visible(&mut self, target: usize) -> Task<Message<S::Row>> {
        let Some(offset) =
            self.virt.reveal_offset(self.scroll_offset, self.viewport_height.get(), target)
        else {
            return Task::none();
        };
        // Nav that scrolls UP is the user leaving the tail — freeze, same as a
        // manual upward scroll (tail-follow must never fight the user).
        if offset < self.scroll_offset {
            self.follow = false;
        }
        self.scroll_offset = offset;
        let scroll = iced::widget::operation::scroll_to(
            self.body_id.clone(),
            AbsoluteOffset { x: self.layout.h_scroll(), y: offset },
        );
        let anchor = self.virt.anchor_at(offset);
        if self.needs_fetch(anchor.row) {
            // Nav is a transaction-like path: fill synchronously when the
            // store is ready (see `fetch_now`) so the row lands this press.
            let fetch = self.fetch_now(anchor.row);
            Task::batch([scroll, fetch])
        } else {
            scroll
        }
    }

    fn needs_fetch(&self, anchor_row: usize) -> bool {
        if self.window_rows.is_empty() {
            return true;
        }
        let window_end = self.window_start + self.window_rows.len();
        let at_top = self.window_start > 0 && anchor_row < self.window_start + EDGE;
        let at_bottom =
            window_end < self.total_rows && anchor_row + MAX_VISIBLE_ROWS + EDGE > window_end;
        at_top || at_bottom
    }

    /// Handles a [`Message`]; returns the follow-up [`Task`].
    pub fn update(&mut self, message: Message<S::Row>) -> Task<Message<S::Row>> {
        match message {
            Message::BodyScrolled(offset) => {
                // A manual scroll away from the tail freezes tail-follow —
                // but `on_scroll` reports are NOT only user scrolls. While
                // `scroll_to` operations never publish (no `Shell` in
                // `operate`, iced_widget-0.14.2/src/scrollable.rs:539),
                // `notify_viewport` fires on every RedrawRequested whose
                // viewport differs from the last report — INCLUDING when only
                // the content bounds changed (scrollable.rs:1084, 1618). So
                // while ingest grows the content under a pinned absolute
                // offset, the scrollable streams stale "above the bottom"
                // reports with no user involved (the failure this prevents:
                // follow
                // unticked itself during the ring's fill phase, because the
                // commanded scroll lands a frame behind the growth).
                //
                // Growth echoes are non-decreasing, so user intent is a
                // RECEDING report: below both the previous report and the
                // grid's own commanded offset. (The second bound keeps a
                // commanded shrink — clear(), viewport resize — from
                // reading as a user scroll.) Recession ACCUMULATES across
                // consecutive receding reports: precision touchpads recede
                // in sub-pixel steps a per-report 1 px test never sees.
                if offset.y < self.last_scroll_report {
                    self.recession += self.last_scroll_report - offset.y;
                } else {
                    self.recession = 0.0;
                }
                // The commanded bound is strict WITHOUT a margin: genuine
                // recession sits strictly below the adopted offset (which
                // trails the reports by one step), while command echoes
                // land exactly ON it — a margin here would swallow
                // sub-pixel steps the accumulator exists to catch.
                let receding = self.recession >= 1.0 && offset.y < self.scroll_offset;
                if self.follow && receding {
                    self.follow = false;
                }
                self.last_scroll_report = offset.y;
                self.scroll_offset = offset.y;
                self.layout.set_h_scroll(offset.x);
                // Keep the header (and footer strip, if any) aligned with the
                // body's horizontal offset.
                let mut tasks = vec![iced::widget::operation::scroll_to(
                    self.header_id.clone(),
                    AbsoluteOffset { y: 0.0, ..offset },
                )];
                if self.has_footer {
                    tasks.push(iced::widget::operation::scroll_to(
                        self.footer_id.clone(),
                        AbsoluteOffset { y: 0.0, ..offset },
                    ));
                }
                let anchor = self.virt.anchor_at(offset.y);
                if self.needs_fetch(anchor.row) {
                    tasks.push(self.fetch_task(anchor.row));
                }
                Task::batch(tasks)
            }
            Message::Fetched { generation, start, rows } => {
                // Stale-fetch guard: only the newest generation may fill the
                // window; superseded results (older scroll position or older
                // spec) would show wrong rows until the next fetch landed.
                if generation == self.fetch_generation {
                    self.window_start = start;
                    self.window_rows = rows;
                    self.window_generation = generation;
                    // An async fill (set_spec's path, or a transact over a
                    // genuinely async store) may complete a pending flight
                    // capture.
                    self.try_schedule_flights();
                }
                Task::none()
            }
            Message::RowPressed { index } => {
                // Selection and focus both need the row's identity; a click on
                // a placeholder (not yet fetched) row changes nothing. v1
                // single-select: the click replaces the selection (multi-select
                // gestures are held open — the underlying Selection is a set).
                if let Some(row) = self.cached_row(index) {
                    let id = self.store.row_id(row);
                    self.selection.replace(id.clone());
                    self.focus = Some(id);
                }
                Task::none()
            }
            Message::RowHovered { index } => {
                self.hovered = Some(index);
                Task::none()
            }
            Message::RowUnhovered { index } => {
                // Adjacent rows' enter/exit can arrive in either order within
                // one frame — only clear if nothing newer took over.
                if self.hovered == Some(index) {
                    self.hovered = None;
                }
                Task::none()
            }
            Message::ColumnResizing { index, delta } => {
                self.layout.preview_resize(index, delta);
                Task::none()
            }
            Message::ColumnResized { index } => {
                self.layout.commit_resize(index);
                Task::none()
            }
            Message::ScrollbarDragged(offset) => {
                // Same semantics as any programmatic jump: freeze follow,
                // clamp, command the scrollable, refetch (the bar is a user
                // gesture — dragging away from the tail must stick).
                let anchor = self.virt.anchor_at(offset.max(0.0));
                self.scroll_to_anchor(anchor)
            }
            Message::ColumnAutoSizeRequested { index } => {
                self.auto_size.insert(index);
                self.auto_size_epoch += 1;
                Task::none()
            }
            Message::ColumnMeasured { index, width } => {
                if self.auto_size.remove(&index)
                    && width < crate::measure::MEASURE_CAP - 0.5
                {
                    // Natural content + the cell's horizontal padding (the
                    // header's grip allowance is folded into the measurement
                    // itself); the policy clamp has final say. A width AT the
                    // measuring cap means some cell asked to Fill — it has no
                    // natural width, so auto-size leaves the column alone
                    // (committing would slam it to the policy maximum, which
                    // reads as broken when a theme switch fits every column).
                    self.layout.set_width(index, width + self.cell_padding * 2.0);
                }
                Task::none()
            }
            Message::HeaderPressed { index } => match self.layout.id(index) {
                Some(column) => {
                    let spec = QuerySpec {
                        sort: self.toggled_sort(column),
                        filter: self.spec.filter.clone(),
                    };
                    self.set_spec(spec)
                }
                None => Task::none(),
            },
        }
    }

    /// Renders the whole grid — header band, virtualized body, footer strip
    /// (when any column provides one), and scrollbars.
    ///
    /// The element **fills all the space its parent gives it, on both
    /// axes** — size the grid by constraining the parent, exactly like any
    /// other iced widget: drop it in a `column!` beside a toolbar and it
    /// takes the rest, or cap it with
    /// `container(grid.view().map(Msg::Grid)).height(400)`. It needs a
    /// bounded height (any layout that isn't infinitely tall) — the visible
    /// slice is computed against it.
    pub fn view(&self) -> Element<'_, Message<S::Row>>
    where
        S::Row: Clone,
    {
        let columns = &self.columns;
        let layout = &self.layout;
        let virt = self.virt;
        let spec_sort = self.spec.sort;
        let scroll_offset = self.scroll_offset;
        let total_rows = self.total_rows;
        let window_start = self.window_start;
        let window_rows = &self.window_rows;
        let store = &self.store;
        let selection = &self.selection;
        let focus = self.focus.as_ref();
        let hovered = self.hovered;
        let auto_size = &self.auto_size;
        let viewport_height = &self.viewport_height;
        let header_id = self.header_id.clone();
        let body_id = self.body_id.clone();
        let header_height = self.header_height;
        let footer_height = self.footer_height;
        let has_footer = self.has_footer;
        let handle_width = self.handle_width;
        let cell_padding = self.cell_padding;
        let row_style = &self.row_style;
        let cell_style = &self.cell_style;
        let header_style = &self.header_style;
        let footer_style = &self.footer_style;
        let sort_indicator = &self.sort_indicator;
        let row_divider = self.row_divider;
        let column_divider = self.column_divider;
        let rule_color = self.rule_color;
        let auto_size_epoch = self.auto_size_epoch;
        let footer_id = self.footer_id.clone();
        let flights = &self.flights;
        let fades = &self.fades;
        let reorder_easing = &self.reorder_easing;
        let fade_cover: crate::slide::CoverFn<iced::Theme> =
            Rc::new(crate::slide::theme_background);

        iced::widget::responsive(move |size| {
            let placements = layout.placements();
            let total_width = layout.total_width();
            let row_height = virt.row_height();
            // Header, 1 px rule, the body, and — when any column provides a
            // footer — another rule plus the footer strip.
            let footer_space = if has_footer { footer_height + 1.0 } else { 0.0 };
            let body_viewport = (size.height - header_height - 1.0 - footer_space).max(0.0);
            let rows_height = virt.total_height(total_rows);
            // Overlay-scrollbar gutters, reserved ONLY when the bar can
            // actually appear — an unconditional gutter reads as a dead gap
            // (e.g. between the last row and a docked footer). Adding one
            // bar's gutter can push the other axis into overflow, hence the
            // second pass.
            let v_over = rows_height > body_viewport;
            let h_over =
                total_width + if v_over { SCROLLBAR_GUTTER } else { 0.0 } > size.width;
            let bottom_gutter = if h_over { SCROLLBAR_GUTTER } else { 0.0 };
            let v_over = rows_height + bottom_gutter > body_viewport;
            let right_gutter = if v_over { SCROLLBAR_GUTTER } else { 0.0 };
            // With a footer, a body shorter than its viewport DOCKS the
            // footer to the content instead of stranding the totals across an
            // empty gap at the pane bottom — pinning only matters once
            // there's something to scroll.
            let body_natural = rows_height + bottom_gutter;
            let docked = has_footer && body_natural < body_viewport;
            let body_view_h = if docked { body_natural } else { body_viewport };
            let body_height = if docked {
                Length::Fixed(body_natural)
            } else {
                Length::Fill
            };
            // Remember the EFFECTIVE viewport (minus the horizontal
            // scrollbar's overlay band) for page-nav / ensure-visible /
            // max-scroll math: with the bottom gutter in the content, the
            // true scroll maximum is `total_height - (viewport - gutter)`,
            // and a row is only "fully visible" above the bar. (`view` is
            // `&self`, hence the Cell.) Materialization below still uses the
            // full band height — rows under the translucent bar must exist.
            viewport_height.set((body_view_h - bottom_gutter).max(0.0));
            let window = virt.visible(scroll_offset, body_view_h, total_rows);
            let cache_end = window_start + window_rows.len();
            let cell_pad = Padding {
                top: 0.0,
                right: cell_padding,
                bottom: 0.0,
                left: cell_padding,
            };

            // --- header row (sort mouse_area INSIDE the resize handle, so a
            // press on the grab strip is consumed before the sort area ever
            // sees it; the handle also captures the event) ---
            let header_cells = placements.iter().map(|p| {
                let col = &columns[p.index];

                let mut label_content: Element<'_, Message<S::Row>> = col.header();
                if let Some(sort) = spec_sort.filter(|s| s.column == p.id) {
                    label_content = row![label_content, (sort_indicator)(sort.direction)]
                        .spacing(4)
                        .align_y(Vertical::Center)
                        .into();
                }
                let label: Element<'_, Message<S::Row>> = container(label_content)
                    .width(Length::Fill)
                    .height(Length::Fixed(header_height))
                    .align_y(Vertical::Center)
                    .padding(cell_pad)
                    .into();
                let label: Element<'_, Message<S::Row>> = if col.sortable() {
                    let index = p.index;
                    mouse_area(label)
                        .on_press(Message::HeaderPressed { index })
                        .into()
                } else {
                    label
                };
                let content: Element<'_, Message<S::Row>> = if col.sizing().is_resizable() {
                    let index = p.index;
                    crate::resize::ResizeHandle::new(
                        label,
                        handle_width,
                        move |delta| Message::ColumnResizing { index, delta },
                        Message::ColumnResized { index },
                    )
                    .on_auto_size(Message::ColumnAutoSizeRequested { index })
                    .into()
                } else {
                    label
                };
                container(content)
                    .width(Length::Fixed(p.width))
                    .height(Length::Fixed(header_height))
                    .into()
            });
            // The header sits on its own band (a step off the body background)
            // with a 1 px rule below — colors via the header-style hook.
            // A corner spacer mirrors the body's external scrollbar strip, so
            // header and body share one horizontal viewport width (and thus
            // one scroll maximum) and stay aligned at the far right.
            let header = container(
                row![
                    scrollable(row(header_cells).width(Length::Fixed(total_width)))
                        .id(header_id.clone())
                        .direction(Direction::Horizontal(hidden_scrollbar()))
                        .width(Length::Fill)
                        .height(Length::Fixed(header_height)),
                    space().width(Length::Fixed(right_gutter)),
                ],
            )
            .style(move |theme: &iced::Theme| (header_style)(theme));

            // --- body rows ---
            // INVARIANT: every keyed child — data row or placeholder — must be
            // the SAME top-level widget type (a `row` of per-column cells).
            // `keyed_column` pairs equal-length children positionally WITHOUT a
            // tag check (iced_widget keyed/column.rs:224-245 — canary-pinned),
            // and `container` is *transparent* in the state tree (its
            // tag/state delegate to its content, iced_widget container.rs:236),
            // so a bare `container(text)` placeholder carries `text`'s stateful
            // tag while a data row carries `row`'s stateless one. Swapping the
            // two under keyed's untag-checked zip hands `text::layout` a
            // stateless node → "Downcast on stateless state" (the startup
            // crash; regression-tested in tests/lifecycle.rs). One level down,
            // all diffs are tag-checked, so per-cell heterogeneity is fine.
            let body_rows = keyed_column(window.range().map(|i| {
                let data = (i >= window_start && i < cache_end)
                    .then(|| &window_rows[i - window_start]);
                let id = data.map(|d| store.row_id(d));
                // Keyed key: a `RowId`-derived hash, so retained
                // widget-tree state follows the ROW across count-changing
                // rebuilds. `keyed` needs `Key: Copy` but `RowId` is only
                // `Clone` — the 64-bit hash is the bridge (a collision merely
                // mispairs one diff, which the uniform-row rule makes benign).
                // Placeholders have no identity yet: a tagged positional hash.
                let key = match &id {
                    Some(id) => keyed_hash(0, id),
                    None => keyed_hash(1, &i),
                };

                // The style hooks' input: selection and focus by IDENTITY
                // (neither ever decorates whatever row occupies an old slot
                // after a re-sort); hover positional and transient; the row
                // data itself for data-driven chrome (TX tints etc.).
                let ctx = RowContext {
                    index: i,
                    row: data,
                    is_selected: id.as_ref().is_some_and(|id| selection.contains(id)),
                    is_focused: id.as_ref().zip(focus).is_some_and(|(id, f)| id == f),
                    is_hovered: hovered == Some(i),
                };

                // The row divider is carved OUT of the row height (pitch
                // unchanged — virtualization math never sees dividers), and
                // the column divider out of each cell's width (column
                // positions stay header-aligned).
                let cell_h = row_height - if row_divider.is_some() { 1.0 } else { 0.0 };
                let last = placements.len().saturating_sub(1);
                let mut cells: Vec<Element<'_, Message<S::Row>>> =
                    Vec::with_capacity(placements.len() * 2);
                for (k, p) in placements.iter().enumerate() {
                    let content: Element<'_, Message<S::Row>> = match data {
                        Some(data) => columns[p.index].cell(data),
                        // Placeholders render dim — clearly "not data yet".
                        None => text("…")
                            .size(13.0)
                            .style(|theme: &iced::Theme| iced::widget::text::Style {
                                color: Some(theme.extended_palette().background.strong.color),
                            })
                            .into(),
                    };
                    let column_id = p.id;
                    let vband = column_divider.filter(|_| k < last);
                    let shave = if vband.is_some() { 1.0 } else { 0.0 };
                    cells.push(
                        container(content)
                            .width(Length::Fixed(p.width - shave))
                            .height(Length::Fixed(cell_h))
                            .align_y(Vertical::Center)
                            .padding(cell_pad)
                            .clip(true)
                            .style(move |theme: &iced::Theme| {
                                (cell_style)(theme, &ctx, column_id)
                            })
                            .into(),
                    );
                    if let Some(color) = vband {
                        cells.push(
                            container(space())
                                .width(Length::Fixed(1.0))
                                .height(Length::Fixed(cell_h))
                                .style(move |_theme: &iced::Theme| {
                                    iced::widget::container::Style {
                                        background: Some(color.into()),
                                        ..iced::widget::container::Style::default()
                                    }
                                })
                                .into(),
                        );
                    }
                }

                // Row chrome via the row-style hook (default: selected >
                // focused > hovered > zebra, theme-derived), wrapped in a
                // Slide carrying any reorder flight. The wrapper chain is the
                // SAME for data and placeholder rows (uniform top-level type
                // — see the INVARIANT above):
                // Slide(mouse_area(container(row))).
                let flight = id.as_ref().and_then(|id| flights.get(id)).copied();
                let fade = id.as_ref().and_then(|id| fades.get(id)).copied();
                // With a row divider, the row is lanes + a 1 px band; the
                // band paints OVER the row chrome (selection tint etc.), as
                // market grids do. Same structure for data and placeholder
                // rows (the uniform-type invariant holds at the Slide level;
                // one level down diffs are tag-checked, so the row/column
                // content switch on a divider toggle rebuilds cleanly).
                let lanes = row(cells).width(Length::Fixed(total_width));
                let row_body: Element<'_, Message<S::Row>> = match row_divider {
                    Some(color) => column![
                        lanes,
                        container(space())
                            .width(Length::Fixed(total_width))
                            .height(Length::Fixed(1.0))
                            .style(move |_theme: &iced::Theme| {
                                iced::widget::container::Style {
                                    background: Some(color.into()),
                                    ..iced::widget::container::Style::default()
                                }
                            }),
                    ]
                    .into(),
                    None => lanes.into(),
                };
                let row_el: Element<'_, Message<S::Row>> = crate::slide::Slide::new(
                    mouse_area(
                        container(row_body)
                            .style(move |theme: &iced::Theme| (row_style)(theme, &ctx)),
                    )
                    .on_press(Message::RowPressed { index: i })
                    .on_enter(Message::RowHovered { index: i })
                    .on_exit(Message::RowUnhovered { index: i }),
                    flight,
                    fade,
                    Rc::clone(reorder_easing),
                    Rc::clone(&fade_cover),
                )
                .into();
                (key, row_el)
            }))
            .width(Length::Fixed(total_width));

            // The content carries the scrollbar gutters itself: extra width
            // past the last column and extra height past the last row, so
            // fully-scrolled content clears the overlay bars.
            // The scrollable's own vertical bar is HIDDEN (its minimum thumb
            // is a hardcoded 2 px — see SCROLLBAR_GUTTER); wheel/keyboard/
            // programmatic scrolling still run through it, while the grid's
            // VScrollbar beside it renders the thumb and handles dragging.
            let body = scrollable(
                column![
                    space().height(Length::Fixed(window.space_before)),
                    body_rows,
                    space().height(Length::Fixed(window.space_after + bottom_gutter)),
                ]
                .width(Length::Fixed(total_width)),
            )
            .id(body_id.clone())
            .on_scroll(|viewport: Viewport| Message::BodyScrolled(viewport.absolute_offset()))
            .direction(Direction::Both {
                vertical: hidden_scrollbar(),
                horizontal: Scrollbar::new(),
            })
            .width(Length::Fill)
            .height(if v_over { Length::Fill } else { body_height });
            let body_pane: Element<'_, Message<S::Row>> = if v_over {
                row![
                    body,
                    crate::scrollbar::VScrollbar::new(
                        scroll_offset,
                        body_view_h,
                        rows_height + bottom_gutter,
                        Message::ScrollbarDragged,
                    ),
                ]
                .height(body_height)
                .into()
            } else {
                body.into()
            };

            // The auto-size measurers: one zero-size phantom PER COLUMN
            // (uniform tree shape every frame), each idle and empty unless
            // its column has a pending measurement. A pending one lays out
            // fresh copies of the column's header + visible cells against
            // generous limits and publishes the natural maximum — so an
            // `auto_size_all` fits every column in a single layout pass.
            let measurers = (0..columns.len()).map(|index| {
                let mut measure_children: Vec<Element<'_, Message<S::Row>>> = Vec::new();
                if auto_size.contains(&index) {
                    let col = &columns[index];
                    // Cells measure through `Column::measure` — the
                    // measurement-friendly rendering. A `None` means the
                    // column has NO natural width (bars); publish a
                    // cap-hitting report so the pending entry drains through
                    // the decline path and the width stays put.
                    let mut cells: Vec<Element<'_, Message<S::Row>>> = Vec::new();
                    let mut unmeasurable = false;
                    for i in window.range() {
                        if i >= window_start && i < cache_end {
                            match col.measure(&window_rows[i - window_start]) {
                                Some(element) => cells.push(element),
                                None => {
                                    unmeasurable = true;
                                    break;
                                }
                            }
                        }
                    }
                    if unmeasurable {
                        measure_children.push(
                            space().width(Length::Fixed(crate::measure::MEASURE_CAP)).into(),
                        );
                    }
                    // A fit with NOTHING to measure would collapse the column
                    // to its header width (empty store at boot, a grid
                    // filtered down to nothing) — stay pending instead; the
                    // fit self-arms on the first frame that has rows.
                    else if !cells.is_empty() {
                        // The header is measured AS RENDERED: the sorted
                        // column carries its sort indicator (+ the 4 px
                        // gap), so a fitted width never clips the arrow.
                        let mut header_el: Element<'_, Message<S::Row>> = col.header();
                        if let Some(sort) = spec_sort.filter(|s| s.column == col.id()) {
                            header_el = row![header_el, (sort_indicator)(sort.direction)]
                                .spacing(4)
                                .align_y(Vertical::Center)
                                .into();
                        }
                        // The header is measured WITH its grip allowance (the
                        // ResizeHandle reserves the header cell's right
                        // edge); body cells are measured bare. Folding the
                        // allowance into the max here — rather than padding
                        // the committed width — keeps cell-dominated columns
                        // symmetric around their content (measured on-screen: a
                        // blanket +grip read as 5 px left / 11 px right
                        // inside the dividers).
                        measure_children.push(
                            container(header_el)
                                .padding(Padding {
                                    top: 0.0,
                                    right: handle_width,
                                    bottom: 0.0,
                                    left: 0.0,
                                })
                                .into(),
                        );
                        measure_children.append(&mut cells);
                        // The footer must fit too — a total is often wider
                        // than any cell (`None` = nothing to measure). The
                        // rendered footer cell loses 1 px to its boundary
                        // tick, so the measurement carries the same
                        // allowance (like the header's grip) — without it a
                        // footer-dominated fit lands exactly 1 px short and
                        // the total wraps.
                        if let Some(footer_el) = col.measure_footer() {
                            measure_children.push(
                                container(footer_el)
                                    .padding(Padding {
                                        top: 0.0,
                                        right: 1.0,
                                        bottom: 0.0,
                                        left: 0.0,
                                    })
                                    .into(),
                            );
                        }
                    }
                }
                crate::measure::Measure::new(measure_children, auto_size_epoch, move |width| {
                    Message::ColumnMeasured { index, width }
                })
            });

            // The frame rules: themable via `set_rule_color` (a GridTheme's
            // structural border), ambient rule style otherwise.
            let frame_rule = || -> Element<'_, Message<S::Row>> {
                match rule_color {
                    Some(color) => iced::widget::rule::horizontal(1)
                        .style(move |theme: &iced::Theme| iced::widget::rule::Style {
                            color,
                            ..iced::widget::rule::default(theme)
                        })
                        .into(),
                    None => iced::widget::rule::horizontal(1).into(),
                }
            };
            let mut children: Vec<Element<'_, Message<S::Row>>> =
                vec![header.into(), frame_rule(), body_pane];
            if has_footer {
                // The footer strip: one cell per column (empty where a column
                // has no footer, so widths stay aligned), horizontally synced
                // with the body like the header.
                let footer_cells = placements.iter().map(|p| {
                    let content: Element<'_, Message<S::Row>> = columns[p.index]
                        .footer()
                        .unwrap_or_else(|| space().into());
                    let cell = container(content)
                        .width(Length::Fill)
                        .height(Length::Fill)
                        .align_y(Vertical::Center)
                        .padding(cell_pad)
                        .clip(true);
                    // A column-boundary tick after every footer cell —
                    // totals float ambiguously without one (and it rhymes
                    // with the header's resize ticks).
                    let tick = iced::widget::rule::vertical(1).style(|theme: &iced::Theme| {
                        iced::widget::rule::Style {
                            fill_mode: iced::widget::rule::FillMode::Percent(50.0),
                            ..iced::widget::rule::default(theme)
                        }
                    });
                    container(row![cell, tick])
                        .width(Length::Fixed(p.width))
                        .height(Length::Fixed(footer_height))
                        .into()
                });
                let footer = container(
                    row![
                        scrollable(row(footer_cells).width(Length::Fixed(total_width)))
                            .id(footer_id.clone())
                            .direction(Direction::Horizontal(hidden_scrollbar()))
                            .width(Length::Fill)
                            .height(Length::Fixed(footer_height)),
                        space().width(Length::Fixed(right_gutter)),
                    ],
                )
                .style(move |theme: &iced::Theme| (footer_style)(theme));
                children.push(frame_rule());
                children.push(footer.into());
            }
            children.extend(measurers.map(Into::into));

            column(children).width(Length::Fill).height(Length::Fill).into()
        })
        .into()
    }
}

/// A zero-size scrollbar — the header scrolls only programmatically (via
/// `scroll_to`), never by the user.
fn hidden_scrollbar() -> Scrollbar {
    Scrollbar::new().width(0).margin(0).scroller_width(0)
}

/// The keyed-diff key bridge: a stable 64-bit hash of a `RowId` (tag 0) or of a
/// placeholder's position (tag 1). `DefaultHasher::new()` is fixed-key
/// SipHash, so keys are stable across frames — which is all keyed diffing
/// compares.
fn keyed_hash(tag: u8, value: &impl std::hash::Hash) -> u64 {
    use std::hash::{DefaultHasher, Hash, Hasher};
    let mut hasher = DefaultHasher::new();
    tag.hash(&mut hasher);
    value.hash(&mut hasher);
    hasher.finish()
}