guido 0.12.0

A reactive Rust GUI library using wgpu for Wayland layer shell widgets
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
//! Child attachment forms for containers.
//!
//! Children come in four forms — two static, two reactive:
//!
//! ```no_run
//! # use guido::prelude::*;
//! # #[derive(Clone, PartialEq)] struct Item { id: u64, name: String }
//! # let entries = create_signal(Vec::<Item>::new());
//! # let items = create_signal(Vec::<Item>::new());
//! # let build_menu = |_: Vec<Item>| text("menu");
//! # let row = |item: Item| text(item.name);
//! # let (a, b, c) = (text("a"), text("b"), text("c"));
//! container()
//!     .child(text("hi"))                                  // static single
//!     .child(move || build_menu(entries.get()))           // reactive single
//!     .children([a, b, c])                                // static list
//!     .children(keyed(move || items.get(), |i| i.id, row)); // reactive keyed list
//! ```
//!
//! A reactive closure re-runs when a signal it read is written, and its
//! result **replaces** the previous widget — there is no key comparison and
//! no silent discard. Tracking is per segment: only the closure whose
//! signals changed re-runs, not every dynamic child of the container.
//!
//! State created inside a closure (signals, effects, `on_cleanup`) lives in
//! an owner scope disposed on replacement. State that must survive a rebuild
//! belongs in signals created outside the closure. To narrow *when* a
//! closure re-runs, read a [`Memo`](crate::reactive::Memo) instead of the
//! raw signal — memos notify only when their value actually changes.
//!
//! For lists, [`keyed()`] preserves per-row state through stable identity
//! and rebuilds only rows whose item content changed.

use rustc_hash::FxHashMap;
use std::cell::RefCell;
use std::hash::Hash;
use std::rc::Rc;

use crate::reactive::invalidation::suspend_widget_tracking;
use crate::reactive::{OwnerId, dispose_owner_now, with_owner};

use super::Widget;
use super::children::{ChildrenSource, DynItem, Leaving, OwnedWidget, SharedOwner};

/// Marker type for a static child (widget value)
pub struct StaticChild;

/// Marker type for a reactive child (closure)
pub struct DynamicChild;

/// Trait for values that can be added as a single child to a container.
///
/// Accepted forms:
/// - a widget value — static, evaluated once
/// - `Option<widget>` — static, and absent when `None`
/// - `move || widget` / `move || Option<widget>` — reactive: the closure
///   re-runs when a signal it reads changes, and its result replaces the
///   previous child (`None` removes it)
#[diagnostic::on_unimplemented(
    message = "`.child()` takes a widget, an `Option` of one, or a reactive closure, and `{Self}` is none of them",
    note = "reactive forms: `.child(move || widget)` or `.child(move || Option<widget>)` — the closure re-runs and replaces the child when a signal it reads changes",
    note = "for reactive lists use `.children(...)` with a closure or `keyed(data, key, build)`"
)]
pub trait IntoChild<Marker = StaticChild> {
    fn add_to_container(self, children_source: &mut ChildrenSource);
}

// Implementation for static widgets
impl<W: Widget + 'static> IntoChild<StaticChild> for W {
    fn add_to_container(self, children_source: &mut ChildrenSource) {
        children_source.add_static(Box::new(self));
    }
}

/// A child that may not be there — static, like the widget it wraps. `None` is
/// a child that was never added rather than one that can come back; the
/// reactive form of the same question is `move || Option<widget>`.
///
/// It shares `StaticChild` with the blanket above and does not overlap it:
/// `Option` is not `#[fundamental]`, so no downstream crate can write
/// `impl Widget for Option<_>`, and coherence knows `Option<W>: Widget` never
/// holds.
impl<W: Widget + 'static> IntoChild<StaticChild> for Option<W> {
    fn add_to_container(self, children_source: &mut ChildrenSource) {
        if let Some(widget) = self {
            widget.add_to_container(children_source);
        }
    }
}

/// What a reactive child closure may return: a widget (always present) or
/// `Option<widget>` (present when Some).
pub trait IntoDynChild {
    fn into_dyn_child(self) -> Option<Box<dyn Widget>>;
}

impl<W: Widget + 'static> IntoDynChild for W {
    fn into_dyn_child(self) -> Option<Box<dyn Widget>> {
        Some(Box::new(self))
    }
}

