nsh-core 0.1.0

Platform-independent core: shadow tree, styles, layout and mount instructions.
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
//! Virtualized list state: item sizes, offsets, the render window and cell
//! recycling. Pure bookkeeping; the core feeds it measurements and scroll
//! offsets and applies its decisions to the tree.
//!
//! Positions are computed along the list's main axis in *natural*
//! coordinates (distance from the start of the content: padding, header,
//! items, footer). An inverted list lays the same content out from the end
//! of the scroll view (item 0 at the bottom) and keeps its distance from
//! the end while content changes, like React Native's inverted lists.
//!
//! # Binding cells
//!
//! The window (Fenwick prefix sums over rows) renders one extra screen above
//! and below the viewport. The core asks JS to bind cells with
//! `__nsh_list(listId, [slot, index, …])`; JS updates a cell's content inside
//! `batch` and then sets its `cellIndex` to confirm, and only confirmed cells
//! are measured and positioned. New cells are created with their first
//! index. The engine runs at most 8 "bind → JS → layout" rounds per frame,
//! merged into one batch. Row-local state travels with recycled cells, so
//! apps keep it outside, keyed by id. Unbound cells keep their last content:
//! the core moves them out of sight (never with a NaN frame; cells never
//! placed are skipped). The header, footer and empty placeholder are cells
//! with a role (`slot="header"`, ...) and are never recycled. Each cell is a
//! Taffy root of its own (its width follows the list's cross axis), so
//! scrolling relays out dirty cells only.
//!
//! # Scroll commands
//!
//! `scrollToEnd` / `scrollToIndex` resolve with estimated sizes for rows
//! never rendered, so the first offset is off. Their target stays pinned:
//! after each round of measurements the list follows it (`follow_pin`),
//! retargeting an animated scroll in flight, until the rows in the
//! viewport are measured, the user scrolls away or the items change.

use rustc_hash::FxHashMap;

use crate::{
    fenwick::Fenwick,
    ops::{CellSlot, ListContentStyle, Viewability},
};

/// How far beyond the viewport cells are kept rendered, in viewports.
const OVERSCAN: f32 = 1.0;
/// Default `onEndReachedThreshold`, in viewports.
const END_THRESHOLD: f32 = 1.0;

/// A recycling slot: one cell node, bound to at most one item.
#[derive(Debug, Clone, Copy)]
pub(super) struct Slot {
    /// Cell node key (`u32::MAX` until the runtime created the cell).
    pub(super) cell: u32,
    /// Item this slot is assigned to.
    pub(super) index: Option<u32>,
    /// Item the cell's content currently shows (confirmed by the runtime).
    pub(super) rendered: Option<u32>,
}

impl Slot {
    /// True when the cell shows its assigned item, so its size and
    /// position belong to that item.
    pub(super) fn ready(&self) -> Option<u32> {
        match (self.index, self.rendered) {
            (Some(i), Some(r)) if i == r && self.cell != u32::MAX => Some(i),
            _ => None,
        }
    }
}

/// A non-recycled cell: the header, footer or empty placeholder.
#[derive(Debug, Clone, Copy)]
pub(super) struct Extra {
    /// Cell node key, or `u32::MAX`.
    pub(super) cell: u32,
    /// Measured main-axis size (0 until measured).
    pub(super) size: f32,
}

impl Extra {
    const NONE: Self = Self {
        cell: u32::MAX,
        size: 0.0,
    };

    fn present(&self) -> bool {
        self.cell != u32::MAX
    }
}

/// Which extra cell.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum ExtraKind {
    Header = 0,
    Footer = 1,
    Empty = 2,
}

/// Where the blocks of a list's content start, in natural coordinates.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(super) struct Blocks {
    pub(super) header: f32,
    /// The first item row (or the empty placeholder).
    pub(super) body: f32,
    pub(super) footer: f32,
    /// Content length: everything plus the end padding.
    pub(super) total: f32,
}

/// A scroll the core asked the platform for, not yet reflected in the
/// offsets it reports.
#[derive(Debug, Clone, Copy, PartialEq)]
enum PendingScroll {
    By(f32),
    To(f32),
}

/// What a list scroll command asked to show: kept after the command, so
/// the offset follows the target while the cells around it are measured
/// (estimated sizes put the first offset off).
#[derive(Debug, Clone, Copy, PartialEq)]
pub(super) enum PinTarget {
    /// `scrollToEnd`.
    End,
    /// `scrollToIndex`.
    Index {
        index: u32,
        view_position: f32,
        view_offset: f32,
    },
}

/// A pinned scroll target and the offset the list was last sent to for
/// it.
#[derive(Debug, Clone, Copy, PartialEq)]
struct Pin {
    target: PinTarget,
    at: f32,
    /// An animated scroll the platform has not finished: the pin follows
    /// by retargeting it, and the user moving away is only noticed once
    /// it landed.
    animating: bool,
}

/// How a pinned list follows its target (`ListState::follow_pin`).
#[derive(Debug, Clone, Copy, PartialEq)]
pub(super) enum Follow {
    /// Already there.
    Stay,
    /// Scroll by this much now (with the anchoring `ScrollBy`).
    By(f32),
    /// Retarget the animated scroll to this offset.
    To(f32),
}

/// How far a reported offset may be from a pinned one and still count as
/// the same (platforms round offsets to pixels).
const PIN_SLACK: f32 = 1.0;

/// A sticky cell's range of travel, in content coordinates along the main
/// axis: it sits at `start` and is pushed down with the scroll offset
/// until `end`.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(super) struct StickyRange {
    pub(super) cell: u32,
    pub(super) start: f32,
    pub(super) end: f32,
}

