nsh-engine 0.7.2

Engine thread that drives the JS host and the core and emits mount batches.
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
//! The runtime's `List` with the engine: rows render, scrolling rebinds
//! recycled cells and `onLoadMore` reaches JS.

use std::{sync::mpsc, time::Duration};

use nsh_core::{ApproxTextEngine, MountBatch, MountItem, Size, ViewKind, geometry::px};
use nsh_engine::{Bundle, Engine, EngineConfig, MountSink};

/// Sends batches to the test, and answers a request for a display frame
/// at once, as a display would at its next refresh.
struct Sink(
    mpsc::Sender<MountBatch>,
    std::sync::Arc<std::sync::OnceLock<nsh_engine::EngineControl>>,
);

impl MountSink for Sink {
    fn submit(&self, batch: MountBatch) {
        let _ = self.0.send(batch);
    }

    fn request_frame(&self) {
        if let Some(control) = self.1.get() {
            control.frame();
        }
    }
}

/// `List`, made in place by the compiler.
const APP: &str = r#"
import { List, mount, signal, Text, View } from "nsh";
const rows = signal(Array.from({ length: 100 }, (_, i) => i));
function App() {
  return (
    <List each={rows()} estimatedItemSize={50} style={{ flex: 1 }}
          onLoadMore={() => rows.update((r) => [...r, ...Array.from({ length: 100 }, (_, i) => r.length + i)])}>
      {(row) => <View style={{ height: 50 }}><Text>{`row ${row()}`}</Text></View>}
    </List>
  );
}
mount(App);
"#;

fn texts(batch: &MountBatch) -> Vec<String> {
    batch
        .items
        .iter()
        .filter_map(|i| match i {
            MountItem::Text { text, .. } => Some(text.text.clone()),
            _ => None,
        })
        .collect()
}

fn cells_created(batch: &MountBatch) -> usize {
    // Each cell is a View whose child is the row View: count rows via text views.
    batch
        .items
        .iter()
        .filter(|i| {
            matches!(
                i,
                MountItem::Create {
                    kind: ViewKind::Text,
                    ..
                }
            )
        })
        .count()
}

#[test]
fn list_scrolls_with_recycled_cells() {
    scrolls_with_recycled_cells(APP);
}

/// `List` as a value (`const L = List; <L>`) is the same component as the
/// tag the compiler makes in place.
#[test]
fn list_as_a_value_scrolls_with_recycled_cells() {
    let app = APP
        .replace("<List ", "<Rows ")
        .replace("</List>", "</Rows>")
        .replace(
            "mount, signal, Text, View } from \"nsh\";",
            "mount, signal, Text, View } from \"nsh\";\nconst Rows = List;",
        );
    assert!(app.contains("<Rows "));
    scrolls_with_recycled_cells(&app);
}

/// Bundles `app` into a config for a 320 x 500 viewport, and the app's
/// directory (the caller removes it).
fn config(app: &str) -> (EngineConfig, std::path::PathBuf) {
    static APPS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
    let dir = std::env::temp_dir().join(format!(
        "nsh-list-{}-{}",
        std::process::id(),
        APPS.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
    ));
    std::fs::create_dir_all(&dir).unwrap();
    let entry = dir.join("App.tsx");
    std::fs::write(&entry, app).unwrap();
    let bundle = nsh_bundler::bundle(&nsh_bundler::BundleOptions {
        entry,
        minify: false,
        split: false,
        ui_sets: vec![nsh_base::registry().into()],
        ..Default::default()
    })
    .unwrap();
    let bytecode = nsh_js::compile_bytecode(&bundle.code, false).unwrap();
    let config = EngineConfig {
        // SAFETY: compiled just now by this runtime.
        app: nsh_engine::App::Js(unsafe { Bundle::bytecode(bytecode) }),
        viewport: Size::new(px(320.0), px(500.0)),
        trace: false,
        content_culling: false,
        network: None,
        websocket: None,
        refuse_connections: None,
        filesystem: None,
        assets: None,
        environment: Default::default(),
        header_heights: (nsh_core::Points(44.0), nsh_core::Points(96.0)),
        limits: nsh_engine::Limits::default(),
        ui_sets: Vec::new(),
        runtime: None,
        support_dir: None,
        cache: nsh_engine::CacheOptions::off(),
        storage: None,
        clock: Default::default(),
        context: Default::default(),
        pinned: Default::default(),
        clipboard: None,
        host: Default::default(),
        picker: None,
        audio: None,
        windows: None,
        login_item: None,
        data_dir: None,
    };
    (config, dir)
}

/// Bundles `app` and starts it on a 320 x 500 viewport: the engine, its
/// batches and the app's directory (the caller removes it).
fn start(app: &str) -> (Engine, mpsc::Receiver<MountBatch>, std::path::PathBuf) {
    let (config, dir) = config(app);
    let (tx, rx) = mpsc::channel();
    let control = std::sync::Arc::new(std::sync::OnceLock::new());
    let engine = Engine::start(config, || ApproxTextEngine, Sink(tx, control.clone())).unwrap();
    let _ = control.set(engine.control());
    // A frame asked for before the control was there.
    engine.control().frame();
    (engine, rx, dir)
}

