vertigo 0.13.1

Reactive Real-DOM library with SSR for Rust
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
use std::{collections::VecDeque, hash::Hash, rc::Rc};

use crate::{
    Computed, DomComment, DomNode, KeyedListItem, ToComputed, dom::dom_id::DomId,
    driver_module::get_driver_dom, fast_hash::FastMap, keyed_computed_list, struct_mut::ValueMut,
};

/// Render an iterable as a keyed list of DOM nodes.
///
/// Each key keeps a stable [`Computed`](crate::Computed) (via [`keyed_computed_list`]).
/// `render` is called when a key **appears**; the node is dropped when the key
/// **leaves**. Item content updates go through that `Computed` — embed it in
/// `dom!`, or wrap with [`Computed::render_value`](crate::Computed::render_value).
///
/// Duplicate keys are skipped (first occurrence is kept).
///
/// Coming from 0.12, where the closure re-ran whenever an item's value changed under an
/// unchanged key: wrap the old body in `render_value`. Reading the value out with
/// `transaction(|ctx| item.get(ctx))` compiles but is a plain read rather than a
/// subscription, so the row renders once and then never updates — use it only for a row
/// that is constant for its key.
///
/// ```rust
/// use vertigo::{dom, Value, render::render_list};
///
/// let my_list = Value::new(vec![
///     (1, "one"),
///     (2, "two"),
///     (3, "three"),
/// ]);
///
/// let elements = render_list(
///     &my_list.to_computed(),
///     |el| el.0,
///     |el| el.render_value(|el| dom! { <div>{el.1}</div> })
/// );
///
/// dom! {
///     <div>
///         {elements}
///     </div>
/// };
/// ```
pub fn render_list<
    T: Clone + PartialEq + 'static,
    K: Clone + Eq + Hash + std::fmt::Debug + 'static,
>(
    computed: impl ToComputed<Vec<T>>,
    get_key: impl Fn(&T) -> K + 'static,
    render: impl Fn(&Computed<T>) -> DomNode + 'static,
) -> DomNode {
    let rows = keyed_computed_list(computed, get_key);
    let render = Rc::new(render);

    DomComment::new_marker("list element", move |parent_id, comment_id, content| {
        let current_list: Rc<ValueMut<VecDeque<(K, Row)>>> =
            Rc::new(ValueMut::new(VecDeque::new()));

        Some(rows.clone().subscribe({
            let render = render.clone();
            let content = content.clone();

            move |new_list| {
                current_list.change(|current| {
                    let prev = std::mem::take(current);
                    *current = reorder_nodes(
                        parent_id,
                        comment_id,
                        prev,
                        VecDeque::from(new_list),
                        render.as_ref(),
                    );

                    content.set(
                        current
                            .iter()
                            .flat_map(|(_, row)| [row.anchor_id(), row.node.id_dom()])
                            .collect(),
                    );
                })
            }
        }))
    })
    .into()
}

/// One rendered row of the list.
///
/// A row is not necessarily a single sibling under the list parent:
/// [`render_value`](crate::Computed::render_value) keeps its content *in front of*
/// its own marker and re-creates it every time that marker is mounted. `anchor` is
/// an empty comment kept directly in front of the row, so that whatever shape the
/// row has, it always has one stable node marking where it begins — that is what
/// insert and move operations anchor on.
struct Row {
    anchor: DomComment,
    node: DomNode,
}

impl Row {
    fn new(node: DomNode) -> Row {
        Row {
            anchor: DomComment::new("row"),
            node,
        }
    }

    fn anchor_id(&self) -> DomId {
        self.anchor.id_dom()
    }

    /// Insert the row - or move it, when it is already mounted - in front of `before`.
    fn insert_before(&self, parent_id: DomId, before: DomId) {
        let driver = get_driver_dom();

        driver.insert_before(parent_id, self.anchor.id_dom(), Some(before));
        // Mounting the node renders its content in front of itself, which lands
        // between the anchor and the node.
        driver.insert_before(parent_id, self.node.id_dom(), Some(before));
    }
}