#[derive(Debug)]
pub(super) struct ListState {
    pub(super) count: u32,
    estimated: f32,
    /// Items per row (`numColumns`).
    pub(super) columns: u32,
    /// Measured main-axis sizes of items; NaN = not measured yet.
    sizes: Vec<f32>,
    /// Row sizes (the largest item of each row) plus the gap after the row.
    rows: Fenwick,
    pub(super) slots: Vec<Slot>,
    by_index: FxHashMap<u32, u32>,
    free: Vec<u32>,
    pub(super) extras: [Extra; 3],
    /// `contentContainerStyle`: padding and gaps.
    pub(super) content: ListContentStyle,
    pub(super) horizontal: bool,
    pub(super) inverted: bool,
    /// `maintainVisibleContentPosition`'s `autoscrollToBottomThreshold`:
    /// a list that is not inverted follows the end of its content while
    /// it is within this distance of it.
    pub(super) follow_end: Option<f32>,
    /// `stickyHeaderIndices`, sorted.
    pub(super) sticky: Vec<u32>,
    /// Sticky ranges last sent to the platform.
    pub(super) sent_sticky: Vec<StickyRange>,
    pub(super) viewability: Viewability,
    /// Last reported viewable items (`first..=last`).
    pub(super) viewable: Option<(u32, u32)>,
    /// `onEndReachedThreshold`, in viewports.
    pub(super) end_threshold: f32,
    /// Main-axis scroll offset reported by the platform (content
    /// coordinates).
    pub(super) offset: f32,
    /// Main-axis size of the list viewport (from layout).
    pub(super) viewport: f32,
    /// Window, bindings or positions need recomputing.
    pub(super) dirty: bool,
    /// Cross-axis size the cells were last laid out at.
    pub(super) cells_cross: f32,
    end_reached_at: Option<u32>,
    /// `content_len - viewport` when the offset was last anchored
    /// (inverted lists and `follow_end`; NaN before the first layout).
    anchored_end: f32,
    /// Scrolls issued to the platform (`ScrollBy` items and `ScrollTo`
    /// commands); platforms count the ones they applied.
    issued: u32,
    /// Issued scrolls by number, oldest first, until a report shows them
    /// applied.
    pending: Vec<(u32, PendingScroll)>,
    /// Cells whose item moved to another index (a splice): the runtime
    /// learns their new index with the next bindings.
    moved: Vec<(u32, u32)>,
    /// Scroll that keeps the visible content in place after a splice.
    splice_anchor: f32,
    /// The target of the last scroll command, until it is reached with
    /// measured cells or the user scrolls away.
    pin: Option<Pin>,
}

impl ListState {
    pub(super) fn new() -> Self {
        Self {
            count: 0,
            estimated: 50.0,
            columns: 1,
            sizes: Vec::new(),
            rows: Fenwick::default(),
            slots: Vec::new(),
            by_index: FxHashMap::default(),
            free: Vec::new(),
            extras: [Extra::NONE; 3],
            content: ListContentStyle::default(),
            horizontal: false,
            inverted: false,
            follow_end: None,
            sticky: Vec::new(),
            sent_sticky: Vec::new(),
            viewability: Viewability::default(),
            viewable: None,
            end_threshold: END_THRESHOLD,
            offset: 0.0,
            viewport: 0.0,
            dirty: true,
            cells_cross: f32::NAN,
            end_reached_at: None,
            anchored_end: f32::NAN,
            issued: 0,
            pending: Vec::new(),
            moved: Vec::new(),
            splice_anchor: 0.0,
            pin: None,
        }
    }

    /// The items changed: `removed` items at `at` were replaced by
    /// `inserted` new ones. Measurements and cells follow the items that
    /// stay, and when the change is above the first visible item the
    /// visible content keeps its place.
    pub(super) fn splice(&mut self, at: u32, removed: u32, inserted: u32) {
        let at = at.min(self.count);
        let removed = removed.min(self.count - at);
        if removed == 0 && inserted == 0 {
            return;
        }
        // The visible content keeps its place instead.
        self.pin = None;
        // The first visible item and where it is in the viewport.
        let anchor = (!self.inverted && self.count > 0 && self.viewport > 0.0).then(|| {
            let top = self.natural_offset();
            let body = self.blocks().body;
            let row = self.rows.find((top - body).max(0.0) as f64) as u32;
            let index = (row * self.columns).min(self.count - 1);
            (index, self.item_at(index) - top)
        });
        let end = (at + removed) as usize;
        self.sizes.splice(
            at as usize..end,
            std::iter::repeat_n(f32::NAN, inserted as usize),
        );
        self.count = self.count - removed + inserted;
        let shift = |i: u32| -> Option<u32> {
            if i < at {
                Some(i)
            } else if i >= at + removed {
                Some(i - removed + inserted)
            } else {
                None
            }
        };
        self.by_index.clear();
        for (slot, s) in self.slots.iter_mut().enumerate() {
            let Some(old) = s.index else { continue };
            match shift(old) {
                Some(new) => {
                    s.index = Some(new);
                    if s.rendered == Some(old) {
                        s.rendered = Some(new);
                    }
                    if new != old {
                        self.moved.push((slot as u32, new));
                    }
                    self.by_index.insert(new, slot as u32);
                }
                None => {
                    s.index = None;
                    s.rendered = None;
                    self.free.push(slot as u32);
                }
            }
        }
        self.free.sort_unstable();
        self.free.dedup();
        self.rebuild_offsets();
        if self.end_reached_at.is_some() {
            self.end_reached_at = None;
        }
        if let Some((index, from_top)) = anchor
            && index >= at + removed
        {
            let moved_to = index - removed + inserted;
            let delta = self.item_at(moved_to) - from_top - self.natural_offset();
            self.offset += delta;
            self.splice_anchor += delta;
        }
    }

    /// The scroll a splice asked for, once.
    pub(super) fn take_splice_anchor(&mut self) -> f32 {
        std::mem::take(&mut self.splice_anchor)
    }