fn scrolls_with_recycled_cells(app: &str) {
    let (engine, rx, dir) = start(app);
    let first = rx.recv_timeout(Duration::from_secs(5)).unwrap();
    // The first frame shows the viewport's rows; the overscan may follow.
    let first_texts = texts(&first);
    assert_eq!(first_texts[0], "row 0");
    for i in 0..10 {
        assert!(first_texts.contains(&format!("row {i}")), "{first_texts:?}");
    }
    let list = first
        .items
        .iter()
        .find_map(|i| match i {
            MountItem::Create {
                id,
                kind: ViewKind::Scroll,
            } => Some(*id),
            _ => None,
        })
        .unwrap();
    // 500 pt viewport + 500 pt overscan at 50 pt per row = 21 rows.
    let mut window = first_texts;
    while let Ok(batch) = rx.recv_timeout(Duration::from_millis(300)) {
        window.extend(texts(&batch));
    }
    assert_eq!(window.len(), 21, "{window:?}");

    // Scroll to row 40: rows 30..=60 are needed; cells are recycled, so the
    // update re-renders text in existing views instead of creating them.
    engine.control().scroll(
        list,
        nsh_core::geometry::point(nsh_core::geometry::px(0.0), nsh_core::geometry::px(2000.0)),
        u32::MAX,
    );
    let batch = rx.recv_timeout(Duration::from_secs(5)).unwrap();
    let shown = texts(&batch);
    assert!(shown.contains(&"row 40".to_owned()), "{shown:?}");
    assert!(
        cells_created(&batch) <= 10,
        "created {} text views",
        cells_created(&batch)
    );

    // Near the end: `onLoadMore` appends rows; the content grows.
    engine.control().scroll(
        list,
        nsh_core::geometry::point(nsh_core::geometry::px(0.0), nsh_core::geometry::px(4600.0)),
        u32::MAX,
    );
    let mut grew = false;
    while let Ok(batch) = rx.recv_timeout(Duration::from_secs(2)) {
        grew |= batch.items.iter().any(
            |i| matches!(i, MountItem::ScrollContent { size, .. } if size.height >= px(10_000.0)),
        );
        if grew {
            break;
        }
    }
    assert!(grew, "onLoadMore did not extend the list");
    let _ = std::fs::remove_dir_all(&dir);
}

/// A `List` in its parent's viewport: no scroll view of its own, its
/// rows follow the page's scroll view around it.
#[test]
fn a_list_in_a_pages_viewport_follows_the_page() {
    let app = r#"
import { List, mount, Scroll, Text, View } from "nsh";
const rows = Array.from({ length: 100 }, (_, i) => i);
function App() {
  return (
    <Scroll style={{ flex: 1 }}>
      <View style={{ height: 200 }}><Text>header</Text></View>
      <List viewport="parent" each={rows} estimatedItemSize={50}>
        {(row) => <View style={{ height: 50 }}><Text>{`row ${row()}`}</Text></View>}
      </List>
    </Scroll>
  );
}
mount(App);
"#;
    let (engine, rx, dir) = start(app);
    let mut items = Vec::new();
    while let Ok(batch) = rx.recv_timeout(Duration::from_millis(500)) {
        items.extend(batch.items);
    }
    let scrolls: Vec<u32> = items
        .iter()
        .filter_map(|i| match i {
            MountItem::Create {
                id,
                kind: ViewKind::Scroll,
            } => Some(*id),
            _ => None,
        })
        .collect();
    assert_eq!(scrolls.len(), 1, "the page's scroll view only");
    let page = scrolls[0];
    let shown: Vec<String> = items
        .iter()
        .filter_map(|i| match i {
            MountItem::Text { text, .. } => Some(text.text.clone()),
            _ => None,
        })
        .collect();
    // From the list's start, 200 down, to 500 below the viewport's end:
    // rows 0 to 16.
    assert!(shown.contains(&"row 16".to_owned()), "{shown:?}");
    assert!(!shown.contains(&"row 17".to_owned()), "{shown:?}");
    // The page's content covers the whole list.
    assert!(items.iter().any(|i| matches!(
        i,
        MountItem::ScrollContent { id, size } if *id == page && size.height == px(200.0 + 100.0 * 50.0)
    )));
    engine
        .control()
        .scroll(page, nsh_core::geometry::point(px(0.0), px(2000.0)), 0);
    let mut shown = Vec::new();
    let mut created = 0;
    while let Ok(batch) = rx.recv_timeout(Duration::from_millis(500)) {
        shown.extend(texts(&batch));
        created += cells_created(&batch);
    }
    // 1800 into the list: rows 26 to 56, in recycled cells.
    assert!(shown.contains(&"row 40".to_owned()), "{shown:?}");
    assert!(shown.contains(&"row 56".to_owned()), "{shown:?}");
    assert!(!shown.contains(&"row 57".to_owned()), "{shown:?}");
    assert!(created <= 14, "created {created} text views");
    let _ = std::fs::remove_dir_all(&dir);
}