impl<W: Widget + 'static> IntoDynChild for Option<W> {
    fn into_dyn_child(self) -> Option<Box<dyn Widget>> {
        self.map(|w| Box::new(w) as Box<dyn Widget>)
    }
}

/// Reactive single child: the closure runs inside its segment's tracking
/// scope — the signals it reads are what trigger a re-run — and inside an
/// owner scope, so signals/effects created during the build are disposed
/// when the widget is replaced or removed. Every re-run replaces the child.
impl<F, C> IntoChild<DynamicChild> for F
where
    F: Fn() -> C + 'static,
    C: IntoDynChild,
{
    fn add_to_container(self, children_source: &mut ChildrenSource) {
        struct State {
            generation: u64,
            /// Widget built by the latest run, adopted by the reconciler's
            /// factory call in the same pass (the fresh generation key
            /// guarantees the factory runs).
            pending: Option<(Box<dyn Widget>, OwnerId)>,
        }

        let state = Rc::new(RefCell::new(State {
            generation: 0,
            pending: None,
        }));
        let child_fn = Rc::new(self);

        // Every run mints a new key, so nothing it returns can name a row
        // that is leaving: the new child is new.
        let items_fn = move |_: &Leaving| {
            let mut st = state.borrow_mut();

            // Defensive: a widget stashed by a previous pass that was never
            // adopted would leak its owner scope.
            if let Some((_, owner_id)) = st.pending.take() {
                dispose_owner_now(owner_id);
            }

            let child_fn = Rc::clone(&child_fn);
            let (built, owner_id) = with_owner(move || child_fn().into_dyn_child());
            match built {
                Some(widget) => {
                    st.generation += 1;
                    st.pending = Some((widget, owner_id));
                    let adopt_state = Rc::clone(&state);
                    vec![DynItem::new(st.generation, move || {
                        let (widget, owner_id) =
                            adopt_state.borrow_mut().pending.take().expect(
                                "reactive child factory ran without a freshly built widget",
                            );
                        OwnedWidget::new(widget, owner_id)
                    })]
                }
                None => {
                    dispose_owner_now(owner_id);
                    vec![]
                }
            }
        };

        children_source.add_dynamic(items_fn);
    }
}

/// Marker type for static children (iterator of widgets)
pub struct StaticChildren;

/// Marker type for reactive children (closure or [`keyed()`])
pub struct DynamicChildren;

/// Marker type for children forwarded from a [`ChildrenSource`] a component
/// was handed
pub struct ForwardedChildren;

/// Trait for values that can be added as children to a container.
///
/// Accepted forms:
/// - an iterator of widgets — static, evaluated once
/// - `move || iterator_of_widgets` — reactive: re-runs when a signal it
///   reads changes, replacing all rows
/// - [`keyed(data, key, build)`](keyed) — reactive with stable identity:
///   preserves per-row state, rebuilds only changed rows
/// - a [`ChildrenSource`] — the children a component was handed by its
///   caller, taking their place where the call is written
#[diagnostic::on_unimplemented(
    message = "`.children()` takes an iterator of widgets, a reactive closure returning one, `keyed(data, key, build)`, or the `ChildrenSource` a component was handed — and `{Self}` is none of those",
    note = "`.children(move || widgets)` replaces all rows when a signal it reads changes; `keyed(data, key, build)` preserves per-row state via stable identity and rebuilds only rows whose item changed"
)]
pub trait IntoChildren<Marker = StaticChildren> {
    fn add_to_container(self, children_source: &mut ChildrenSource);
}

// Implementation for static children - IntoIterator<Item = W> where W: Widget
// Each widget in the iterator becomes a separate static slot
impl<I, W> IntoChildren<StaticChildren> for I
where
    I: IntoIterator<Item = W>,
    W: Widget + 'static,
{
    fn add_to_container(self, children_source: &mut ChildrenSource) {
        for widget in self {
            children_source.add_static(Box::new(widget));
        }
    }
}

/// The children a component was handed, put where the component wants them.
///
/// `#[prop(children)]` gives the component a `ChildrenSource` the caller
/// filled in, and this is how it goes back into a tree — as one item in a
/// sequence, so a title above it and a footer below it stay where they were
/// written.
impl IntoChildren<ForwardedChildren> for ChildrenSource {
    fn add_to_container(self, children_source: &mut ChildrenSource) {
        children_source.append(self);
    }
}