fn reorder_nodes<T: Clone + PartialEq + 'static, K: Clone + Eq + Hash>(
    parent_id: DomId,
    comment_id: DomId,
    mut real_child: VecDeque<(K, Row)>,
    mut new_child: VecDeque<KeyedListItem<K, Computed<T>>>,
    render: &dyn Fn(&Computed<T>) -> DomNode,
) -> VecDeque<(K, Row)> {
    let pairs_top = get_pairs_top(&mut real_child, &mut new_child);
    let mut pairs_bottom = get_pairs_bottom(&mut real_child, &mut new_child);

    let last_before = pairs_bottom
        .front()
        .map(|(_, row)| row.anchor_id())
        .unwrap_or(comment_id);

    let mut pairs_middle = get_pairs_middle(parent_id, last_before, real_child, new_child, render);

    let mut pairs = pairs_top;
    pairs.append(&mut pairs_middle);
    pairs.append(&mut pairs_bottom);
    pairs
}

fn get_pairs_top<T: Clone + PartialEq, K: PartialEq>(
    current: &mut VecDeque<(K, Row)>,
    new_child: &mut VecDeque<KeyedListItem<K, Computed<T>>>,
) -> VecDeque<(K, Row)> {
    let mut pairs_top = VecDeque::new();

    loop {
        match (current.pop_front(), new_child.pop_front()) {
            (Some((key, node)), Some(item)) => {
                if key == item.key {
                    pairs_top.push_back((key, node));
                    continue;
                }

                current.push_front((key, node));
                new_child.push_front(item);
            }
            (Some(pair), None) => current.push_front(pair),
            (None, Some(item)) => new_child.push_front(item),
            (None, None) => {}
        }

        return pairs_top;
    }
}

fn get_pairs_bottom<T: Clone + PartialEq, K: PartialEq>(
    current: &mut VecDeque<(K, Row)>,
    new_child: &mut VecDeque<KeyedListItem<K, Computed<T>>>,
) -> VecDeque<(K, Row)> {
    let mut pairs_bottom = VecDeque::new();

    loop {
        match (current.pop_back(), new_child.pop_back()) {
            (Some((key, node)), Some(item)) => {
                if key == item.key {
                    pairs_bottom.push_front((key, node));
                    continue;
                }

                current.push_back((key, node));
                new_child.push_back(item);
            }
            (Some(pair), None) => current.push_back(pair),
            (None, Some(item)) => new_child.push_back(item),
            (None, None) => {}
        }

        return pairs_bottom;
    }
}

fn get_pairs_middle<T: Clone + PartialEq + 'static, K: Clone + Eq + Hash>(
    parent_id: DomId,
    last_before: DomId,
    real_child: VecDeque<(K, Row)>,
    new_child: VecDeque<KeyedListItem<K, Computed<T>>>,
    render: &dyn Fn(&Computed<T>) -> DomNode,
) -> VecDeque<(K, Row)> {
    let mut cache: FastMap<K, (usize, Row)> = real_child
        .into_iter()
        .enumerate()
        .map(|(index, (key, row))| (key, (index, row)))
        .collect();

    // The middle in its new order, each surviving row carrying where it used to be.
    // Rows the cache does not know are new, and are rendered here.
    let mut rows: Vec<(K, Row, Option<usize>)> = Vec::with_capacity(new_child.len());

    for item in new_child {
        match cache.remove(&item.key) {
            Some((was_at, row)) => rows.push((item.key, row, Some(was_at))),
            None => rows.push((item.key, Row::new(render(&item.value)), None)),
        }
    }

    let settled = rows_already_in_order(&rows);

    // Right to left, so that every row anchors on the one that follows it - which by then is
    // already in its final position, whether it was moved or left alone.
    let mut before = last_before;

    for (index, (_, row, _)) in rows.iter().enumerate().rev() {
        if !settled[index] {
            row.insert_before(parent_id, before);
        }

        before = row.anchor_id();
    }

    // Whatever is left in the cache is a row that left the list; dropping it removes its DOM.
    rows.into_iter().map(|(key, row, _)| (key, row)).collect()
}