/// The props `List` does not use itself reach its scroll view, as they do
/// a `<Scroll>`'s: the test id and accessibility (UI tests find the list),
/// classes, touch props and layout events; and they follow their signals.
#[test]
fn list_passes_host_props_to_its_scroll_view() {
    let app = r#"
import { List, mount, signal, Text, View } from "nsh";
const label = signal("Feed");
const size = signal("none");
function App() {
  return (
    <View style={{ flex: 1 }}>
      <Text>{`size ${size()}`}</Text>
      <List each={[1, 2, 3]} testID="feed" accessibilityLabel={label()} role="list"
            accessibilityHint="Posts" class="bg-red-500" style={{ pointerEvents: "box-none", flex: 1 }}
            onLayout={({ bounds: e }) => { size.set(`${e.size.width}x${e.size.height}`); label.set("Feed 2"); }}>
        {(row) => <View style={{ height: 50 }}><Text>{`row ${row()}`}</Text></View>}
      </List>
    </View>
  );
}
mount(App);
"#;
    let (_engine, rx, dir) = start(app);
    let mut items = Vec::new();
    let mut shown = Vec::new();
    while let Ok(batch) = rx.recv_timeout(Duration::from_secs(2)) {
        shown.extend(texts(&batch));
        items.extend(batch.items);
        if shown.iter().any(|t| t.starts_with("size 320")) {
            break;
        }
    }
    let list = items
        .iter()
        .find_map(|i| match i {
            MountItem::Create {
                id,
                kind: ViewKind::Scroll,
            } => Some(*id),
            _ => None,
        })
        .expect("a scroll view");
    let props = items
        .iter()
        .filter_map(|i| match i {
            MountItem::ViewProps { id, props } if *id == list => Some(props),
            _ => None,
        })
        .next_back()
        .expect("the list's view props");
    assert_eq!(props.test_id.as_deref(), Some("feed"));
    assert_eq!(props.accessibility.hint.as_deref(), Some("Posts"));
    assert_eq!(props.accessibility.role, nsh_core::AccessibilityRole::List);
    assert_eq!(props.pointer_events, nsh_core::PointerEvents::BoxNone);
    // The label follows its signal (set by `onLayout`).
    let labels: Vec<_> = items
        .iter()
        .filter_map(|i| match i {
            MountItem::ViewProps { id, props } if *id == list => props.accessibility.label.clone(),
            MountItem::AccessibilityLabel { id, label } if *id == list => label.clone(),
            _ => None,
        })
        .collect();
    assert_eq!(labels.first().map(|l| &**l), Some("Feed"), "{labels:?}");
    assert_eq!(labels.last().map(|l| &**l), Some("Feed 2"), "{labels:?}");
    // The class styles the scroll view.
    let red = items.iter().any(|i| {
        matches!(i, MountItem::ViewStyle { id, style }
            if *id == list && style.background_color != nsh_core::Color::TRANSPARENT)
    });
    assert!(red, "the class did not style the list");
    // `onLayout` reached JS with the list's size (under a 17 pt text).
    assert!(shown.iter().any(|t| t == "size 320x483"), "{shown:?}");
    let _ = std::fs::remove_dir_all(&dir);
}

/// What a [`Paced`] engine's sink saw: its errors and whether a display
/// frame was asked for.
#[derive(Default)]
struct Seen {
    errors: std::sync::Mutex<Vec<String>>,
    frame: std::sync::atomic::AtomicBool,
}

struct PacedSink(mpsc::Sender<MountBatch>, std::sync::Arc<Seen>);

impl MountSink for PacedSink {
    fn submit(&self, batch: MountBatch) {
        let _ = self.0.send(batch);
    }

    fn report_error(&self, message: &str) {
        self.1.errors.lock().unwrap().push(message.to_owned());
    }

    fn request_frame(&self) {
        self.1
            .frame
            .store(true, std::sync::atomic::Ordering::SeqCst);
    }
}

/// A list app on a [`nsh_engine::LocalEngine`], so a test sees every
/// turn's batch: [`Paced::turn`] is one pump, [`Paced::frame`] the display
/// frame the engine asked for. Keeps what each text view shows.
struct Paced {
    engine: nsh_engine::LocalEngine<ApproxTextEngine>,
    rx: mpsc::Receiver<MountBatch>,
    seen: std::sync::Arc<Seen>,
    texts: std::collections::HashMap<nsh_core::NodeId, String>,
    /// Text views made so far.
    created: usize,
    list: Option<nsh_core::NodeId>,
    pressable: Option<nsh_core::NodeId>,
    dir: std::path::PathBuf,
    /// Every item received, in order.
    items: Vec<MountItem>,
}

impl Paced {
    fn start(app: &str) -> Self {
        let (config, dir) = config(app);
        let (tx, rx) = mpsc::channel();
        let seen = std::sync::Arc::new(Seen::default());
        let engine =
            nsh_engine::LocalEngine::start(config, ApproxTextEngine, PacedSink(tx, seen.clone()))
                .expect("the app starts");
        let mut paced = Paced {
            engine,
            rx,
            seen,
            texts: Default::default(),
            created: 0,
            list: None,
            pressable: None,
            dir,
            items: Vec::new(),
        };
        paced.receive();
        paced
    }

    /// Applies the batches sent so far to the model; one `Vec` of the
    /// texts each batch set, per batch.
    fn receive(&mut self) -> Vec<Vec<String>> {
        let mut batches = Vec::new();
        while let Ok(batch) = self.rx.try_recv() {
            let mut set = Vec::new();
            self.items.extend(batch.items.iter().cloned());
            for item in &batch.items {
                match item {
                    MountItem::Text { id, text, .. } => {
                        self.texts.insert(*id, text.text.clone());
                        set.push(text.text.clone());
                    }
                    MountItem::Delete { id } => {
                        self.texts.remove(id);
                    }
                    MountItem::Create {
                        id,
                        kind: ViewKind::Scroll,
                    } => self.list = self.list.or(Some(*id)),
                    MountItem::Create {
                        kind: ViewKind::Text,
                        ..
                    } => self.created += 1,
                    MountItem::Events { id, events }
                        if events.contains(nsh_core::EventKind::Press) =>
                    {
                        self.pressable = Some(*id);
                    }
                    _ => {}
                }
            }
            batches.push(set);
        }
        batches
    }

    /// One wake-up of the engine: what was sent is handled and committed.
    fn turn(&mut self) -> Vec<Vec<String>> {
        self.engine.pump();
        self.receive()
    }

    /// The display frame the engine asked for, if it did.
    fn frame(&mut self) -> Option<Vec<Vec<String>>> {
        if !self
            .seen
            .frame
            .swap(false, std::sync::atomic::Ordering::SeqCst)
        {
            return None;
        }
        self.engine.control().frame();
        Some(self.turn())
    }

    /// Turns and frames until nothing changes, with `check` after each
    /// batch.
    fn settle(&mut self, mut check: impl FnMut(&Self, &[String])) {
        for _ in 0..500 {
            let mut batches = self.turn();
            if let Some(more) = self.frame() {
                batches.extend(more);
            }
            if batches.is_empty() && !self.seen.frame.load(std::sync::atomic::Ordering::SeqCst) {
                return;
            }
            for batch in &batches {
                check(self, batch);
            }
        }
        panic!("the list never settled");
    }