    /// Records a `ScrollBy` sent to the platform.
    pub(super) fn issue_scroll_by(&mut self, delta: f32) {
        self.issued += 1;
        self.pending.push((self.issued, PendingScroll::By(delta)));
    }

    /// Records a `ScrollTo` sent to the platform.
    pub(super) fn issue_scroll_to(&mut self, offset: f32) {
        self.issued += 1;
        self.pending.push((self.issued, PendingScroll::To(offset)));
    }

    /// The platform reports its offset after applying `applied` of the
    /// issued scrolls: scrolls it has not applied yet still count, so a
    /// report that predates them does not move the window backwards.
    pub(super) fn reported(&mut self, offset: f32, applied: u32) {
        self.pending.retain(|&(n, _)| n > applied);
        let mut at = offset;
        for &(_, scroll) in &self.pending {
            match scroll {
                PendingScroll::By(d) => at += d,
                PendingScroll::To(t) => at = t,
            }
        }
        if at != self.offset {
            self.offset = at;
            self.dirty = true;
        }
        if let Some(pin) = &mut self.pin
            && self.pending.is_empty()
        {
            if (at - pin.at).abs() <= PIN_SLACK {
                if pin.animating {
                    // Landed: a correction may follow.
                    pin.animating = false;
                    self.dirty = true;
                }
            } else if !pin.animating {
                // The user scrolled away.
                self.pin = None;
            }
        }
    }

    /// Keeps following `target` after a scroll command sent the list to
    /// `offset` (animated or not); `None` (a plain offset) ends the pin.
    pub(super) fn pin(&mut self, target: Option<PinTarget>, offset: f32, animated: bool) {
        self.pin = target.map(|target| Pin {
            target,
            at: offset,
            animating: animated,
        });
    }

    /// The content offset for `target` with the sizes known now.
    pub(super) fn target_offset(&self, target: PinTarget) -> f32 {
        match target {
            PinTarget::End => self.end_offset(),
            PinTarget::Index {
                index,
                view_position,
                view_offset,
            } => self.offset_for_index(index, view_position, view_offset),
        }
    }

    /// After measurements: where a pinned list goes for its target, which
    /// moved as estimated sizes became real ones. The pin ends once the
    /// list is there and every item in the viewport is measured (nothing
    /// visible can move it any more).
    pub(super) fn follow_pin(&mut self, anchored: f32) -> Follow {
        let Some(mut pin) = self.pin else {
            return Follow::Stay;
        };
        if self.viewport <= 0.0 {
            return Follow::Stay;
        }
        let target = self.target_offset(pin.target);
        if pin.animating {
            // The platform moves an animation in flight along with the
            // anchoring scroll.
            pin.at += anchored;
            let follow = if (target - pin.at).abs() > PIN_SLACK {
                pin.at = target;
                Follow::To(target)
            } else {
                Follow::Stay
            };
            self.pin = Some(pin);
            return follow;
        }
        let delta = target - self.offset;
        if delta != 0.0 {
            self.jump(target);
        }
        pin.at = target;
        self.pin = (!self.viewport_measured()).then_some(pin);
        if delta == 0.0 {
            Follow::Stay
        } else {
            Follow::By(delta)
        }
    }

    /// Whether a scroll command's target is still followed.
    #[cfg(test)]
    pub(super) fn pinned(&self) -> bool {
        self.pin.is_some()
    }

    /// Whether every item overlapping the viewport has its measured size.
    fn viewport_measured(&self) -> bool {
        let start = self.natural_offset();
        self.items_in(start, start + self.viewport)
            .is_none_or(|(first, last)| {
                self.sizes[first as usize..=last as usize]
                    .iter()
                    .all(|s| !s.is_nan())
            })
    }

    // --- Geometry ----------------------------------------------------------

    fn effective(&self, i: usize) -> f32 {
        let s = self.sizes[i];
        if s.is_nan() { self.estimated } else { s }
    }

    fn row_count(&self) -> u32 {
        self.count.div_ceil(self.columns)
    }

    fn row_of(&self, i: u32) -> u32 {
        i / self.columns
    }

    /// Size of row `r`: its largest item.
    fn row_size(&self, r: u32) -> f32 {
        let start = (r * self.columns) as usize;
        let end = (start + self.columns as usize).min(self.sizes.len());
        (start..end).map(|i| self.effective(i)).fold(0.0, f32::max)
    }

    /// The gap between rows along the main axis.
    fn main_gap(&self) -> f32 {
        if self.horizontal {
            self.content.column_gap
        } else {
            self.content.row_gap
        }
    }

    /// The gap between columns.
    pub(super) fn cross_gap(&self) -> f32 {
        if self.horizontal {
            self.content.row_gap
        } else {
            self.content.column_gap
        }
    }

    /// Padding at the start / end of the main axis and of the cross axis.
    fn main_padding(&self) -> (f32, f32) {
        let p = &self.content.padding;
        if self.horizontal {
            (p.left, p.right)
        } else {
            (p.top, p.bottom)
        }
    }

    pub(super) fn cross_padding(&self) -> (f32, f32) {
        let p = &self.content.padding;
        if self.horizontal {
            (p.top, p.bottom)
        } else {
            (p.left, p.right)
        }
    }

    fn rows_changed(&mut self) {
        self.dirty = true;
    }

    fn rebuild_offsets(&mut self) {
        let gap = self.main_gap() as f64;
        let rows = (0..self.row_count()).map(|r| self.row_size(r) as f64 + gap);
        self.rows = Fenwick::from_sizes(rows.collect::<Vec<_>>().into_iter());
        self.dirty = true;
    }

    /// Length of the item rows (no trailing gap).
    fn items_len(&self) -> f32 {
        if self.count == 0 {
            0.0
        } else {
            self.rows.total() as f32 - self.main_gap()
        }
    }