/// Reactive unkeyed list: the closure re-runs when a signal it reads
/// changes and its rows replace the previous ones wholesale. All rows of
/// one run share a single owner scope, disposed when the last row drops.
///
/// Rows have no identity across runs — inner state does not survive a
/// re-run. Use [`keyed()`] when rows carry state worth preserving.
impl<F, I, W> IntoChildren<DynamicChildren> for F
where
    F: Fn() -> I + 'static,
    I: IntoIterator<Item = W>,
    W: Widget + 'static,
{
    fn add_to_container(self, children_source: &mut ChildrenSource) {
        struct State {
            next_generation: u64,
            /// Rows built by the latest run, adopted by the reconciler's
            /// factory calls in the same pass.
            pending: FxHashMap<u64, Box<dyn Widget>>,
        }

        let state = Rc::new(RefCell::new(State {
            next_generation: 0,
            pending: FxHashMap::default(),
        }));
        let list_fn = Rc::new(self);

        // Keys are minted per run, as the single child's are.
        let items_fn = move |_: &Leaving| {
            let mut st = state.borrow_mut();
            // Defensive: unadopted rows from a previous pass (their shared
            // owner guard was dropped with the unadopted factories).
            st.pending.clear();

            let list_fn = Rc::clone(&list_fn);
            let (widgets, owner_id) = with_owner(move || {
                list_fn()
                    .into_iter()
                    .map(|w| Box::new(w) as Box<dyn Widget>)
                    .collect::<Vec<_>>()
            });
            if widgets.is_empty() {
                dispose_owner_now(owner_id);
                return vec![];
            }

            let shared = SharedOwner::new(owner_id);
            let mut out = Vec::with_capacity(widgets.len());
            for widget in widgets {
                let generation = st.next_generation;
                st.next_generation += 1;
                st.pending.insert(generation, widget);

                let adopt_state = Rc::clone(&state);
                let shared = shared.clone();
                out.push(DynItem::new(generation, move || {
                    let widget = adopt_state
                        .borrow_mut()
                        .pending
                        .remove(&generation)
                        .expect("reactive children factory ran without a freshly built row");
                    OwnedWidget::new_shared(widget, shared)
                }));
            }
            out
        };

        children_source.add_dynamic(items_fn);
    }
}

/// A reactive keyed children list: tracked data, key-based identity,
/// untracked per-item builder. Built with [`keyed()`], consumed by
/// `.children()`.
pub struct KeyedChildren<T, I, K, W> {
    data: Box<dyn Fn() -> I>,
    key: Box<dyn Fn(&T) -> K>,
    build: Box<dyn Fn(T) -> W>,
}

/// Reactive keyed children list: tracked data, key-based identity,
/// untracked per-item builder with content diffing.
///
/// `data` runs inside the segment's tracking scope and yields the items.
/// `key` extracts each item's stable identity (it survives reorders). Per
/// item:
///
/// - new key → `build` runs (untracked, in an owner scope)
/// - known key, item `==` previous → the existing widget is kept untouched
///   (inner state and animations persist, including across reorders)
/// - known key, item changed → `build` re-runs and the rebuilt widget
///   replaces the old one (its owner scope is disposed)
/// - key gone → widget dropped with owner cleanup
///
/// The item type chooses the granularity: fields excluded from it can be
/// read via signals inside the row for in-place updates, fields included
/// trigger a row rebuild when they change.
///
/// The key is any `Hash + Eq + Clone`, so an identity that is already a string
/// or a tuple can be used as it is rather than hashed by hand at the call site.
/// Rows are indexed by the key itself, not by a hash of it, so two distinct keys
/// are never reconciled as one:
///
/// ```no_run
/// # use guido::prelude::*;
/// # #[derive(Clone, PartialEq)] struct Space { id: u64 }
/// # let workspaces = create_signal(Vec::<Space>::new());
/// # let workspace_pill = |_: Space| text("ws");
/// container().children(keyed(
///     move || workspaces.get(),
///     |ws| ws.id,
///     workspace_pill,
/// ));
///
/// # #[derive(Clone, PartialEq)] struct Tab { title: String }
/// # let tabs = create_signal(Vec::<Tab>::new());
/// # let tab_button = |_: Tab| text("tab");
/// container().children(keyed(
///     move || tabs.get(),
///     |tab| tab.title.clone(),
///     tab_button,
/// ));
/// ```
pub fn keyed<T, I, K, W>(
    data: impl Fn() -> I + 'static,
    key: impl Fn(&T) -> K + 'static,
    build: impl Fn(T) -> W + 'static,
) -> KeyedChildren<T, I, K, W>
where
    T: Clone + PartialEq + 'static,
    I: IntoIterator<Item = T>,
    K: Hash + Eq + Clone + 'static,
    W: Widget + 'static,
{
    KeyedChildren {
        data: Box::new(data),
        key: Box::new(key),
        build: Box::new(build),
    }
}