    fn scroll_to(&self, y: f32) {
        self.engine.control().scroll(
            self.list.expect("a list"),
            nsh_core::geometry::point(px(0.0), px(y)),
            u32::MAX,
        );
    }

    fn errors(&self) -> Vec<String> {
        self.seen.errors.lock().unwrap().clone()
    }

    /// Rows `first..=last` are what text views show.
    fn shows(&self, first: u32, last: u32) -> bool {
        (first..=last).all(|i| self.texts.values().any(|t| *t == format!("row {i}")))
    }
}

impl Drop for Paced {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.dir);
    }
}

/// Rows of objects (`row().label`), `count` of them, and a pressable view
/// whose press runs `press` on the rows signal.
fn rows_app(count: usize, mount_effect: &str, press: &str) -> String {
    format!(
        r#"
import {{ List, mount, signal, Text, View }} from "nsh";
const rows = signal(Array.from({{ length: {count} }}, (_, i) => ({{ label: `row ${{i}}` }})));
{mount_effect}
function App() {{
  return (
    <View style={{{{ flex: 1 }}}}>
      <View onPress={{() => {{ {press} }}}} style={{{{ height: 0 }}}} />
      <List each={{rows()}} estimatedItemSize={{50}} style={{{{ flex: 1 }}}}>
        {{(row) => <View style={{{{ height: 50 }}}}><Text>{{row().label}}</Text></View>}}
      </List>
    </View>
  );
}}
mount(App);
"#
    )
}

/// The data shrinking while cells of the first window wait to be bound:
/// cells whose items are gone are never asked for (a cell made for an
/// index past the end would read `undefined`).
#[test]
fn shrinking_rows_before_the_window_is_bound_binds_no_missing_item() {
    let app = rows_app(
        100,
        "setTimeout(() => rows.set(rows().slice(0, 3)), 0);",
        "",
    );
    let mut paced = Paced::start(&app);
    paced.settle(|_, _| {});
    assert_eq!(paced.errors(), Vec::<String>::new());
    assert!(paced.shows(0, 2), "{:?}", paced.texts);
}

/// `header`, `footer` and `empty` that are one `<If>` or `<Each>` follow
/// their conditions: a memo is the slot's to track, not a component to
/// call once.
#[test]
fn slots_follow_their_if_and_each() {
    let app = r#"
import { List, mount, signal, Text, View } from "nsh";
const on = signal(false);
function App() {
  return (
    <View style={{ flex: 1 }}>
      <View onPress={() => on.set(!on())} style={{ height: 0 }} />
      <List each={[] as string[]} style={{ flex: 1 }}
            header={<If when={on()}><Text>header</Text></If>}
            footer={<Each of={on() ? [] : ["footer"]}>{(t) => <Text>{t()}</Text>}</Each>}
            empty={<If when={on()}><Text>empty</Text></If>}>
        {(row) => <Text>{row()}</Text>}
      </List>
    </View>
  );
}
mount(App);
"#;
    let mut paced = Paced::start(app);
    paced.settle(|_, _| {});
    let shown = |paced: &Paced| {
        let mut texts: Vec<_> = paced.texts.values().cloned().collect();
        texts.sort();
        texts
    };
    assert_eq!(shown(&paced), ["footer"]);
    for expected in [&["empty", "header"][..], &["footer"]] {
        paced.engine.control().dispatch_event(
            paced.pressable.expect("the pressable view"),
            nsh_core::EventKind::Press,
            nsh_core::EventPayload::None,
        );
        paced.settle(|_, _| {});
        assert_eq!(shown(&paced), expected);
    }
    assert_eq!(paced.errors(), Vec::<String>::new());
}

/// A `separator` that is one `<If>` keeps following its condition after
/// rows move: what its getter makes lives with the cell, not with the
/// computation that reruns when the cell's index changes.
#[test]
fn a_separator_follows_its_if_after_rows_move() {
    let app = r#"
import { List, mount, signal, Text, View } from "nsh";
const on = signal(false);
const items = signal(["a", "b", "c"]);
const steps = [
  () => on.set(true),
  () => items.set(["z", "a", "b", "c"]),
  () => on.set(false),
  () => on.set(true),
];
function App() {
  return (
    <View style={{ flex: 1 }}>
      <View onPress={() => steps.shift()?.()} style={{ height: 0 }} />
      <List each={items()} style={{ flex: 1 }} separator={<If when={on()}><Text>sep</Text></If>}>
        {(row) => <Text>{row()}</Text>}
      </List>
    </View>
  );
}
mount(App);
"#;
    let mut paced = Paced::start(app);
    paced.settle(|_, _| {});
    let separators = |paced: &Paced| paced.texts.values().filter(|t| *t == "sep").count();
    assert_eq!(separators(&paced), 0);
    for expected in [2, 3, 0, 3] {
        paced.engine.control().dispatch_event(
            paced.pressable.expect("the pressable view"),
            nsh_core::EventKind::Press,
            nsh_core::EventPayload::None,
        );
        paced.settle(|_, _| {});
        assert_eq!(separators(&paced), expected);
    }
    assert_eq!(paced.errors(), Vec::<String>::new());
}

/// A row added above keeps every cell on its row in every batch: cells
/// whose item moved learn their new index in the commit of the change.
/// The list is at its start, so the new row shows at once, in a cell the
/// window no longer needs at its far end; no cell shows a neighbour's
/// row meanwhile.
#[test]
fn prepending_a_row_never_shows_a_cell_with_its_neighbours_row() {
    let app = rows_app(100, "", "rows.update((r) => [{ label: \"new\" }, ...r]);");
    let mut paced = Paced::start(&app);
    paced.settle(|_, _| {});
    assert!(paced.shows(0, 20), "{:?}", paced.texts);
    let before = paced.texts.clone();
    paced.engine.control().dispatch_event(
        paced.pressable.expect("the pressable view"),
        nsh_core::EventKind::Press,
        nsh_core::EventPayload::None,
    );
    let mut wrong = Vec::new();
    paced.settle(|paced, _| {
        for (id, text) in &before {
            let now = paced.texts.get(id);
            if now != Some(text) && now.map(String::as_str) != Some("new") {
                wrong.push((text.clone(), now.cloned()));
            }
        }
    });
    assert!(wrong.is_empty(), "cells showed another row: {wrong:?}");
    assert!(paced.texts.values().any(|t| t == "new"));
    assert_eq!(paced.errors(), Vec::<String>::new());
}