/// Which rows are already in the right order relative to each other, and so need no move.
///
/// This is a longest-increasing-subsequence over the rows' previous positions. Any set of
/// surviving rows whose old positions ascend is, by construction, already in the correct
/// relative order in the document - so only the rows *outside* that set have to be
/// re-inserted. Taking the longest such set is what makes the number of moves minimal.
fn rows_already_in_order<K>(rows: &[(K, Row, Option<usize>)]) -> Vec<bool> {
    let mut settled = vec![false; rows.len()];

    // Patience sorting. `tails[length - 1]` is the row index ending the increasing run of
    // that length with the smallest possible tail; `previous` threads each row back to its
    // predecessor so the winning run can be walked out at the end.
    let mut tails: Vec<usize> = Vec::new();
    let mut previous: Vec<Option<usize>> = vec![None; rows.len()];

    for (index, (_, _, was_at)) in rows.iter().enumerate() {
        // A row that did not exist before has to be inserted no matter what the others do.
        let Some(was_at) = *was_at else {
            continue;
        };

        let position = tails.partition_point(|tail| match rows[*tail].2 {
            Some(tail_was_at) => tail_was_at < was_at,
            // `tails` only ever holds surviving rows, so this arm is unreachable. Treating it
            // as "not smaller" keeps the search total rather than panicking on a future edit.
            None => false,
        });

        previous[index] = position.checked_sub(1).map(|earlier| tails[earlier]);

        match tails.get_mut(position) {
            Some(tail) => *tail = index,
            None => tails.push(index),
        }
    }

    let mut cursor = tails.last().copied();

    while let Some(index) = cursor {
        settled[index] = true;
        cursor = previous[index];
    }

    settled
}

#[cfg(test)]
mod tests {
    use std::{cell::Cell, rc::Rc};

    use super::{Row, render_list, reorder_nodes};
    use crate::{self as vertigo, dom};
    use crate::{
        Computed, DomId, DomNode, KeyedListItem, Value,
        dev::inspect::{DomDebugFragment, log_start},
    };

    fn row(key: u32, label: &str) -> (u32, String) {
        (key, label.to_string())
    }

    fn item(key: u32, label: &str) -> KeyedListItem<u32, Computed<String>> {
        KeyedListItem {
            key,
            value: Computed::from({
                let label = label.to_string();
                move |_| label.clone()
            }),
        }
    }

    fn mount_render_value_list(items: &Value<Vec<(u32, String)>>) -> DomNode {
        let list = render_list(
            items,
            |item| item.0,
            |item| item.render_value(|item| dom! { <li>{item.1.as_str()}</li> }),
        );
        dom! { <ul>{list}</ul> }
    }

    fn pseudo_html(items: &Value<Vec<(u32, String)>>) -> String {
        log_start();
        let _root = mount_render_value_list(items);
        DomDebugFragment::from_log().to_pseudo_html()
    }

    fn pseudo_html_after(items: &Value<Vec<(u32, String)>>, update: impl FnOnce()) -> String {
        log_start();
        let _root = mount_render_value_list(items);
        update();
        DomDebugFragment::from_log().to_pseudo_html()
    }

    fn row_html(label: &str) -> String {
        format!("<!-- row --><li>{label}</li><!-- v -->")
    }

    fn list_html(rows: &[&str]) -> String {
        format!(
            "<ul>{rows}<!-- list element --></ul>",
            rows = rows.iter().map(|label| row_html(label)).collect::<String>()
        )
    }

    /// A row whose root is a plain element (no `render_value` wrapper around it).
    fn mount_element_list(items: &Value<Vec<(u32, String)>>) -> DomNode {
        let list = render_list(
            items,
            |item| item.0,
            |item| {
                let label = item.map(|item| item.1);
                dom! { <li>{label}</li> }
            },
        );
        dom! { <ul>{list}</ul> }
    }

    fn element_pseudo_html_after(
        items: &Value<Vec<(u32, String)>>,
        update: impl FnOnce(),
    ) -> String {
        log_start();
        let _root = mount_element_list(items);
        update();
        DomDebugFragment::from_log().to_pseudo_html()
    }