    /// Start of each block of content, in natural coordinates.
    pub(super) fn blocks(&self) -> Blocks {
        let gap = self.main_gap();
        let (start, end) = self.main_padding();
        let [header, footer, empty] = &self.extras;
        let mut at = start;
        let mut any = false;
        let mut place = |present: bool, size: f32| {
            if !present {
                return at;
            }
            if any {
                at += gap;
            }
            any = true;
            let here = at;
            at += size;
            here
        };
        let header_at = place(header.present(), header.size);
        let body_at = if self.count > 0 {
            place(true, self.items_len())
        } else {
            place(empty.present(), empty.size)
        };
        let footer_at = place(footer.present(), footer.size);
        Blocks {
            header: header_at,
            body: body_at,
            footer: footer_at,
            total: at + end,
        }
    }

    /// Total content length along the main axis (what the platform
    /// scrolls).
    pub(super) fn content_len(&self) -> f32 {
        let total = self.blocks().total;
        if self.inverted {
            total.max(self.viewport)
        } else {
            total
        }
    }

    /// Content coordinate of a span at natural position `at` of length
    /// `size`.
    pub(super) fn to_content(&self, at: f32, size: f32) -> f32 {
        if self.inverted {
            self.content_len() - at - size
        } else {
            at
        }
    }

    /// The viewport's start in natural coordinates.
    fn natural_offset(&self) -> f32 {
        if self.inverted {
            self.content_len() - self.offset - self.viewport
        } else {
            self.offset
        }
    }

    /// Natural position of item `i` (its row's start).
    pub(super) fn item_at(&self, i: u32) -> f32 {
        self.blocks().body + self.rows.prefix(self.row_of(i) as usize) as f32
    }

    /// Size and position of each cell across the main axis: `(offset,
    /// size)` of column `col`.
    pub(super) fn column(&self, cross: f32, col: u32) -> (f32, f32) {
        let (start, end) = self.cross_padding();
        let gap = self.cross_gap();
        let n = self.columns as f32;
        let width = ((cross - start - end - gap * (n - 1.0)) / n).max(0.0);
        (start + col as f32 * (width + gap), width)
    }

    /// The cross-axis span of extras: the content width inside padding.
    pub(super) fn full_width(&self, cross: f32) -> (f32, f32) {
        let (start, end) = self.cross_padding();
        (start, (cross - start - end).max(0.0))
    }

    /// Main-axis size of item `i`'s row.
    pub(super) fn row_extent(&self, i: u32) -> f32 {
        self.row_size(self.row_of(i))
    }

    pub(super) fn column_of(&self, i: u32) -> u32 {
        i % self.columns
    }

    // --- Updates -----------------------------------------------------------

    pub(super) fn set_count(&mut self, count: u32) {
        if count == self.count {
            return;
        }
        self.count = count;
        self.sizes.resize(count as usize, f32::NAN);
        self.rebuild_offsets();
        if self.end_reached_at.is_some_and(|c| c != count) {
            self.end_reached_at = None;
        }
    }

    pub(super) fn set_estimated(&mut self, estimated: f32) {
        if estimated > 0.0 && estimated != self.estimated {
            self.estimated = estimated;
            self.rebuild_offsets();
        }
    }

    pub(super) fn set_columns(&mut self, columns: u32) {
        let columns = columns.max(1);
        if columns != self.columns {
            self.columns = columns;
            // Cells change width: their sizes are measured again.
            self.sizes.fill(f32::NAN);
            self.cells_cross = f32::NAN;
            self.rebuild_offsets();
        }
    }

    pub(super) fn set_content(&mut self, content: ListContentStyle) {
        if content != self.content {
            let cross_changed = self.cross_padding() != {
                let p = &content.padding;
                if self.horizontal {
                    (p.top, p.bottom)
                } else {
                    (p.left, p.right)
                }
            } || self.cross_gap()
                != if self.horizontal {
                    content.row_gap
                } else {
                    content.column_gap
                };
            self.content = content;
            if cross_changed {
                self.cells_cross = f32::NAN;
            }
            self.rebuild_offsets();
        }
    }

    pub(super) fn set_horizontal(&mut self, horizontal: bool) {
        if horizontal != self.horizontal {
            self.horizontal = horizontal;
            self.sizes.fill(f32::NAN);
            self.rebuild_offsets();
        }
    }

    pub(super) fn set_inverted(&mut self, inverted: bool) {
        if inverted != self.inverted {
            self.inverted = inverted;
            self.anchored_end = f32::NAN;
            self.dirty = true;
        }
    }

    pub(super) fn set_follow_end(&mut self, threshold: Option<f32>) {
        if threshold != self.follow_end {
            self.follow_end = threshold;
            self.anchored_end = f32::NAN;
            self.dirty = true;
        }
    }

    pub(super) fn set_sticky(&mut self, mut sticky: Vec<u32>) {
        sticky.sort_unstable();
        sticky.dedup();
        if sticky != self.sticky {
            self.sticky = sticky;
            self.dirty = true;
        }
    }

    /// Records a measured size. Returns the change if the item lies
    /// entirely before the viewport (the caller scrolls by it so the
    /// visible content stays put).
    pub(super) fn measured(&mut self, i: u32, size: f32) -> f32 {
        let idx = i as usize;
        if idx >= self.sizes.len() || self.sizes[idx] == size {
            return 0.0;
        }
        let row = self.row_of(i);
        let before = self.row_size(row);
        let row_start = self.item_at(i);
        let natural = self.natural_offset();
        let above_viewport = row_start < natural && row_start + before <= natural;
        self.sizes[idx] = size;
        let delta = self.row_size(row) - before;
        if delta != 0.0 {
            self.rows.add(row as usize, delta as f64);
        }
        self.dirty = true;
        if above_viewport && !self.inverted {
            delta
        } else {
            0.0
        }
    }