/// A window of rows that slides (a chat keeping its newest messages): one
/// update drops the first row and appends one, rows rebuilt as new objects
/// with the same keys. The rows read far down stay on screen, though rows
/// are taller than estimated: the change at each end is its own splice,
/// so the rows between keep their measured sizes and the viewport keeps
/// its rows in place.
#[test]
fn a_sliding_window_of_rows_keeps_the_rows_on_screen() {
    let app = r#"
import { List, mount, signal, Text, View } from "nsh";
const rows = signal(Array.from({ length: 240 }, (_, i) => ({ label: `row ${i}` })));
const first = signal("");
let next = 240;
function App() {
  return (
    <View style={{ flex: 1 }}>
      <View onPress={() => rows.update((r) => [...r.slice(1).map((row) => ({ ...row })), { label: `row ${next++}` }])} style={{ height: 0 }} />
      <Text>{`first ${first()}`}</Text>
      <List each={rows()} keyExtractor={(row) => row.label} estimatedItemSize={50} style={{ flex: 1 }}
            onViewableItemsChange={({ viewableItems }) => first.set(viewableItems.filter((t) => t.isViewable).sort((a, b) => a.index - b.index)[0]?.key ?? "")}>
        {(row) => <View style={{ height: 80 }}><Text>{row().label}</Text></View>}
      </List>
    </View>
  );
}
mount(App);
"#;
    let mut paced = Paced::start(app);
    paced.settle(|_, _| {});
    // Down to row 190, a step at a time, so the rows on the way are measured.
    for y in (0..=190 * 80).step_by(400) {
        paced.scroll_to(y as f32);
        paced.settle(|_, _| {});
    }
    let first = |paced: &Paced| {
        paced
            .texts
            .values()
            .find(|t| t.starts_with("first "))
            .cloned()
    };
    let read = first(&paced);
    assert_eq!(read.as_deref(), Some("first row 190"));
    for _ in 0..3 {
        paced.engine.control().dispatch_event(
            paced.pressable.expect("the pressable view"),
            nsh_core::EventKind::Press,
            nsh_core::EventPayload::None,
        );
        paced.settle(|_, _| {});
        assert_eq!(first(&paced), read);
    }
    assert_eq!(paced.errors(), Vec::<String>::new());
}

/// A keyed row that moves up (an item that sorts first once it changes),
/// its rows rebuilt as new objects with the same keys: the row and the rows
/// it passes keep their cells, so no view is made and no text drawn again,
/// with or without a layout animation; under one, the moved row slides
/// from where it showed to its new place.
#[test]
fn moving_a_keyed_row_keeps_every_cell_on_its_row() {
    use std::collections::HashMap;

    use nsh_core::NodeId;
    const APP: &str = r#"
import { LayoutAnimation, List, mount, signal, Text, View } from "nsh";
const rows = signal(Array.from({ length: 100 }, (_, i) => ({ label: `row ${i}` })));
function App() {
  const up = () => {
    ANIMATE
    rows.update((r) => {
      const next = r.map((row) => ({ ...row }));
      next.splice(2, 0, ...next.splice(10, 1));
      return next;
    });
  };
  return (
    <View style={{ flex: 1 }}>
      <View onPress={up} style={{ height: 0 }} />
      <List each={rows()} keyExtractor={(row) => row.label} estimatedItemSize={50} style={{ flex: 1 }}>
        {(row) => <View style={{ height: 50 }}><Text>{row().label}</Text></View>}
      </List>
    </View>
  );
}
mount(App);
"#;
    for animated in [false, true] {
        let animate = "LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);";
        let app = APP.replace("ANIMATE", if animated { animate } else { "" });
        let mut paced = Paced::start(&app);
        paced.settle(|_, _| {});
        assert!(paced.shows(0, 12), "{:?}", paced.texts);
        let list = paced.list.expect("the list");
        let mut parents: HashMap<NodeId, NodeId> = HashMap::new();
        let mut frames = HashMap::new();
        for item in std::mem::take(&mut paced.items) {
            match item {
                MountItem::Insert { parent, child, .. } => {
                    parents.insert(child, parent);
                }
                MountItem::Frame { id, frame } => {
                    frames.insert(id, frame);
                }
                _ => {}
            }
        }
        let cell_of = |mut id: NodeId| loop {
            let parent = parents[&id];
            if parent == list {
                return id;
            }
            id = parent;
        };
        let moved = paced
            .texts
            .iter()
            .find_map(|(id, t)| (t == "row 10").then_some(cell_of(*id)))
            .unwrap();
        let (before, created) = (paced.texts.clone(), paced.created);
        paced.engine.control().dispatch_event(
            paced.pressable.expect("the pressable view"),
            nsh_core::EventKind::Press,
            nsh_core::EventPayload::None,
        );
        let mut drawn = Vec::new();
        paced.settle(|_, set| drawn.extend_from_slice(set));
        assert!(drawn.is_empty(), "animated {animated}: drew {drawn:?}");
        assert_eq!(paced.created, created, "animated {animated}: views made");
        assert_eq!(paced.texts, before, "animated {animated}");
        // The moved row's cell: placed at its new row, sliding there from
        // its old one under the layout animation.
        let mut animation = None;
        let mut placed = None;
        for item in &paced.items {
            match item {
                MountItem::LayoutAnimation(a) => animation = a.update,
                MountItem::Frame { id, frame } if *id == moved => {
                    placed = Some((frame.origin.y.0, animation.is_some()));
                }
                _ => {}
            }
        }
        assert_eq!(frames[&moved].origin.y.0, 500.0);
        assert_eq!(placed, Some((100.0, animated)), "animated {animated}");
        assert_eq!(paced.errors(), Vec::<String>::new());
    }
}