    /// A row whose body is an interpolated reactive value. That embeds as a self-patching
    /// text node, so - unlike the `render_value` rows above - it leaves no marker comment
    /// inside the element.
    fn element_list_html(rows: &[&str]) -> String {
        format!(
            "<ul>{rows}<!-- list element --></ul>",
            rows = rows
                .iter()
                .map(|label| format!("<!-- row --><li>{label}</li>"))
                .collect::<String>()
        )
    }

    #[test]
    fn element_rows_prepend() {
        let items = Value::new(vec![row(2, "two"), row(3, "three")]);

        let html = element_pseudo_html_after(&items, || {
            items.set(vec![row(1, "one"), row(2, "two"), row(3, "three")]);
        });

        assert_eq!(html, element_list_html(&["one", "two", "three"]));
    }

    #[test]
    fn element_rows_insert_in_middle() {
        let items = Value::new(vec![row(1, "one"), row(3, "three")]);

        let html = element_pseudo_html_after(&items, || {
            items.set(vec![row(1, "one"), row(2, "two"), row(3, "three")]);
        });

        assert_eq!(html, element_list_html(&["one", "two", "three"]));
    }

    /// The trailing row is untouched, so the moved rows have to anchor on it
    /// instead of on the list marker.
    #[test]
    fn element_rows_reorder_in_middle() {
        let items = Value::new(vec![
            row(1, "one"),
            row(2, "two"),
            row(3, "three"),
            row(4, "four"),
        ]);

        let html = element_pseudo_html_after(&items, || {
            items.set(vec![
                row(1, "one"),
                row(3, "three"),
                row(2, "two"),
                row(4, "four"),
            ]);
        });

        assert_eq!(html, element_list_html(&["one", "three", "two", "four"]));
    }

    /// A row only ever anchors on nodes it owns, so unrelated siblings under the
    /// same parent keep their place.
    #[test]
    fn sibling_before_the_list_keeps_its_place() {
        let items = Value::new(vec![row(2, "two"), row(3, "three"), row(4, "four")]);

        log_start();
        let list = render_list(
            &items,
            |item| item.0,
            |item| item.render_value(|item| dom! { <li>{item.1.as_str()}</li> }),
        );
        let _root = dom! { <ul><li>"header"</li>{list}</ul> };
        items.set(vec![
            row(1, "one"),
            row(3, "three"),
            row(2, "two"),
            row(4, "four"),
        ]);

        let rows = ["one", "three", "two", "four"]
            .iter()
            .map(|label| row_html(label))
            .collect::<String>();

        assert_eq!(
            DomDebugFragment::from_log().to_pseudo_html(),
            format!("<ul><li>header</li>{rows}<!-- list element --></ul>")
        );
    }

    /// Two lists interleaved under one parent: each moves only its own rows.
    #[test]
    fn two_lists_in_the_same_parent_do_not_interfere() {
        let left = Value::new(vec![row(1, "l1"), row(2, "l2")]);
        let right = Value::new(vec![row(1, "r1"), row(2, "r2"), row(3, "r3")]);

        log_start();
        let left_list = render_list(
            &left,
            |item| item.0,
            |item| item.render_value(|item| dom! { <li>{item.1.as_str()}</li> }),
        );
        let right_list = render_list(
            &right,
            |item| item.0,
            |item| item.render_value(|item| dom! { <li>{item.1.as_str()}</li> }),
        );
        let _root = dom! { <ul>{left_list}{right_list}</ul> };

        right.set(vec![row(2, "r2"), row(1, "r1"), row(3, "r3")]);

        let left_rows = ["l1", "l2"]
            .iter()
            .map(|label| row_html(label))
            .collect::<String>();
        let right_rows = ["r2", "r1", "r3"]
            .iter()
            .map(|label| row_html(label))
            .collect::<String>();

        assert_eq!(
            DomDebugFragment::from_log().to_pseudo_html(),
            format!("<ul>{left_rows}<!-- list element -->{right_rows}<!-- list element --></ul>")
        );
    }