    /// Records the size of an extra cell; returns the anchoring change as
    /// [`ListState::measured`] does.
    pub(super) fn measured_extra(&mut self, kind: ExtraKind, size: f32) -> f32 {
        let blocks = self.blocks();
        let extra = &mut self.extras[kind as usize];
        if extra.size == size {
            return 0.0;
        }
        let delta = size - extra.size;
        extra.size = size;
        self.rows_changed();
        let at = match kind {
            ExtraKind::Header => blocks.header,
            ExtraKind::Footer => blocks.footer,
            ExtraKind::Empty => blocks.body,
        };
        // Inverted lists keep their distance from the end instead
        // (`anchor_end`). Otherwise: an extra entirely before the
        // viewport's start (not one that was empty at the top, with the
        // list at the top).
        let old_end = at + size - delta;
        if !self.inverted && at < self.offset && old_end <= self.offset {
            delta
        } else {
            0.0
        }
    }

    /// Inverted lists keep their distance from the end of the content:
    /// returns how far to scroll after content or viewport changes (and
    /// starts at the end). Other lists with `follow_end` stay at the end
    /// when the end moves away while they are within the threshold of it
    /// (a growing last item, a shrinking viewport); scrolled further up,
    /// they keep what is visible (content grows below it).
    pub(super) fn anchor_end(&mut self) -> f32 {
        if self.viewport <= 0.0 {
            return 0.0;
        }
        let end = (self.content_len() - self.viewport).max(0.0);
        if !self.inverted {
            let Some(threshold) = self.follow_end else {
                return 0.0;
            };
            let was = std::mem::replace(&mut self.anchored_end, end);
            if was.is_nan() || end <= was || was - self.offset > threshold {
                return 0.0;
            }
            let delta = end - self.offset;
            self.offset = end;
            return delta;
        }
        let delta = if self.anchored_end.is_nan() {
            end - self.offset
        } else {
            end - self.anchored_end
        };
        self.anchored_end = end;
        self.offset += delta;
        delta
    }

    /// The platform is about to scroll to `offset` (a command): the window
    /// follows it right away, and inverted lists anchor to it.
    pub(super) fn jump(&mut self, offset: f32) {
        self.offset = offset;
        if self.inverted {
            self.anchored_end = (self.content_len() - self.viewport).max(0.0);
        }
        self.dirty = true;
    }

    /// The content offset that shows item `index` at `view_position` (0:
    /// start of the viewport, 1: end) shifted by `view_offset`, clamped to
    /// the content.
    pub(super) fn offset_for_index(&self, index: u32, view_position: f32, view_offset: f32) -> f32 {
        let index = index.min(self.count.saturating_sub(1));
        let size = self.row_size(self.row_of(index));
        let at = self.to_content(self.item_at(index), size);
        let free = self.viewport - size;
        let offset = if self.inverted {
            // Mirrored like the inverted list itself.
            at - (1.0 - view_position) * free + view_offset
        } else {
            at - view_position * free - view_offset
        };
        offset.clamp(0.0, (self.content_len() - self.viewport).max(0.0))
    }

    pub(super) fn end_offset(&self) -> f32 {
        if self.inverted {
            0.0
        } else {
            (self.content_len() - self.viewport).max(0.0)
        }
    }

    // --- Cells -------------------------------------------------------------

    pub(super) fn add_slot_cell(&mut self, slot: CellSlot, cell: u32) {
        let s = match slot {
            CellSlot::Item(s) => s as usize,
            CellSlot::Header => return self.set_extra(ExtraKind::Header, cell),
            CellSlot::Footer => return self.set_extra(ExtraKind::Footer, cell),
            CellSlot::Empty => return self.set_extra(ExtraKind::Empty, cell),
        };
        if s >= self.slots.len() {
            self.slots.resize(
                s + 1,
                Slot {
                    cell: u32::MAX,
                    index: None,
                    rendered: None,
                },
            );
        }
        self.slots[s].cell = cell;
        self.dirty = true;
    }

    fn set_extra(&mut self, kind: ExtraKind, cell: u32) {
        self.extras[kind as usize] = Extra { cell, size: 0.0 };
        self.dirty = true;
    }

    pub(super) fn remove_cell(&mut self, cell: u32) {
        for slot in &mut self.slots {
            if slot.cell == cell {
                slot.cell = u32::MAX;
                slot.rendered = None;
                self.dirty = true;
            }
        }
        for extra in &mut self.extras {
            if extra.cell == cell {
                *extra = Extra::NONE;
                self.dirty = true;
            }
        }
    }

    pub(super) fn rendered(&mut self, cell: u32, index: u32) {
        if let Some(slot) = self.slots.iter_mut().find(|s| s.cell == cell) {
            slot.rendered = Some(index);
            self.dirty = true;
        }
    }

    // --- Window ------------------------------------------------------------

    /// Item range `first..=last` of rows overlapping the natural span
    /// `[start, end]`, or `None`.
    fn items_in(&self, start: f32, end: f32) -> Option<(u32, u32)> {
        if self.count == 0 {
            return None;
        }
        let body = self.blocks().body;
        if end < body || start > body + self.items_len() {
            return None;
        }
        let first_row = self.rows.find((start - body).max(0.0) as f64) as u32;
        let last_row =
            (self.rows.find((end - body).max(0.0) as f64) as u32).min(self.row_count() - 1);
        let first = first_row * self.columns;
        let last = ((last_row + 1) * self.columns - 1).min(self.count - 1);
        Some((first, last))
    }