/// A row added at the start of an inverted list (a chat's new message)
/// leaves the other cells on their rows: rows made again by key
/// (`<Each of={[key]}>`) are not made again, only the new one is made.
#[test]
fn prepending_a_row_makes_only_that_row() {
    let app = r#"
import { List, mount, signal, Text, View } from "nsh";
const rows = signal(Array.from({ length: 100 }, (_, i) => ({ label: `row ${i}` })));
function App() {
  return (
    <View style={{ flex: 1 }}>
      <View onPress={() => rows.update((r) => [{ label: "new" }, ...r])} style={{ height: 0 }} />
      <List each={rows()} inverted estimatedItemSize={50} style={{ flex: 1 }}>
        {(row) => (
          <Each of={[row().label]}>
            {(label) => <View style={{ height: 50 }}><Text>{label()}</Text></View>}
          </Each>
        )}
      </List>
    </View>
  );
}
mount(App);
"#;
    let mut paced = Paced::start(app);
    paced.settle(|_, _| {});
    assert!(paced.shows(0, 10), "{:?}", paced.texts);
    let before = paced.created;
    paced.engine.control().dispatch_event(
        paced.pressable.expect("the pressable view"),
        nsh_core::EventKind::Press,
        nsh_core::EventPayload::None,
    );
    paced.settle(|_, _| {});
    assert!(paced.texts.values().any(|t| t == "new"));
    assert_eq!(paced.created - before, 1, "rows made again");
    assert_eq!(paced.errors(), Vec::<String>::new());
}

/// A row added at the start of an inverted list under a layout animation
/// (a chat's new message): the rows that showed slide up from where they
/// were on screen, though the list scrolls to keep its distance from the
/// end, and the cell the new row takes appears at its place instead of
/// moving from the row it showed before.
#[test]
fn a_layout_animation_slides_an_inverted_lists_rows() {
    let app = r#"
import { LayoutAnimation, List, mount, signal, Text, View } from "nsh";
const rows = signal(Array.from({ length: 100 }, (_, i) => ({ label: `row ${i}` })));
function App() {
  const add = () => {
    LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
    rows.update((r) => [{ label: "new" }, ...r]);
  };
  return (
    <View style={{ flex: 1 }}>
      <View onPress={add} style={{ height: 0 }} />
      <List each={rows()} inverted estimatedItemSize={50} style={{ flex: 1 }}>
        {(row) => <View style={{ height: 50 }}><Text>{row().label}</Text></View>}
      </List>
    </View>
  );
}
mount(App);
"#;
    use std::collections::HashMap;

    use nsh_core::{NodeId, geometry::Bounds};
    let mut paced = Paced::start(app);
    paced.settle(|_, _| {});
    let list = paced.list.expect("the list");
    // What a platform holds: each view's parent and frame, the label each
    // cell shows.
    let mut parents: HashMap<NodeId, NodeId> = HashMap::new();
    let mut frames: HashMap<NodeId, Bounds<nsh_core::geometry::Points>> = HashMap::new();
    let mut apply = |items: &[MountItem], parents: &mut HashMap<NodeId, NodeId>| {
        for item in items {
            match item {
                MountItem::Insert { parent, child, .. } => {
                    parents.insert(*child, *parent);
                }
                MountItem::Frame { id, frame } => {
                    frames.insert(*id, *frame);
                }
                _ => {}
            }
        }
    };
    let cell_of = |parents: &HashMap<NodeId, NodeId>, mut id: NodeId| loop {
        let parent = *parents.get(&id)?;
        if parent == list {
            return Some(id);
        }
        id = parent;
    };
    let before_items = std::mem::take(&mut paced.items);
    apply(&before_items, &mut parents);
    let labels = |paced: &Paced, parents: &HashMap<NodeId, NodeId>| -> HashMap<NodeId, String> {
        paced
            .texts
            .iter()
            .filter_map(|(id, text)| Some((cell_of(parents, *id)?, text.clone())))
            .collect()
    };
    drop(apply);
    let before = labels(&paced, &parents);
    let at_before = frames.clone();

    paced.engine.control().dispatch_event(
        paced.pressable.expect("the pressable view"),
        nsh_core::EventKind::Press,
        nsh_core::EventPayload::None,
    );
    paced.turn();
    let batch = std::mem::take(&mut paced.items);
    // Replays the batch: each frame with the layout animation before it,
    // from the frame the view had then.
    let mut model = at_before.clone();
    let mut animation = None;
    let mut scrolled = 0.0;
    let mut created = std::collections::HashSet::new();
    let mut last: HashMap<NodeId, (Bounds<_>, bool)> = HashMap::new();
    for item in &batch {
        match item {
            MountItem::LayoutAnimation(a) => animation = a.update,
            MountItem::Create { id, .. } => {
                created.insert(*id);
            }
            MountItem::Insert { parent, child, .. } => {
                parents.insert(*child, *parent);
            }
            MountItem::ScrollBy { id, dy, .. } if *id == list => scrolled += dy.0,
            MountItem::Frame { id, frame } => {
                let from = model.insert(*id, *frame);
                let animated = animation.is_some() && from.is_some() && !created.contains(id);
                last.insert(*id, (from.unwrap_or(*frame), animated));
            }
            _ => {}
        }
    }
    paced.receive();
    let after = labels(&paced, &parents);
    assert!(
        scrolled > 0.0,
        "an inverted list keeps its distance from the end"
    );
    let mut checked = 0;
    for (cell, label) in &after {
        let Some(&(from, animated)) = last.get(cell) else {
            // No frame: the scroll moved it at once.
            assert!(
                before.get(cell) != Some(label) || scrolled == 0.0,
                "{label} jumped with the scroll"
            );
            continue;
        };
        if label == "new" {
            assert!(
                !animated,
                "the new row moved from another row's place to its own"
            );
            continue;
        }
        if before.get(cell) != Some(label) {
            continue;
        }
        let shown = at_before[cell].origin.y.0;
        assert!(animated, "{label} did not slide");
        assert_eq!(
            from.origin.y.0 - scrolled,
            shown,
            "{label} did not start where it showed"
        );
        assert_eq!(model[cell].origin.y.0, shown - 50.0 + scrolled, "{label}");
        checked += 1;
    }
    assert!(checked >= 10, "rows checked: {checked}");
    assert!(after.values().any(|l| l == "new"));
    assert_eq!(paced.errors(), Vec::<String>::new());
}