    /// A row that is itself a list spans several siblings of the outer list's
    /// parent, none of which is at a fixed offset from the row's own node.
    #[test]
    fn row_that_is_itself_a_list_reorders() {
        let items = Value::new(vec![row(1, "one"), row(2, "two"), row(3, "three")]);

        log_start();
        let list = render_list(
            &items,
            |item| item.0,
            |item| {
                let labels = item.map(|item| vec![item.1]);
                render_list(
                    labels,
                    |label| label.clone(),
                    |label| label.render_value(|label| dom! { <li>{label}</li> }),
                )
            },
        );
        let _root = dom! { <ul>{list}</ul> };
        items.set(vec![row(2, "two"), row(1, "one"), row(3, "three")]);

        let rows = ["two", "one", "three"]
            .iter()
            .map(|label| {
                format!("<!-- row --><!-- row --><li>{label}</li><!-- v --><!-- list element -->")
            })
            .collect::<String>();

        assert_eq!(
            DomDebugFragment::from_log().to_pseudo_html(),
            format!("<ul>{rows}<!-- list element --></ul>")
        );
    }

    /// A key appearing during an update runs `render` while the graph is mid-refresh, so
    /// the nested list this row renders is built at that point.
    #[test]
    fn row_that_is_itself_a_list_can_be_added_during_an_update() {
        let items = Value::new(vec![row(1, "one")]);

        log_start();
        let list = render_list(
            &items,
            |item| item.0,
            |item| {
                let labels = item.map(|item| vec![item.1]);
                render_list(
                    labels,
                    |label| label.clone(),
                    |label| label.render_value(|label| dom! { <li>{label}</li> }),
                )
            },
        );
        let _root = dom! { <ul>{list}</ul> };
        items.set(vec![row(1, "one"), row(2, "two")]);

        let rows = ["one", "two"]
            .iter()
            .map(|label| {
                format!("<!-- row --><!-- row --><li>{label}</li><!-- v --><!-- list element -->")
            })
            .collect::<String>();

        assert_eq!(
            DomDebugFragment::from_log().to_pseudo_html(),
            format!("<ul>{rows}<!-- list element --></ul>")
        );
    }

    #[test]
    fn key_removed_and_added_again() {
        let items = Value::new(vec![row(1, "one"), row(2, "two"), row(3, "three")]);

        let html = pseudo_html_after(&items, || {
            items.set(vec![row(1, "one"), row(3, "three")]);
            items.set(vec![row(1, "one"), row(2, "two"), row(3, "three")]);
        });

        assert_eq!(html, list_html(&["one", "two", "three"]));
    }

    #[test]
    fn renders_three_items_in_source_order() {
        let items = Value::new(vec![row(1, "one"), row(2, "two"), row(3, "three")]);

        assert_eq!(pseudo_html(&items), list_html(&["one", "two", "three"]));
    }

    #[test]
    fn updates_item_content_without_rerendering() {
        let items = Value::new(vec![row(1, "one")]);
        let render_calls = Rc::new(Cell::new(0));

        log_start();
        let list = render_list(&items, |item| item.0, {
            let render_calls = render_calls.clone();
            move |item| {
                render_calls.set(render_calls.get() + 1);
                item.render_value(|item| dom! { <li>{item.1.as_str()}</li> })
            }
        });
        let _root = dom! { <ul>{list}</ul> };
        assert_eq!(render_calls.get(), 1);

        items.set(vec![row(1, "two")]);

        let html = DomDebugFragment::from_log().to_pseudo_html();
        assert_eq!(render_calls.get(), 1);
        assert_eq!(html, list_html(&["two"]));
    }

    #[test]
    fn appends_item_after_initial_render() {
        let items = Value::new(vec![row(1, "one"), row(2, "two")]);

        let html = pseudo_html_after(&items, || {
            items.set(vec![row(1, "one"), row(2, "two"), row(3, "three")]);
        });

        assert_eq!(html, list_html(&["one", "two", "three"]));
    }

    #[test]
    fn removes_item_from_middle() {
        let items = Value::new(vec![row(1, "one"), row(2, "two"), row(3, "three")]);

        let html = pseudo_html_after(&items, || {
            items.set(vec![row(1, "one"), row(3, "three")]);
        });

        assert_eq!(html, list_html(&["one", "three"]));
    }