impl<T, I, K, W> IntoChildren<DynamicChildren> for KeyedChildren<T, I, K, W>
where
    T: Clone + PartialEq + 'static,
    I: IntoIterator<Item = T> + 'static,
    K: Hash + Eq + Clone + 'static,
    W: Widget + 'static,
{
    fn add_to_container(self, children_source: &mut ChildrenSource) {
        add_keyed_children(children_source, self.data, self.key, self.build);
    }
}

/// Wire a (tracked data, key, untracked builder) triple into a
/// ChildrenSource as a keyed dynamic list. See [`keyed()`] for the
/// semantics.
fn add_keyed_children<T, I, K, W>(
    source: &mut ChildrenSource,
    data_fn: impl Fn() -> I + 'static,
    key_fn: impl Fn(&T) -> K + 'static,
    build_fn: impl Fn(T) -> W + 'static,
) where
    T: Clone + PartialEq + 'static,
    I: IntoIterator<Item = T>,
    K: Hash + Eq + Clone + 'static,
    W: Widget + 'static,
{
    struct Row<T> {
        item: T,
        /// Serves as the reconciliation key: globally unique per (identity,
        /// content version), stable while the item compares equal.
        generation: u64,
    }
    /// Rows are indexed by the key itself, not by a hash of it. Reducing the
    /// key to a u64 first would make two colliding keys the same row — one
    /// widget serving two items and the other silently dropped — and no
    /// non-cryptographic hash can rule that out for keys like strings and
    /// tuples, which is exactly what this signature invites.
    struct KeyedState<T, K> {
        rows: FxHashMap<K, Row<T>>,
        /// Rows dropped from the data whose widget may still be playing its
        /// exit. A key that comes back with an equal item takes its generation
        /// back from here, and the reconciler hands it the leaving row rather
        /// than building one; a row the reconciler no longer holds is
        /// forgotten on the next run.
        departed: FxHashMap<K, Row<T>>,
        next_generation: u64,
        /// Widgets built eagerly this pass, awaiting adoption by the
        /// reconciler's factory calls (keyed by generation).
        pending: FxHashMap<u64, (Box<dyn Widget>, OwnerId)>,
    }

    // Fx rather than the std hasher: this runs once per row per pass, on every
    // frame a list changes, and widening the key from u64 to any Hash made a
    // string key ordinary. These are the app's own identities, not adversarial
    // input, which is the condition SipHash is there for.
    let state = Rc::new(RefCell::new(KeyedState::<T, K> {
        rows: FxHashMap::default(),
        departed: FxHashMap::default(),
        next_generation: 0,
        pending: FxHashMap::default(),
    }));

    let items_fn = move |leaving: &Leaving| {
        let items = data_fn(); // tracked: runs inside the segment scope
        let mut st = state.borrow_mut();
        let st = &mut *st;
        st.departed
            .retain(|_, row| leaving.contains(row.generation));

        // Defensive: widgets stashed by a previous pass that were never
        // adopted would leak their owner scopes.
        for (_, (_, owner_id)) in st.pending.drain() {
            dispose_owner_now(owner_id);
        }

        // Keyed by first sighting rather than a plain set: a duplicate is worth
        // reporting *with the row it collided with*, and that is the one thing a
        // set cannot say.
        let mut seen = FxHashMap::default();
        let mut out = Vec::new();
        for (index, item) in items.into_iter().enumerate() {
            let key = key_fn(&item);
            // Looked up now and recorded at the end of the row, rather than
            // through `entry`: `entry` takes the key by value, so it would clone
            // every key on every pass — a heap allocation per row for the string
            // keys this signature invites, on a list that has settled and is
            // building nothing. This way only a row that is actually created
            // clones, and a second hash of a key already in cache is the cheaper
            // half of that trade.
            //
            // The first sighting, not the previous one: reporting against the
            // previous would, with duplicates at 0, 2 and 5, send the reader to
            // item 2 — which was itself skipped and is not in the list.
            if let Some(first) = seen.get(&key) {
                // Without the key's value: `Debug` would be a bound the mechanism
                // does not need, and it would keep an opaque newtype out of
                // `keyed` in order to format a log line. Both indices instead —
                // the type alone names nothing, but the pair of rows that
                // collided is enough to go and look at them.
                log::warn!(
                    "keyed children: item {index} repeats the {} key of item {first}, skipping it",
                    std::any::type_name::<K>(),
                );
                continue;
            }

            let generation = match st.rows.get(&key) {
                Some(row) if row.item == item => row.generation,
                // Back mid-exit, unchanged: the same generation, so the same
                // row.
                None if st.departed.get(&key).is_some_and(|row| row.item == item) => {
                    let row = st.departed.remove(&key).expect("just looked up");
                    let generation = row.generation;
                    st.rows.insert(key.clone(), row);
                    generation
                }
                _ => {
                    let generation = st.next_generation;
                    st.next_generation += 1;
                    let (widget, owner_id) = with_owner(|| {
                        suspend_widget_tracking(|| {
                            Box::new(build_fn(item.clone())) as Box<dyn Widget>
                        })
                    });
                    st.pending.insert(generation, (widget, owner_id));
                    st.rows.insert(key.clone(), Row { item, generation });
                    generation
                }
            };

            // Recorded once the row is dealt with, moving the key rather than
            // cloning it — nothing below needs it again.
            seen.insert(key, index);

            let adopt_state = Rc::clone(&state);
            out.push(DynItem::new(generation, move || {
                let (widget, owner_id) = adopt_state
                    .borrow_mut()
                    .pending
                    .remove(&generation)
                    .expect("keyed children factory ran without a freshly built widget");
                OwnedWidget::new(widget, owner_id)
            }));
        }
        // Kept rather than dropped, in case the reconciler lets them play an
        // exit — the next run forgets any it did not.
        st.departed
            .extend(st.rows.extract_if(|key, _| !seen.contains_key(key)));
        out
    };

    source.add_dynamic(items_fn);
}

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

    use super::*;
    use crate::layout::{Constraints, Size};
    use crate::reactive::{create_signal, on_cleanup};
    use crate::tree::LayoutCtx;
    use crate::tree::{Tree, WidgetId};
    use crate::widgets::{Container, container};

    struct TestWidget;
    impl Widget for TestWidget {
        fn layout(&mut self, _: &mut LayoutCtx, _: Constraints) -> Size {
            Size::zero()
        }
        fn paint(&self, _: &mut crate::renderer::PaintContext) {}
    }

    /// A parented ChildrenSource ready for reconciliation.
    fn children_host() -> (Tree, ChildrenSource) {
        let mut tree = Tree::new();
        let parent = tree.register(Box::new(TestWidget));
        let mut source = ChildrenSource::default();
        source.set_container_id(parent);
        (tree, source)
    }

    /// An `Option` is a child, so `child` is the only way in.
    ///
    /// Counted off the tree rather than off the `ChildrenSource`, because a
    /// static child is registered when the container registers its children
    /// and not before — the source holds it pending until then.
    #[test]
    fn an_optional_child_is_a_child() {
        fn registered(container: Container) -> usize {
            let mut tree = Tree::new();
            let id = tree.register(Box::new(container));
            tree.with_widget_mut(id, |w, id, t| w.register_children(t, id));
            tree.get_children(id).len()
        }

        assert_eq!(
            registered(container().child(Some(TestWidget))),
            1,
            "`Some(w)` is the widget"
        );
        assert_eq!(
            registered(container().child(None::<TestWidget>)),
            0,
            "`None` is no child at all"
        );
    }

    /// Two keys that a 64-bit hash cannot tell apart must still be two rows.
    /// While the reconciler indexed by `FxHash` of the key this collapsed them:
    /// one widget served both items and the other was silently dropped.
    #[test]
    fn colliding_keys_are_still_distinct_rows() {
        /// A key whose hash is deliberately useless, standing in for the
        /// collision a real hash makes merely unlikely.
        // Deliberately not Debug: the key bound must not require it.
        #[derive(Clone, PartialEq, Eq)]
        struct Collides(&'static str);

        impl std::hash::Hash for Collides {
            fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
                0u8.hash(state);
            }
        }

        let (mut tree, mut source) = children_host();
        let items = create_signal(vec![Collides("a"), Collides("b")]);

        IntoChildren::<DynamicChildren>::add_to_container(
            keyed(
                move || items.get(),
                |c: &Collides| c.clone(),
                |_| TestWidget,
            ),
            &mut source,
        );

        let ids = source.reconcile_and_get(&mut tree).clone();
        assert_eq!(ids.len(), 2, "two keys, two widgets");

        // And the identity survives a reorder: same widgets, swapped.
        items.set(vec![Collides("b"), Collides("a")]);
        source.reconcile_with_tracking(&mut tree);
        let reordered = source.reconcile_and_get(&mut tree).clone();
        assert_eq!(reordered, vec![ids[1], ids[0]]);
    }

    #[test]
    fn closure_child_replaces_on_tracked_change() {
        let (mut tree, mut source) = children_host();
        let sig = create_signal(1u64);
        let unrelated = create_signal(0u64);
        let builds = Rc::new(Cell::new(0usize));

        let builds_counter = builds.clone();
        let closure = move || {
            sig.get();
            builds_counter.set(builds_counter.get() + 1);
            TestWidget
        };
        IntoChild::<DynamicChild>::add_to_container(closure, &mut source);

        let first = source.reconcile_and_get(&mut tree).clone();
        assert_eq!(first.len(), 1);
        assert_eq!(builds.get(), 1);

        // Untracked signal change: segment not dirty, widget untouched
        unrelated.set(1);
        source.reconcile_with_tracking(&mut tree);
        assert_eq!(source.reconcile_and_get(&mut tree).clone(), first);
        assert_eq!(builds.get(), 1);

        // Tracked signal change: closure re-runs, widget replaced
        sig.set(2);
        source.reconcile_with_tracking(&mut tree);
        let second = source.reconcile_and_get(&mut tree).clone();
        assert_eq!(second.len(), 1);
        assert_ne!(second[0], first[0]);
        assert_eq!(builds.get(), 2);

        // No-op write (same value): signals skip notification entirely
        sig.set(2);
        source.reconcile_with_tracking(&mut tree);
        assert_eq!(source.reconcile_and_get(&mut tree).clone(), second);
        assert_eq!(builds.get(), 2);
    }

    /// A replaced dynamic child's WHOLE subtree must leave the tree during
    /// the reconcile itself. If descendants lingered for deferred cleanup,
    /// their queued reconciles could still run in the same batch and read
    /// state owned (and just disposed) by the replaced root.
    #[test]
    fn replaced_child_subtree_is_torn_down_synchronously() {
        struct ParentWidget;
        impl Widget for ParentWidget {
            fn layout(&mut self, _: &mut LayoutCtx, _: Constraints) -> Size {
                Size::zero()
            }
            fn paint(&self, _: &mut crate::renderer::PaintContext) {}
            fn register_children(&mut self, tree: &mut Tree, id: WidgetId) {
                let child = tree.register(Box::new(TestWidget));
                tree.set_parent(child, id);
            }
        }

        let (mut tree, mut source) = children_host();
        let sig = create_signal(0u64);

        let closure = move || {
            sig.get();
            ParentWidget
        };
        IntoChild::<DynamicChild>::add_to_container(closure, &mut source);
        source.reconcile_and_get(&mut tree);

        // host + row root + row's registered child
        let count_after_build = tree.widget_count();
        assert_eq!(count_after_build, 3);

        // Tracked change: the row is replaced by a fresh build
        sig.set(1);
        source.reconcile_with_tracking(&mut tree);

        // Same shape, and the OLD subtree is fully gone already — no
        // deferred leftovers
        assert_eq!(tree.widget_count(), count_after_build);
    }

    #[test]
    fn segments_rerun_independently() {
        let (mut tree, mut source) = children_host();
        let sig_a = create_signal(0u64);
        let sig_b = create_signal(0u64);

        let closure_a = move || {
            sig_a.get();
            TestWidget
        };
        let closure_b = move || {
            sig_b.get();
            TestWidget
        };
        IntoChild::<DynamicChild>::add_to_container(closure_a, &mut source);
        IntoChild::<DynamicChild>::add_to_container(closure_b, &mut source);

        let first = source.reconcile_and_get(&mut tree).clone();
        assert_eq!(first.len(), 2);

        // Only segment A's signal changes: B's widget must survive
        sig_a.set(1);
        source.reconcile_with_tracking(&mut tree);
        let second = source.reconcile_and_get(&mut tree).clone();
        assert_ne!(second[0], first[0]);
        assert_eq!(second[1], first[1]);
    }

    #[test]
    fn closure_child_controls_presence() {
        let (mut tree, mut source) = children_host();
        let show = create_signal(false);

        let closure = move || show.get().then_some(TestWidget);
        IntoChild::<DynamicChild>::add_to_container(closure, &mut source);

        assert!(source.reconcile_and_get(&mut tree).is_empty());

        show.set(true);
        source.reconcile_with_tracking(&mut tree);
        assert_eq!(source.reconcile_and_get(&mut tree).len(), 1);

        show.set(false);
        source.reconcile_with_tracking(&mut tree);
        assert!(source.reconcile_and_get(&mut tree).is_empty());
    }

    #[test]
    fn closure_children_replace_all_rows_and_dispose_batch_owner() {
        let (mut tree, mut source) = children_host();
        let count = create_signal(2u64);
        let cleanups = Rc::new(Cell::new(0usize));

        let cleanups_counter = cleanups.clone();
        let closure = move || {
            let cleanups_counter = cleanups_counter.clone();
            on_cleanup(move || cleanups_counter.set(cleanups_counter.get() + 1));
            (0..count.get()).map(|_| TestWidget).collect::<Vec<_>>()
        };
        IntoChildren::<DynamicChildren>::add_to_container(closure, &mut source);

        let first = source.reconcile_and_get(&mut tree).clone();
        assert_eq!(first.len(), 2);
        assert_eq!(cleanups.get(), 0);

        count.set(3);
        source.reconcile_with_tracking(&mut tree);
        let second = source.reconcile_and_get(&mut tree).clone();
        assert_eq!(second.len(), 3);
        // All rows replaced, previous batch owner disposed exactly once
        assert!(first.iter().all(|id| !second.contains(id)));
        assert_eq!(cleanups.get(), 1);
    }

    #[test]
    fn keyed_children_diff_by_identity_and_content() {
        let (mut tree, mut source) = children_host();
        let items = create_signal(vec![(1u64, "a".to_string()), (2, "b".to_string())]);
        let builds = Rc::new(Cell::new(0usize));

        let builds_counter = builds.clone();
        keyed(
            move || items.get(),
            |(id, _)| *id,
            move |_| {
                builds_counter.set(builds_counter.get() + 1);
                TestWidget
            },
        )
        .add_to_container(&mut source);

        let first = source.reconcile_and_get(&mut tree).clone();
        assert_eq!(first.len(), 2);
        assert_eq!(builds.get(), 2);

        // Reorder with equal content: widgets reused, order follows data
        items.set(vec![(2, "b".to_string()), (1, "a".to_string())]);
        source.reconcile_with_tracking(&mut tree);
        let reordered = source.reconcile_and_get(&mut tree).clone();
        assert_eq!(reordered, vec![first[1], first[0]]);
        assert_eq!(builds.get(), 2);

        // Content change on one item: only that row rebuilds
        items.set(vec![(2, "B!".to_string()), (1, "a".to_string())]);
        source.reconcile_with_tracking(&mut tree);
        let changed = source.reconcile_and_get(&mut tree).clone();
        assert_eq!(changed.len(), 2);
        assert_ne!(changed[0], reordered[0]); // row 2 rebuilt
        assert_eq!(changed[1], reordered[1]); // row 1 untouched
        assert_eq!(builds.get(), 3);

        // Removal drops only the removed row
        items.set(vec![(1, "a".to_string())]);
        source.reconcile_with_tracking(&mut tree);
        let removed = source.reconcile_and_get(&mut tree).clone();
        assert_eq!(removed, vec![changed[1]]);
        assert_eq!(builds.get(), 3);
    }

    #[test]
    fn keyed_children_skip_duplicate_keys() {
        let (mut tree, mut source) = children_host();

        // Three of them, so the report has a choice to get wrong: the second and
        // the third are both told about the *first*, which is the row still on
        // screen — not about each other, one of which was itself skipped.
        keyed(
            move || vec![(7u64, "x"), (1, "a"), (7, "y"), (7, "z")],
            |(id, _)| *id,
            |_| TestWidget,
        )
        .add_to_container(&mut source);

        // Only the first item with a given key is rendered
        assert_eq!(source.reconcile_and_get(&mut tree).len(), 2);
    }
}