/// A fling that moves the window faster than cells bind: once it stops,
/// only rows of the window it stopped at are bound (requests for windows
/// already left are dropped, not bound late).
#[test]
fn a_fling_binds_no_row_of_a_window_left_behind() {
    let app = rows_app(2000, "", "");
    let mut paced = Paced::start(&app);
    paced.settle(|_, _| {});
    let mut binds = 0;
    for step in 1..=20 {
        paced.scroll_to(step as f32 * 1500.0);
        binds += paced.turn().iter().map(Vec::len).sum::<usize>();
        if let Some(batches) = paced.frame() {
            binds += batches.iter().map(Vec::len).sum::<usize>();
        }
    }
    // The last window: a viewport of overscan on either side of 30000.
    let window = (30_000 - 500) / 50..=(30_000 + 500 + 500) / 50;
    let mut stale = Vec::new();
    paced.settle(|_, batch| {
        binds += batch.len();
        for text in batch {
            let row: u32 = text.trim_start_matches("row ").parse().unwrap();
            if !window.contains(&row) {
                stale.push(row);
            }
        }
    });
    assert!(stale.is_empty(), "bound after the fling: rows {stale:?}");
    assert!(paced.shows(600, 609), "{:?}", paced.texts);
    eprintln!("fling: {binds} binds");
    assert_eq!(paced.errors(), Vec::<String>::new());
}

/// A jump binds what it shows first: the batch of the jump holds every
/// visible row; the overscan around it may follow.
#[test]
fn a_jump_binds_the_visible_rows_first() {
    let app = rows_app(2000, "", "");
    let mut paced = Paced::start(&app);
    paced.settle(|_, _| {});
    paced.scroll_to(5000.0);
    let batches = paced.turn();
    let first = batches.first().expect("a batch for the jump");
    for i in 100..=109 {
        assert!(
            first.contains(&format!("row {i}")),
            "row {i} missing from the jump's batch: {first:?}"
        );
    }
    paced.settle(|_, _| {});
    assert!(paced.shows(90, 120), "{:?}", paced.texts);
}

/// A list opened at an old page loads the newer one when the user scrolls
/// back to its start (`onLoadMoreAtStart`), not where it opens; the rows
/// on screen keep their place as the page arrives above them.
#[test]
fn list_loads_more_at_its_start_after_the_user_scrolls_there() {
    let app = r#"
import { List, mount, signal, Text, View } from "nsh";
const rows = signal(Array.from({ length: 100 }, (_, i) => 100 + i));
const starts = signal(0);
function App() {
  return (
    <View style={{ flex: 1 }}>
      <Text>{`starts ${starts()}`}</Text>
      <List each={rows()} estimatedItemSize={50} style={{ flex: 1 }}
            onLoadMoreAtStart={() => {
              starts.set(starts() + 1);
              rows.update((r) => [...Array.from({ length: 100 }, (_, i) => r[0] - 100 + i), ...r]);
            }}>
        {(row) => <View style={{ height: 50 }}><Text>{`row ${row()}`}</Text></View>}
      </List>
    </View>
  );
}
mount(App);
"#;
    let (engine, rx, dir) = start(app);
    let first = rx.recv_timeout(Duration::from_secs(5)).unwrap();
    let shown = texts(&first);
    assert!(shown.contains(&"starts 0".to_owned()), "{shown:?}");
    assert!(shown.contains(&"row 100".to_owned()), "{shown:?}");
    let list = first
        .items
        .iter()
        .find_map(|i| match i {
            MountItem::Create {
                id,
                kind: ViewKind::Scroll,
            } => Some(*id),
            _ => None,
        })
        .unwrap();
    let scroll = |y: f32| {
        engine
            .control()
            .scroll(list, nsh_core::geometry::point(px(0.0), px(y)), u32::MAX)
    };
    let fired = |batches: &[MountBatch], label: &str| {
        batches.iter().any(|b| texts(b).iter().any(|t| t == label))
    };
    let drain = |wait: u64| {
        std::iter::from_fn(|| rx.recv_timeout(Duration::from_millis(wait)).ok()).collect::<Vec<_>>()
    };
    // Where it opens is not an approach; away from the start, nothing.
    scroll(2000.0);
    assert!(!fired(&drain(300), "starts 1"), "fired away from the start");
    // Back near the start: one load, and the rows on screen stay (the new
    // page is 100 rows of 50 pt above them).
    scroll(100.0);
    let batches = drain(500);
    assert!(fired(&batches, "starts 1"), "onLoadMoreAtStart did not run");
    let kept = batches.iter().flat_map(|b| &b.items).any(
        |i| matches!(i, MountItem::ScrollBy { id, dy, .. } if *id == list && *dy == px(5000.0)),
    );
    assert!(kept, "the visible rows did not keep their place");
    // 5000 pt from the start now: nothing more.
    assert!(!fired(&drain(300), "starts 2"), "fired again");
    let _ = std::fs::remove_dir_all(&dir);
}