    /// The span of content (main axis, content coordinates) whose items
    /// are rendered: the viewport and the overscan around it.
    pub(super) fn render_window(&self) -> (f32, f32) {
        let overscan = self.viewport * OVERSCAN;
        (
            self.offset - overscan,
            self.offset + self.viewport + overscan,
        )
    }

    /// The sticky item currently pinned to the viewport's start: the last
    /// one that starts before it.
    pub(super) fn active_sticky(&self) -> Option<u32> {
        if !self.sticky_enabled() {
            return None;
        }
        let at = self.natural_offset();
        let mut active = None;
        for &s in &self.sticky {
            if s >= self.count || self.item_at(s) > at {
                break;
            }
            active = Some(s);
        }
        active
    }

    /// Sticky items need one column and a list that is not inverted (as in
    /// React Native).
    pub(super) fn sticky_enabled(&self) -> bool {
        !self.sticky.is_empty() && self.columns == 1 && !self.inverted
    }

    /// The travel range of sticky item `index`: from its position to where
    /// the next sticky item pushes it out.
    pub(super) fn sticky_range(&self, index: u32, cell: u32, size: f32) -> StickyRange {
        let start = self.item_at(index);
        let next = self.sticky.iter().find(|&&s| s > index && s < self.count);
        let end = match next {
            Some(&n) => (self.item_at(n) - size).max(start),
            None => f32::INFINITY,
        };
        StickyRange { cell, start, end }
    }

    /// Recomputes the render window. New `(slot, index)` bindings are
    /// pushed to `binds`. Returns true if `onEndReached` should fire.
    pub(super) fn update_window(&mut self, binds: &mut Vec<(u32, u32)>) -> bool {
        self.dirty = false;
        if self.count == 0 || self.viewport <= 0.0 {
            for slot in 0..self.slots.len() {
                self.unbind(slot as u32);
            }
            return false;
        }
        // Cells whose item moved: the runtime learns their new index.
        binds.append(&mut self.moved);
        let at = self.natural_offset();
        let overscan = self.viewport * OVERSCAN;
        let range = self.items_in(at - overscan, at + self.viewport + overscan);
        let sticky = self.active_sticky();
        let wanted = |i: u32| range.is_some_and(|(f, l)| (f..=l).contains(&i)) || sticky == Some(i);

        for slot in 0..self.slots.len() as u32 {
            if let Some(i) = self.slots[slot as usize].index
                && !wanted(i)
            {
                self.unbind(slot);
            }
        }
        let mut bind = |this: &mut Self, i: u32| {
            if this.by_index.contains_key(&i) {
                return;
            }
            let slot = match this.free.pop() {
                Some(slot) => slot,
                None => {
                    this.slots.push(Slot {
                        cell: u32::MAX,
                        index: None,
                        rendered: None,
                    });
                    this.slots.len() as u32 - 1
                }
            };
            this.slots[slot as usize].index = Some(i);
            this.by_index.insert(i, slot);
            binds.push((slot, i));
        };
        if let Some((first, last)) = range {
            for i in first..=last {
                bind(self, i);
            }
        }
        if let Some(s) = sticky {
            bind(self, s);
        }

        let total = self.blocks().total;
        let near_end = at + self.viewport >= total - self.viewport * self.end_threshold;
        if near_end && self.end_reached_at != Some(self.count) {
            self.end_reached_at = Some(self.count);
            return true;
        }
        false
    }

    fn unbind(&mut self, slot: u32) {
        if let Some(i) = self.slots[slot as usize].index.take() {
            self.by_index.remove(&i);
            self.free.push(slot);
        }
    }