    #[test]
    fn removes_all_items() {
        let items = Value::new(vec![row(1, "one"), row(2, "two")]);

        let html = pseudo_html_after(&items, || {
            items.set(Vec::new());
        });

        assert_eq!(html, "<ul><!-- list element --></ul>");
    }

    #[test]
    fn reorders_items_in_middle() {
        let items = Value::new(vec![row(1, "one"), row(2, "two"), row(3, "three")]);

        let html = pseudo_html_after(&items, || {
            items.set(vec![row(1, "one"), row(3, "three"), row(2, "two")]);
        });

        assert_eq!(html, list_html(&["one", "three", "two"]));
    }

    #[test]
    fn prepends_item() {
        let items = Value::new(vec![row(2, "two"), row(3, "three")]);

        let html = pseudo_html_after(&items, || {
            items.set(vec![row(1, "one"), row(2, "two"), row(3, "three")]);
        });

        assert_eq!(html, list_html(&["one", "two", "three"]));
    }

    /// Moving a row must carry its DOM along, not rebuild it — a rebuilt row loses
    /// focus, selection, scroll position and running animations.
    #[test]
    fn moving_a_row_keeps_its_content() {
        let items = Value::new(vec![
            row(1, "one"),
            row(2, "two"),
            row(3, "three"),
            row(4, "four"),
        ]);
        let content_renders = Rc::new(Cell::new(0));

        log_start();
        let list = render_list(&items, |item| item.0, {
            let content_renders = content_renders.clone();
            move |item| {
                let content_renders = content_renders.clone();
                item.render_value(move |item| {
                    content_renders.set(content_renders.get() + 1);
                    dom! { <li>{item.1.as_str()}</li> }
                })
            }
        });
        let _root = dom! { <ul>{list}</ul> };
        assert_eq!(content_renders.get(), 4);

        items.set(vec![
            row(1, "one"),
            row(3, "three"),
            row(2, "two"),
            row(4, "four"),
        ]);

        assert_eq!(
            content_renders.get(),
            4,
            "moving a row must not re-render its content"
        );
        assert_eq!(
            DomDebugFragment::from_log().to_pseudo_html(),
            list_html(&["one", "three", "two", "four"])
        );
    }

    /// A moved row keeps its subscription, so a later value change still lands in the
    /// row's new position rather than where it used to be.
    #[test]
    fn updating_a_moved_row_replaces_content_in_place() {
        let items = Value::new(vec![
            row(1, "one"),
            row(2, "two"),
            row(3, "three"),
            row(4, "four"),
        ]);

        let html = pseudo_html_after(&items, || {
            items.set(vec![
                row(1, "one"),
                row(3, "three"),
                row(2, "two"),
                row(4, "four"),
            ]);
            items.set(vec![
                row(1, "one"),
                row(3, "three"),
                row(2, "TWO"),
                row(4, "four"),
            ]);
        });

        assert_eq!(html, list_html(&["one", "three", "TWO", "four"]));
    }

    /// The same guarantee one level down: moving a row whose node is a nested marker
    /// must not rebuild the nested subtree either.
    #[test]
    fn moving_a_row_keeps_nested_content() {
        let items = Value::new(vec![
            row(1, "one"),
            row(2, "two"),
            row(3, "three"),
            row(4, "four"),
        ]);
        let content_renders = Rc::new(Cell::new(0));

        log_start();
        let list = render_list(&items, |item| item.0, {
            let content_renders = content_renders.clone();
            move |item| {
                let label = item.map(|item| item.1);
                let content_renders = content_renders.clone();
                item.render_value(move |_| {
                    let content_renders = content_renders.clone();
                    label.render_value(move |label| {
                        content_renders.set(content_renders.get() + 1);
                        dom! { <li>{label}</li> }
                    })
                })
            }
        });
        let _root = dom! { <ul>{list}</ul> };
        assert_eq!(content_renders.get(), 4);

        items.set(vec![
            row(1, "one"),
            row(3, "three"),
            row(2, "two"),
            row(4, "four"),
        ]);

        assert_eq!(
            content_renders.get(),
            4,
            "moving a row must not re-render its nested content"
        );
    }