/// `ref.measureScrollPosition()` answers, after the layout of the turn
/// that asks, which row the viewport starts in and how far into it, as
/// the list lays out its rows of different sizes.
#[test]
fn a_list_measures_where_its_viewport_starts() {
    let app = r#"
import { List, mount, signal, Text, View, type ListRef } from "nsh";
const shown = signal("waiting");
let list!: ListRef;
function App() {
  return (
    <View style={{ flex: 1 }}>
      <Text>{shown()}</Text>
      <List ref={list} each={Array.from({ length: 100 }, (_, i) => i)} estimatedItemSize={50} style={{ flex: 1 }}
            onScroll={async () => {
              const at = await list.measureScrollPosition();
              shown.set(at ? `at ${at.index} ${at.offset}` : "none");
            }}>
        {(row) => <View style={{ height: 40 + (row() % 3) * 20 }} />}
      </List>
    </View>
  );
}
mount(App);
"#;
    let (engine, rx, dir) = start(app);
    let first = rx.recv_timeout(Duration::from_secs(5)).unwrap();
    let list = first
        .items
        .iter()
        .find_map(|i| match i {
            MountItem::Create {
                id,
                kind: ViewKind::Scroll,
            } => Some(*id),
            _ => None,
        })
        .unwrap();
    while rx.recv_timeout(Duration::from_millis(300)).is_ok() {}
    // Rows of 40, 60 and 80 points: row 8 starts at 460.
    engine.control().scroll(
        list,
        nsh_core::geometry::point(px(0.0), px(500.0)),
        u32::MAX,
    );
    let shown: Vec<String> = std::iter::from_fn(|| rx.recv_timeout(Duration::from_secs(2)).ok())
        .flat_map(|b| texts(&b))
        .collect();
    assert!(shown.iter().any(|t| t == "at 8 40"), "{shown:?}");
    let _ = std::fs::remove_dir_all(&dir);
}

/// The empty cell goes with its list: a list taken away while it shows
/// its `empty` slot disposes what the slot made. It used to stay alive
/// under a root no one disposed, its effects still running, its owner's
/// freed slot taken by later nodes (#1984).
#[test]
fn the_empty_cell_goes_with_its_list() {
    let app = r#"
import { effect, List, mount, signal, Text, untracked, View } from "nsh";
const shown = signal(true);
const tick = signal(0);
const runs = signal(0);
const steps = [() => shown.set(false), () => tick.set(1)];
function Empty() {
  effect(() => {
    tick();
    untracked(() => runs.set(runs() + 1));
  });
  return <Text>empty</Text>;
}
function App() {
  return (
    <View style={{ flex: 1 }}>
      <View onPress={() => steps.shift()?.()} style={{ height: 0 }} />
      <Text>{`runs ${runs()}`}</Text>
      <If when={shown()}>
        <List each={[] as string[]} style={{ flex: 1 }} empty={<Empty />}>
          {(row) => <Text>{row()}</Text>}
        </List>
      </If>
    </View>
  );
}
mount(App);
"#;
    let mut paced = Paced::start(app);
    paced.settle(|_, _| {});
    let has = |paced: &Paced, text: &str| paced.texts.values().any(|t| t == text);
    let runs = |paced: &Paced| {
        paced
            .texts
            .values()
            .find(|t| t.starts_with("runs "))
            .cloned()
    };
    assert!(has(&paced, "empty"), "{:?}", paced.texts);
    let before = runs(&paced);
    for _ in 0..2 {
        paced.engine.control().dispatch_event(
            paced.pressable.expect("the pressable view"),
            nsh_core::EventKind::Press,
            nsh_core::EventPayload::None,
        );
        paced.settle(|_, _| {});
    }
    assert_eq!(
        runs(&paced),
        before,
        "the empty cell's effect ran after its list went: {:?}",
        paced.texts
    );
    assert_eq!(paced.errors(), Vec::<String>::new());
}

/// The overscan waiting to bind is bound once a display frame, on the
/// frame's turn: the turns between two frames (a timer, a message from
/// the main thread) bind none of it, so a frame gets one paced slice
/// (#2472). It all comes in the end.
#[test]
fn paced_overscan_binds_only_on_display_frames() {
    // Rows of 12 views each: the overscan takes several slices.
    let app = r#"
import { List, mount, Text, View } from "nsh";
const rows = Array.from({ length: 100 }, (_, i) => i);
function App() {
  return (
    <List each={rows} estimatedItemSize={50} style={{ flex: 1 }}>
      {(row) => (
        <View style={{ height: 50, flexDirection: "row" }}>
          {Array.from({ length: 12 }, (_, c) => <View><Text>{`row ${row()}.${c}`}</Text></View>)}
        </View>
      )}
    </List>
  );
}
mount(App);
"#;
    let mut paced = Paced::start(app);
    // The platform sends display frames from here on.
    paced.frame().expect("the app asks for a frame");
    let mut frames = 1;
    let mut slices = 0;
    while paced.seen.frame.load(std::sync::atomic::Ordering::SeqCst) {
        for _ in 0..3 {
            let between = paced.turn();
            assert!(
                between.iter().all(Vec::is_empty),
                "a turn between frames bound overscan: {between:?}"
            );
        }
        let batches = paced.frame().expect("a frame was asked for");
        frames += 1;
        if batches.iter().any(|b| !b.is_empty()) {
            slices += 1;
        }
        assert!(frames < 500, "the overscan never finished binding");
    }
    assert!(slices > 1, "the overscan was paced over frames ({slices})");
    assert!(
        (0..=20).all(|i| paced.texts.values().any(|t| *t == format!("row {i}.11"))),
        "{:?}",
        paced.texts
    );
    assert_eq!(paced.errors(), Vec::<String>::new());
}