    /// The viewable items under the list's viewability rules (React
    /// Native's `ViewabilityHelper`): `first..=last`, or `None`.
    pub(super) fn viewable_items(&self) -> Option<(u32, u32)> {
        if self.viewport <= 0.0 {
            return None;
        }
        let top = self.natural_offset();
        let bottom = top + self.viewport;
        let (first, last) = self.items_in(top, bottom)?;
        let viewable = |row: u32| {
            let start = self.item_at(row * self.columns);
            let size = self.row_size(row);
            let end = start + size;
            if start >= top && end <= bottom {
                return true;
            }
            let pixels = (end.min(bottom) - start.max(top)).max(0.0);
            let (percent, threshold) = match (
                self.viewability.view_area_percent,
                self.viewability.item_visible_percent,
            ) {
                (Some(t), _) => (100.0 * pixels / self.viewport, t),
                (None, Some(t)) => (100.0 * pixels / size.max(f32::EPSILON), t),
                (None, None) => return pixels > 0.0,
            };
            if threshold > 0.0 {
                percent >= threshold
            } else {
                pixels > 0.0
            }
        };
        let (mut first_row, mut last_row) = (self.row_of(first), self.row_of(last));
        while first_row <= last_row && !viewable(first_row) {
            first_row += 1;
        }
        while last_row >= first_row && !viewable(last_row) {
            if last_row == 0 {
                return None;
            }
            last_row -= 1;
        }
        (first_row <= last_row).then(|| {
            (
                first_row * self.columns,
                ((last_row + 1) * self.columns - 1).min(self.count - 1),
            )
        })
    }
}

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

    fn list(count: u32, estimated: f32, viewport: f32) -> ListState {
        let mut l = ListState::new();
        l.set_estimated(estimated);
        l.set_count(count);
        l.viewport = viewport;
        l
    }

    #[test]
    fn window_covers_viewport_plus_overscan() {
        let mut l = list(1000, 50.0, 400.0);
        let mut binds = Vec::new();
        l.update_window(&mut binds);
        // [0, 800] at 50 per item -> items 0..=16.
        assert_eq!(binds.len(), 17);
        assert_eq!(binds[0], (0, 0));

        // Scroll down a screen: items scrolled far above are recycled.
        l.offset = 2000.0;
        binds.clear();
        l.update_window(&mut binds);
        let indices: Vec<u32> = binds.iter().map(|b| b.1).collect();
        assert_eq!(indices.first(), Some(&32));
        assert_eq!(indices.last(), Some(&56));
        // Slots were reused, not grown without bound.
        assert!(l.slots.len() <= 25 + 17, "{}", l.slots.len());
    }

    #[test]
    fn measurements_shift_offsets_and_anchor_above_viewport() {
        let mut l = list(100, 50.0, 400.0);
        l.offset = 1000.0;
        // Item 0 is above the viewport: growing it must scroll by the same.
        assert_eq!(l.measured(0, 80.0), 30.0);
        assert_eq!(l.item_at(1), 80.0);
        assert_eq!(l.blocks().total, 100.0 * 50.0 + 30.0);
        // Item 30 is in view: no anchoring.
        assert_eq!(l.measured(30, 10.0), 0.0);
    }

    #[test]
    fn end_reached_fires_once_per_count() {
        let mut l = list(10, 50.0, 400.0);
        let mut binds = Vec::new();
        assert!(
            l.update_window(&mut binds),
            "500 px of content in a 400 px viewport"
        );
        assert!(!l.update_window(&mut binds));
        l.set_count(20);
        l.offset = 600.0;
        assert!(l.update_window(&mut binds));
    }

    #[test]
    fn shrinking_count_unbinds() {
        let mut l = list(100, 50.0, 400.0);
        let mut binds = Vec::new();
        l.update_window(&mut binds);
        l.set_count(3);
        binds.clear();
        l.update_window(&mut binds);
        assert_eq!(l.slots.iter().filter(|s| s.index.is_some()).count(), 3);
    }

    #[test]
    fn columns_share_rows() {
        let mut l = list(10, 50.0, 1000.0);
        l.set_columns(3);
        // 4 rows of 50.
        assert_eq!(l.blocks().total, 200.0);
        assert_eq!(l.item_at(4), 50.0);
        assert_eq!(l.column_of(4), 1);
        // A row is as tall as its tallest item.
        l.measured(4, 80.0);
        assert_eq!(l.item_at(6), 130.0);
        assert_eq!(l.column(320.0, 2), (320.0 * 2.0 / 3.0, 320.0 / 3.0));
        let mut binds = Vec::new();
        l.update_window(&mut binds);
        assert_eq!(binds.len(), 10);
    }

    #[test]
    fn padding_gaps_and_extras() {
        let mut l = list(3, 50.0, 1000.0);
        l.set_content(ListContentStyle {
            padding: EdgeInsets {
                top: 10.0,
                right: 16.0,
                bottom: 20.0,
                left: 16.0,
            },
            row_gap: 8.0,
            column_gap: 0.0,
        });
        l.add_slot_cell(CellSlot::Header, 7);
        l.measured_extra(ExtraKind::Header, 30.0);
        l.add_slot_cell(CellSlot::Footer, 8);
        l.measured_extra(ExtraKind::Footer, 40.0);
        let b = l.blocks();
        assert_eq!(b.header, 10.0);
        assert_eq!(b.body, 10.0 + 30.0 + 8.0);
        // Three items with two gaps between them.
        assert_eq!(b.footer, b.body + 3.0 * 50.0 + 2.0 * 8.0 + 8.0);
        assert_eq!(b.total, b.footer + 40.0 + 20.0);
        assert_eq!(l.full_width(400.0), (16.0, 368.0));
        // No items: the empty placeholder takes their place.
        l.set_count(0);
        l.add_slot_cell(CellSlot::Empty, 9);
        l.measured_extra(ExtraKind::Empty, 100.0);
        let b = l.blocks();
        assert_eq!(b.footer, b.body + 100.0 + 8.0);
    }

    #[test]
    fn lists_follow_the_end_within_the_threshold() {
        let mut l = list(100, 50.0, 400.0);
        l.set_follow_end(Some(10.0));
        assert_eq!(l.anchor_end(), 0.0, "starts where it is");
        // At the end: the last item grows by 30, the list follows.
        l.offset = 5000.0 - 400.0;
        l.measured(99, 80.0);
        assert_eq!(l.anchor_end(), 30.0);
        assert_eq!(l.offset, 5030.0 - 400.0);
        // Scrolled up: it grows below what is visible, which stays.
        l.offset = 1000.0;
        l.measured(99, 120.0);
        assert_eq!(l.anchor_end(), 0.0);
        assert_eq!(l.offset, 1000.0);
        // Without the option, nothing follows.
        let mut m = list(100, 50.0, 400.0);
        m.anchor_end();
        m.offset = 5000.0 - 400.0;
        m.measured(99, 80.0);
        assert_eq!(m.anchor_end(), 0.0);
    }

    #[test]
    fn inverted_lists_start_at_the_end_and_keep_their_distance_from_it() {
        let mut l = list(100, 50.0, 400.0);
        l.set_inverted(true);
        // Starts scrolled to the end; item 0 is at the bottom.
        assert_eq!(l.anchor_end(), 5000.0 - 400.0);
        assert_eq!(l.to_content(l.item_at(0), 50.0), 4950.0);
        let mut binds = Vec::new();
        l.update_window(&mut binds);
        assert_eq!(binds.first().map(|b| b.1), Some(0));
        assert!(binds.iter().all(|b| b.1 <= 16));
        // Older items load (appended): the visible content stays put.
        l.set_count(120);
        assert_eq!(l.anchor_end(), 1000.0);
        assert_eq!(l.offset, 5600.0);
        assert_eq!(l.to_content(l.item_at(0), 50.0), 5950.0);
        // A short list sits at the bottom.
        let mut s = list(2, 50.0, 400.0);
        s.set_inverted(true);
        s.anchor_end();
        assert_eq!(s.offset, 0.0);
        assert_eq!(s.to_content(s.item_at(0), 50.0), 350.0);
    }

    #[test]
    fn sticky_items_stay_rendered_and_travel_until_the_next() {
        let mut l = list(100, 50.0, 400.0);
        l.set_sticky(vec![30, 0]);
        l.offset = 1000.0;
        assert_eq!(l.active_sticky(), Some(0));
        let mut binds = Vec::new();
        l.update_window(&mut binds);
        assert!(binds.iter().any(|b| b.1 == 0), "{binds:?}");
        assert_eq!(
            l.sticky_range(0, 1, 50.0),
            StickyRange {
                cell: 1,
                start: 0.0,
                end: 1450.0
            }
        );
        assert_eq!(l.sticky_range(30, 1, 50.0).end, f32::INFINITY);
        l.offset = 1600.0;
        assert_eq!(l.active_sticky(), Some(30));
    }

    #[test]
    fn viewability_thresholds() {
        let mut l = list(100, 100.0, 400.0);
        l.offset = 50.0;
        // Any visible pixel: items 0..=4.
        assert_eq!(l.viewable_items(), Some((0, 4)));
        l.viewability.item_visible_percent = Some(60.0);
        assert_eq!(l.viewable_items(), Some((1, 3)));
        l.viewability.item_visible_percent = Some(50.0);
        assert_eq!(l.viewable_items(), Some((0, 4)));
    }

    #[test]
    fn stale_offset_reports_keep_pending_scrolls() {
        let mut l = list(100, 50.0, 400.0);
        l.offset = 500.0;
        l.issue_scroll_by(30.0);
        // Reported before the platform applied the shift.
        l.reported(500.0, 0);
        assert_eq!(l.offset, 530.0);
        l.issue_scroll_to(1000.0);
        l.reported(531.0, 1);
        assert_eq!(l.offset, 1000.0);
        l.reported(1002.0, 2);
        assert_eq!(l.offset, 1002.0);
        assert!(l.pending.is_empty());
    }

    #[test]
    fn extras_at_the_top_do_not_scroll_the_list() {
        let mut l = list(0, 50.0, 400.0);
        l.add_slot_cell(CellSlot::Empty, 3);
        assert_eq!(l.measured_extra(ExtraKind::Empty, 65.0), 0.0);
        let mut l = list(100, 50.0, 400.0);
        l.add_slot_cell(CellSlot::Header, 3);
        assert_eq!(l.measured_extra(ExtraKind::Header, 30.0), 0.0);
        // Scrolled past it: the visible content keeps its place.
        l.offset = 500.0;
        assert_eq!(l.measured_extra(ExtraKind::Header, 40.0), 10.0);
        // Inverted lists anchor to their end instead.
        l.set_inverted(true);
        assert_eq!(l.measured_extra(ExtraKind::Header, 50.0), 0.0);
    }

    #[test]
    fn splices_keep_measurements_cells_and_the_visible_content() {
        let mut l = list(100, 50.0, 400.0);
        let mut binds = Vec::new();
        l.offset = 1000.0;
        l.update_window(&mut binds);
        for (slot, index) in binds.drain(..) {
            l.add_slot_cell(CellSlot::Item(slot), 100 + slot);
            l.rendered(100 + slot, index);
        }
        l.measured(25, 80.0);
        // Three items arrive at the top: item 20 (the first visible) keeps
        // its place on screen.
        let before = l.item_at(20) - l.offset;
        l.splice(0, 0, 3);
        assert_eq!(l.count, 103);
        assert_eq!(l.item_at(23) - l.offset, before);
        assert_eq!(l.take_splice_anchor(), 150.0);
        // Item 25's measurement moved with it.
        assert_eq!(l.row_extent(28), 80.0);
        // Cells follow their items, and the runtime is told.
        l.update_window(&mut binds);
        assert!(binds.iter().any(|&(_, i)| i == 28));
        assert!(l.slots.iter().any(|s| s.ready() == Some(28)));
        // A change below the viewport moves nothing.
        let offset = l.offset;
        l.splice(90, 2, 0);
        assert_eq!(l.offset, offset);
        assert_eq!(l.count, 101);
    }

    #[test]
    fn pins_follow_until_landed_measured_or_scrolled_away() {
        let mut l = list(100, 50.0, 400.0);
        // An animated scroll to the end: retargeted when the end moves,
        // corrected once it landed.
        l.pin(Some(PinTarget::End), 4600.0, true);
        l.issue_scroll_to(4600.0);
        l.measured(99, 90.0);
        assert_eq!(l.follow_pin(0.0), Follow::To(4640.0));
        l.issue_scroll_to(4640.0);
        l.reported(3000.0, 2);
        assert!(l.pinned(), "in flight");
        l.reported(4640.0, 2);
        l.measured(98, 60.0);
        assert_eq!(l.follow_pin(0.0), Follow::By(10.0));
        assert_eq!(l.offset, 4650.0);
        assert!(l.pinned(), "rows in the viewport not measured yet");
        // The user scrolls away: the pin ends.
        l.reported(4000.0, 2);
        assert!(!l.pinned());
        // Splices end it too.
        l.pin(Some(PinTarget::End), 4650.0, false);
        l.splice(0, 1, 0);
        assert!(!l.pinned());
    }

    #[test]
    fn scroll_to_index() {
        let mut l = list(100, 50.0, 400.0);
        assert_eq!(l.offset_for_index(10, 0.0, 0.0), 500.0);
        assert_eq!(l.offset_for_index(10, 0.5, 0.0), 500.0 - 175.0);
        assert_eq!(l.offset_for_index(99, 0.0, 0.0), 5000.0 - 400.0);
        l.set_inverted(true);
        // Item 0 at the bottom of the viewport.
        assert_eq!(l.offset_for_index(0, 0.0, 0.0), 4600.0);
    }
}