    /// A row that occupies more than two siblings: the inner `render_value` adds
    /// its own marker, so the row is `[anchor][content][inner marker][outer marker]`.
    #[test]
    fn nested_render_value_rows_reorder() {
        let items = Value::new(vec![
            row(1, "one"),
            row(2, "two"),
            row(3, "three"),
            row(4, "four"),
        ]);

        log_start();
        let list = render_list(
            &items,
            |item| item.0,
            |item| {
                let label = item.map(|item| item.1);
                item.render_value(move |_| label.render_value(|label| dom! { <li>{label}</li> }))
            },
        );
        let _root = dom! { <ul>{list}</ul> };
        items.set(vec![
            row(1, "one"),
            row(3, "three"),
            row(2, "two"),
            row(4, "four"),
        ]);

        let rows = ["one", "three", "two", "four"]
            .iter()
            .map(|label| format!("<!-- row --><li>{label}</li><!-- v --><!-- v -->"))
            .collect::<String>();

        assert_eq!(
            DomDebugFragment::from_log().to_pseudo_html(),
            format!("<ul>{rows}<!-- list element --></ul>")
        );
    }

    #[test]
    fn renders_without_render_value_markers() {
        let items = Value::new(vec![row(1, "one"), row(2, "two"), row(3, "three")]);

        log_start();
        let list = render_list(
            &items,
            |item| item.0,
            |item| crate::transaction(|ctx| dom! { <li>{item.get(ctx).1.as_str()}</li> }),
        );
        let _root = dom! { <ul>{list}</ul> };

        assert_eq!(
            DomDebugFragment::from_log().to_pseudo_html(),
            "<ul><!-- row --><li>one</li><!-- row --><li>two</li><!-- row --><li>three</li><!-- list element --></ul>"
        );
    }

    #[test]
    fn renders_empty_list_then_populates() {
        let items = Value::new(Vec::<(u32, String)>::new());

        let html = pseudo_html_after(&items, || {
            items.set(vec![row(1, "one")]);
        });

        assert_eq!(html, list_html(&["one"]));
    }

    #[test]
    fn skips_duplicate_keys() {
        let items = Value::new(vec![row(1, "first"), row(1, "duplicate"), row(2, "two")]);

        assert_eq!(pseudo_html(&items), list_html(&["first", "two"]));
    }

    #[test]
    fn reuses_node_when_key_stays() {
        let existing = Row::new(DomNode::from("same"));
        let node_id = existing.node.id_dom();
        let render_calls = Rc::new(std::cell::Cell::new(0usize));

        let result = reorder_nodes(
            DomId::from_u64(200),
            DomId::from_u64(201),
            std::collections::VecDeque::from([(1, existing)]),
            std::collections::VecDeque::from([item(1, "same")]),
            &{
                let render_calls = render_calls.clone();
                move |value: &Computed<String>| {
                    render_calls.set(render_calls.get() + 1);
                    crate::transaction(|ctx| DomNode::from(value.get(ctx)))
                }
            },
        );

        assert_eq!(result.len(), 1);
        assert_eq!(render_calls.get(), 0);
        assert_eq!(result[0].1.node.id_dom(), node_id);
    }

    #[test]
    fn renders_only_the_new_key() {
        let existing = Row::new(DomNode::from("old"));
        let existing_id = existing.node.id_dom();
        let render_calls = Rc::new(std::cell::Cell::new(0usize));

        let result = reorder_nodes(
            DomId::from_u64(100),
            DomId::from_u64(101),
            std::collections::VecDeque::from([(1, existing)]),
            std::collections::VecDeque::from([item(1, "old"), item(2, "new")]),
            &{
                let render_calls = render_calls.clone();
                move |value: &Computed<String>| {
                    render_calls.set(render_calls.get() + 1);
                    crate::transaction(|ctx| DomNode::from(value.get(ctx)))
                }
            },
        );

        assert_eq!(result.len(), 2);
        assert_eq!(result[0].1.node.id_dom(), existing_id);
        assert_eq!(result[1].0, 2);
        assert_eq!(render_calls.get(), 1);
    }
}