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
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
use std::rc::Rc;

use rustc_hash::FxHashMap;

use crate::jobs::{JobRequest, request_job};
use crate::layout::{Constraints, Size};
use crate::reactive::{OwnerId, dispose_owner_now, under_owner};
use crate::renderer::PaintContext;
use crate::tree::{LayoutCtx, Tree, WidgetId};

use super::Widget;
use super::widget::{Event, EventResponse, LayoutHints};

/// What a dynamic segment runs to learn its rows — told which of its keys
/// are still leaving.
type ItemsFn = dyn Fn(&Leaving) -> Vec<DynItem>;

/// Segment metadata - tracks what kind of source each segment is
enum SegmentType {
    /// Static widgets - just a count (widget IDs stored in merged)
    Static(usize),
    /// Dynamic source with keyed reconciliation
    Dynamic {
        items_fn: Rc<ItemsFn>,
        /// Widget IDs by key while one reconciliation matches them against
        /// what was asked for. Empty between passes.
        cached: FxHashMap<u64, WidgetId>,
        /// Current keys in display order — a leaving row's among them, in the
        /// place it held, so this and the segment's run of `merged` line up.
        current_keys: Vec<u64>,
        /// The rows that were removed and are playing their exit, by key.
        /// Findable here until they are disposed, which is what lets a key
        /// that comes back mid-exit reclaim its row instead of building one.
        leaving: FxHashMap<u64, WidgetId>,
        /// Whether items_fn has run at least once. After the first run the
        /// segment only re-runs when a signal it tracks is written
        /// (per-segment dirty marking in the invalidation registry).
        has_run: bool,
    },
}

/// Represents the source of children for a container
///
/// Uses a segment-based architecture:
/// - Static segments: widgets added directly, stored in `pending_static` during construction
/// - Dynamic segments: widgets from reactive closures with keyed reconciliation
///
/// During construction, static widgets are stored in `pending_static`. When the widget
/// tree is registered with an tree (via `register_pending`), widgets are moved to the
/// tree and their IDs are stored in `merged`.
#[derive(Default)]
pub struct ChildrenSource {
    /// All widget IDs in order (static and dynamic interleaved) - populated after registration
    merged: Vec<WidgetId>,
    /// Pending static widgets not yet registered with the tree
    pending_static: Vec<Box<dyn Widget>>,
    /// Segment metadata (boundaries and reconciliation info)
    segments: Vec<SegmentType>,
    /// Parent container ID for subscriber registration
    container_id: Option<WidgetId>,
    /// Whether initial reconciliation has been done
    initial_reconcile_done: bool,
}

impl ChildrenSource {
    /// Set the container ID for subscriber registration
    pub fn set_container_id(&mut self, id: WidgetId) {
        self.container_id = Some(id);
    }

    /// Add a static child widget
    ///
    /// The widget is stored in `pending_static` until `register_pending` is called
    /// with an tree reference.
    pub fn add_static(&mut self, widget: Box<dyn Widget>) {
        self.pending_static.push(widget);

        // Track in segment metadata
        if let Some(SegmentType::Static(count)) = self.segments.last_mut() {
            *count += 1;
        } else {
            self.segments.push(SegmentType::Static(1));
        }
    }

    /// Take everything `other` holds, in order, after what this source has.
    ///
    /// Both halves are build-time state — `pending_static` is drained at
    /// registration and `segments` is written while the tree is being built —
    /// so appending the two is the whole of it. Static widgets stay in
    /// insertion order because the reconciler walks segments and takes that
    /// many from the merged list in the order they were pushed.
    ///
    /// What it is for: a component forwarding the children it was handed, via
    /// [`IntoChildren`](super::IntoChildren) for `ChildrenSource`.
    pub(crate) fn append(&mut self, mut other: ChildrenSource) {
        debug_assert!(
            other.merged.is_empty() && !other.initial_reconcile_done,
            "a source is forwarded while the tree is being built, before \
             anything in it has reached a widget id"
        );

        // Moved out field by field, so the husk that drops at the end of this
        // call holds nothing: `ChildrenSource` drops by asking the loop to
        // unregister every widget it still has.
        let mut statics = std::mem::take(&mut other.pending_static).into_iter();
        for segment in std::mem::take(&mut other.segments) {
            match segment {
                // Back through `add_static`, so a static run arriving at the
                // seam is opened or extended by the same rule as one written
                // here directly.
                SegmentType::Static(count) => {
                    for widget in statics.by_ref().take(count) {
                        self.add_static(widget);
                    }
                }
                dynamic => self.segments.push(dynamic),
            }
        }
    }

    /// Register all pending static widgets with the tree.
    ///
    /// This should be called before layout. It recursively registers the widget tree.
    pub fn register_pending(&mut self, tree: &mut Tree, parent_id: WidgetId) {
        for widget in self.pending_static.drain(..) {
            // Register this widget - tree assigns the ID
            let widget_id = tree.register(widget);
            tree.set_parent(widget_id, parent_id);
            self.merged.push(widget_id);

            // Recursively register children with the newly assigned widget ID
            tree.with_widget_mut(widget_id, |widget, id, tree| {
                widget.register_children(tree, id);
            });
        }
    }

    /// Add a dynamic children source.
    ///
    /// `items_fn` is told which of the keys it returned before are still
    /// leaving, so a source whose keys mean something across runs — `keyed`,
    /// and not the closure forms, which mint a key every run — can hand one of
    /// them back and have its row returned rather than rebuilt.
    pub fn add_dynamic(&mut self, items_fn: impl Fn(&Leaving) -> Vec<DynItem> + 'static) {
        self.segments.push(SegmentType::Dynamic {
            items_fn: Rc::new(items_fn),
            cached: FxHashMap::default(),
            current_keys: Vec::new(),
            leaving: FxHashMap::default(),
            has_run: false,
        });
    }

    /// Check if any dynamic segments exist
    pub fn has_dynamic(&self) -> bool {
        self.segments
            .iter()
            .any(|s| matches!(s, SegmentType::Dynamic { .. }))
    }

    /// Reconcile dynamic segments and rebuild the merged list.
    ///
    /// Each dynamic segment re-runs its items_fn only when a signal it read
    /// was written (per-segment dirty marking) or on its first run. Reads
    /// during the run are tracked to this (container, segment) pair.
    ///
    /// A segment holding a leaving row whose exit has settled is rebuilt too,
    /// whether or not it re-ran: that is where the row is disposed.
    fn reconcile(&mut self, tree: &mut Tree, parent_id: WidgetId) {
        let dirty = crate::reactive::invalidation::take_dirty_segments(parent_id);

        // First pass: re-run dirty segments and collect those whose rows
        // change — new keys, or a leaving row to dispose (`None`).
        let mut segments_with_changes: Vec<(usize, Option<Vec<DynItem>>)> = Vec::new();

        for (idx, segment) in self.segments.iter_mut().enumerate() {
            if let SegmentType::Dynamic {
                items_fn,
                current_keys,
                leaving,
                has_run,
                ..
            } = segment
            {
                let needs_run = !*has_run
                    || dirty.as_ref().is_some_and(|d| {
                        d.contains(&(idx as u32))
                            || d.contains(&crate::reactive::invalidation::EVERY_SEGMENT)
                    });
                let settled = leaving.values().any(|&id| !is_exiting(tree, id));
                if needs_run {
                    let items_fn = Rc::clone(items_fn);
                    let new_items = crate::reactive::invalidation::with_segment_tracking(
                        parent_id,
                        idx as u32,
                        || items_fn(&Leaving(leaving)),
                    );
                    *has_run = true;

                    let new_keys = new_items.iter().map(|i| i.key);
                    let unchanged = if leaving.is_empty() {
                        new_keys.eq(current_keys.iter().copied())
                    } else {
                        let live = current_keys.iter().filter(|k| !leaving.contains_key(k));
                        new_keys.eq(live.copied())
                    };
                    if !unchanged {
                        segments_with_changes.push((idx, Some(new_items)));
                        continue;
                    }
                }
                if settled {
                    segments_with_changes.push((idx, None));
                }
            }
        }

        // If nothing changed, skip the entire rebuild
        if segments_with_changes.is_empty() {
            return;
        }

        // Take ownership of old merged vec to avoid borrow conflicts
        let old_merged = std::mem::take(&mut self.merged);
        let mut old_merged_iter = old_merged.into_iter();

        // Build new merged vec by walking through segments
        let mut new_merged = Vec::with_capacity(old_merged_iter.len());
        let mut change_idx = 0;

        for (idx, segment) in self.segments.iter_mut().enumerate() {
            match segment {
                SegmentType::Static(count) => {
                    // Static widgets: take IDs from old merged
                    for _ in 0..*count {
                        if let Some(widget_id) = old_merged_iter.next() {
                            new_merged.push(widget_id);
                        }
                    }
                }
                SegmentType::Dynamic {
                    cached,
                    current_keys,
                    leaving,
                    ..
                } => {
                    // Check if this segment has changes
                    let has_changes = change_idx < segments_with_changes.len()
                        && segments_with_changes[change_idx].0 == idx;

                    if has_changes {
                        let (_, new_items) = std::mem::take(&mut segments_with_changes[change_idx]);
                        change_idx += 1;

                        let old: Vec<(u64, WidgetId)> = current_keys
                            .drain(..)
                            .filter_map(|key| old_merged_iter.next().map(|id| (key, id)))
                            .collect();
                        let mut rows = Rows {
                            tree: &mut *tree,
                            parent_id,
                            cached,
                            keys: current_keys,
                            leaving,
                            merged: &mut new_merged,
                        };
                        match new_items {
                            Some(new_items) => rows.replace(old, new_items),
                            None => rows.dispose_settled(old),
                        }
                    } else {
                        // Keys unchanged - just move widget IDs from old merged to new merged
                        for _ in 0..current_keys.len() {
                            if let Some(widget_id) = old_merged_iter.next() {
                                new_merged.push(widget_id);
                            }
                        }
                    }
                }
            }
        }

        self.merged = new_merged;
    }

    /// Reconcile with signal tracking. Called from main loop job processing.
    /// Returns true if children changed.
    pub fn reconcile_with_tracking(&mut self, tree: &mut Tree) -> bool {
        if !self.has_dynamic() {
            return false;
        }

        let container_id = self
            .container_id
            .expect("container_id must be set before reconcile_with_tracking");

        let prev_count = self.merged.len();

        // Signal reads are tracked per segment inside reconcile()
        self.reconcile(tree, container_id);
        self.initial_reconcile_done = true;

        prev_count != self.merged.len()
    }

    /// Reconcile and get widget IDs (for layout)
    /// Does lazy initial reconciliation with tracking if needed.
    pub fn reconcile_and_get(&mut self, tree: &mut Tree) -> &Vec<WidgetId> {
        // Lazy initial reconciliation (for first frame before any jobs exist)
        if self.has_dynamic() && !self.initial_reconcile_done {
            if let Some(container_id) = self.container_id {
                // Signal reads are tracked per segment inside reconcile()
                self.reconcile(tree, container_id);
                self.initial_reconcile_done = true;
            } else {
                // Fallback: reconcile without tracking (shouldn't happen in practice)
                // This case shouldn't occur as container_id should always be set
            }
        }
        // Subsequent reconciliations (triggered by jobs) already done by process_pending_jobs
        // Just return the already-reconciled list
        &self.merged
    }

    /// Get widget IDs (for paint and events)
    /// After first frame, this just returns the already-reconciled children.
    pub fn get(&self) -> &Vec<WidgetId> {
        &self.merged
    }

    /// Get mutable reference to widget IDs
    pub fn get_mut(&mut self) -> &mut Vec<WidgetId> {
        &mut self.merged
    }

    /// Check if empty
    pub fn is_empty(&self) -> bool {
        self.merged.is_empty()
    }

    /// Get the number of children
    pub fn len(&self) -> usize {
        self.merged.len()
    }
}

/// The keys of a dynamic segment's rows that are leaving — removed, and still
/// playing their exit.
///
/// Handed to the segment's items function on every run. A key it returns that
/// is in here gets its leaving row back, exit cancelled, instead of a new one
/// built; a source that cannot promise its keys mean the same row across runs
/// ignores it.
pub struct Leaving<'a>(&'a FxHashMap<u64, WidgetId>);

impl Leaving<'_> {
    /// Whether the row this key named is still leaving.
    pub fn contains(&self, key: u64) -> bool {
        self.0.contains_key(&key)
    }
}

/// Whether the widget at `id` is still playing its exit.
fn is_exiting(tree: &Tree, id: WidgetId) -> bool {
    tree.with_widget(id, |widget| widget.is_exiting())
        .unwrap_or(false)
}

/// One dynamic segment's rows, while a reconciliation rewrites them.
struct Rows<'a> {
    tree: &'a mut Tree,
    parent_id: WidgetId,
    cached: &'a mut FxHashMap<u64, WidgetId>,
    keys: &'a mut Vec<u64>,
    leaving: &'a mut FxHashMap<u64, WidgetId>,
    merged: &'a mut Vec<WidgetId>,
}

impl Rows<'_> {
    /// The segment's rows become `new_items`, in their order: a key it had is
    /// reused (a leaving one reclaimed), a key it did not have is built, and a
    /// row nothing asked for again leaves — after the nearest row that stood
    /// before it, if it declared an exit, and in this pass if it did not.
    fn replace(&mut self, old: Vec<(u64, WidgetId)>, new_items: Vec<DynItem>) {
        let start = self.merged.len();
        for &(key, id) in &old {
            self.cached.insert(key, id);
        }

        for item in new_items {
            let widget_id = match self.cached.remove(&item.key) {
                Some(widget_id) => {
                    // Reuse existing widget (preserves state!) — and a leaving
                    // one comes back from wherever its exit had taken it.
                    if self.leaving.remove(&item.key).is_some() {
                        self.tree.with_widget_mut(widget_id, |widget, id, tree| {
                            widget.cancel_exit(tree, id)
                        });
                        crate::jobs::reattach_widget_subtree(self.tree, widget_id);
                    }
                    widget_id
                }
                None => {
                    // Create new widget and register in tree
                    let widget = (item.widget_fn)();
                    let widget_id = self.tree.register(widget);
                    self.tree.set_parent(widget_id, self.parent_id);
                    // Recursively register children with the newly assigned widget ID
                    self.tree.with_widget_mut(widget_id, |widget, id, tree| {
                        widget.register_children(tree, id);
                    });
                    widget_id
                }
            };
            self.keys.push(item.key);
            self.merged.push(widget_id);
        }

        // What was not asked for again, in the order it stood. A row that
        // stays to play its exit goes back after the nearest row that stood
        // before it and is still here, wherever this change moved that one —
        // `None` is the front — so its siblings move when it is gone rather
        // than when it starts to go.
        let mut after: FxHashMap<Option<u64>, Vec<(u64, WidgetId)>> = FxHashMap::default();
        let mut before = None;
        for (key, id) in old {
            if self.cached.remove(&key).is_none() {
                before = Some(key);
                continue;
            }
            let was_leaving = self.leaving.contains_key(&key);
            let stays = if was_leaving {
                is_exiting(self.tree, id)
            } else {
                self.begin_leaving(id)
            };
            if stays {
                self.leaving.insert(key, id);
                after.entry(before).or_default().push((key, id));
            } else if was_leaving {
                self.leaving.remove(&key);
                crate::jobs::teardown_widget_subtree(self.tree, id);
            } else {
                // No exit: the WHOLE subtree comes out of the tree
                // synchronously (subscribers + dirty segments cleared, children
                // first). The root's exclusive owner is disposed by its Drop
                // right here, so any state it owned (memos captured by
                // descendant closures) dies with it — a descendant left behind
                // for deferred cleanup could still reconcile this batch and
                // read that disposed state.
                crate::jobs::teardown_widget_subtree(self.tree, id);
            }
        }
        if after.is_empty() {
            return;
        }

        let keys = std::mem::take(self.keys);
        let ids = self.merged.split_off(start);
        let front = after.remove(&None).into_iter().flatten();
        let rows = keys.into_iter().zip(ids).flat_map(|row| {
            let behind = after.remove(&Some(row.0)).into_iter().flatten();
            std::iter::once(row).chain(behind)
        });
        for (key, id) in front.chain(rows) {
            self.keys.push(key);
            self.merged.push(id);
        }
    }

    /// Nothing was asked for: the rows stay as they are, less the leaving
    /// ones whose exit has settled, which are disposed.
    fn dispose_settled(&mut self, old: Vec<(u64, WidgetId)>) {
        for (key, id) in old {
            if self.leaving.contains_key(&key) && !is_exiting(self.tree, id) {
                self.leaving.remove(&key);
                crate::jobs::teardown_widget_subtree(self.tree, id);
            } else {
                self.keys.push(key);
                self.merged.push(id);
            }
        }
    }

    /// Start the exit a removed row declared, if it declared one, and detach
    /// it while it plays: nothing in it runs again, and its owner lives as
    /// long as the widget does. The teardown's comment above is why that is
    /// still safe — a live descendant could read state its owner had
    /// disposed, and a detached one is never asked to.
    ///
    /// An exit that begins already where it was going has nothing to play,
    /// and is a teardown like no exit at all.
    fn begin_leaving(&mut self, id: WidgetId) -> bool {
        let began = self
            .tree
            .with_widget_mut(id, |widget, id, tree| widget.begin_exit(tree, id))
            .unwrap_or(false);
        if !began || !is_exiting(self.tree, id) {
            return false;
        }
        // The pointer goes as the focus does: a card removed under the cursor
        // does not play its exit hovered, or pressed. Before the detach, which
        // is what makes the subtree refuse events.
        crate::reactive::diagnostics::snapshot_zone(|| {
            self.tree.with_widget_mut(id, |widget, id, tree| {
                widget.event(tree, id, &Event::MouseLeave)
            });
            self.tree.deliver_hover_changes();
        });
        crate::jobs::detach_widget_subtree(self.tree, id);
        true
    }
}

impl Drop for ChildrenSource {
    fn drop(&mut self) {
        // Push unregister jobs - will be processed in main loop
        // This defers the actual unregistration so Drop doesn't need tree access
        for widget_id in self.merged.drain(..) {
            request_job(widget_id, JobRequest::Unregister);
        }
        // Also push jobs for any widgets still in dynamic caches
        for segment in &mut self.segments {
            if let SegmentType::Dynamic { cached, .. } = segment {
                for widget_id in cached.values() {
                    request_job(*widget_id, JobRequest::Unregister);
                }
                cached.clear();
            }
        }
    }
}

/// Wrapper for dynamic items with key + widget factory.
///
/// `DynItem` represents a single item in a dynamic children list. Each item has:
/// - A unique `key` used for reconciliation (matching old/new items)
/// - A `widget_fn` factory that creates the widget lazily
///
/// # Ownership and Automatic Cleanup
///
/// When using the `.children()` method with a closure returning keyed items,
/// the `IntoChildren` trait implementation automatically wraps each item's
/// widget factory with an ownership scope. This means:
///
/// 1. **Signals created inside the factory are automatically cleaned up** when the
///    item is removed from the dynamic children list.
/// 2. **Effects created inside the factory are automatically disposed** when removed.
/// 3. **Custom cleanup callbacks** can be registered with [`on_cleanup`](crate::reactive::on_cleanup)
///    to clean up other resources (timers, connections, etc.).
///
/// Note: `DynItem::new` itself does NOT create the ownership scope. The wrapping
/// happens in the `IntoChildren<DynamicChildren>` trait implementation which calls
/// `with_owner()` and wraps the widget in `OwnedWidget`.
///
/// # Performance Characteristics
///
/// - Widget factories are only called for NEW keys (not seen before)
/// - Existing widgets are reused when their key persists across updates
/// - Cleanup runs synchronously when items are removed during reconciliation
/// - The reverse mapping ensures O(1) lookup for effect ownership checks
///
/// # Example
///
/// ```no_run
/// use guido::prelude::*;
/// # #[derive(Clone, PartialEq)] struct Item { id: u64, name: String }
/// # let data = create_signal(Vec::<Item>::new());
///
/// // `keyed` is how a caller reaches this: one owner per key, and ownership of
/// // whatever the builder creates is automatic.
/// container().children(keyed(
///     move || data.get(),
///     |item| item.id,
///     |item| {
///         // Signals created here are automatically cleaned up
///         let local_state = create_signal(0);
///
///         // Effects are automatically disposed
///         let id = item.id;
///         create_effect(move || {
///             println!("Item {id} state: {}", local_state.get());
///         });
///
///         // Register custom cleanup for non-reactive resources
///         on_cleanup(move || {
///             println!("Item {id} was removed!");
///         });
///
///         text(move || format!("Item: {}", item.name))
///     },
/// ));
/// ```
pub struct DynItem {
    pub key: u64,
    /// Factory function to create the widget. Only called for NEW keys.
    pub widget_fn: Box<dyn FnOnce() -> Box<dyn Widget>>,
}

impl DynItem {
    /// Create a new dynamic item with a widget factory closure.
    pub fn new<W: Widget + 'static>(key: u64, widget_fn: impl FnOnce() -> W + 'static) -> Self {
        Self {
            key,
            widget_fn: Box::new(move || Box::new(widget_fn())),
        }
    }
}

/// Widget wrapper that owns a reactive scope.
///
/// `OwnedWidget` wraps another widget and associates it with a reactive owner.
/// When the `OwnedWidget` is dropped (e.g., when removed from a dynamic children list),
/// it automatically disposes the owner and all resources created within that scope:
///
/// - **Signals** are disposed and subsequent access will panic
/// - **Effects** are stopped and will no longer run
/// - **Cleanup callbacks** registered via [`on_cleanup`](crate::reactive::on_cleanup)
///   are executed in reverse order (LIFO)
///
/// # When Ownership Wrapping Happens
///
/// Ownership wrapping is automatic when using the `.children()` method with dynamic
/// keyed items. The `IntoChildren<DynamicChildren>` trait implementation creates
/// `OwnedWidget` instances for each new item. You typically don't need to create
/// `OwnedWidget` directly.
///
/// # Performance Characteristics
///
/// - Disposal is synchronous and happens during reconciliation
/// - Child owners are disposed before parent owners (depth-first)
/// - The cleanup cost is O(S + E + C) where S = signals, E = effects, C = cleanup callbacks
///
/// # Example
///
/// ```no_run
/// use guido::prelude::*;
/// # use guido::reactive::__internal::with_owner;
/// use guido::widgets::children::OwnedWidget;
///
/// // Manual ownership wrapping (usually not needed - use .children() instead)
/// let (widget, owner_id) = with_owner(|| {
///     let signal = create_signal(42);
///     text(move || format!("Value: {}", signal.get()))
/// });
/// let owned = OwnedWidget::new(Box::new(widget), owner_id);
///
/// // When `owned` is dropped, the signal is disposed
/// ```
pub struct OwnedWidget {
    inner: Box<dyn Widget>,
    owner: OwnerHandle,
}

enum OwnerHandle {
    /// This widget is the sole user of the owner scope.
    Exclusive(OwnerId),
    /// The owner scope is shared by several widgets (one closure run built
    /// them all); it is disposed when the last of them drops.
    Shared(SharedOwner),
}

/// Reference-counted owner scope: disposes the owner when the last clone
/// drops. Used by reactive list closures, where a single run builds every
/// row inside one scope.
#[derive(Clone)]
pub struct SharedOwner {
    guard: Rc<OwnerGuard>,
}

struct OwnerGuard(OwnerId);

impl Drop for OwnerGuard {
    fn drop(&mut self) {
        dispose_owner_now(self.0);
    }
}

impl SharedOwner {
    pub fn new(owner_id: OwnerId) -> Self {
        Self {
            guard: Rc::new(OwnerGuard(owner_id)),
        }
    }
}

impl OwnedWidget {
    /// Create a new owned widget with the given inner widget and owner ID.
    pub fn new(inner: Box<dyn Widget>, owner_id: OwnerId) -> Self {
        Self {
            inner,
            owner: OwnerHandle::Exclusive(owner_id),
        }
    }

    /// Create an owned widget participating in a shared owner scope.
    pub fn new_shared(inner: Box<dyn Widget>, shared: SharedOwner) -> Self {
        Self {
            inner,
            owner: OwnerHandle::Shared(shared),
        }
    }
}

impl OwnerHandle {
    /// The scope this widget's reactive resources belong to, however it holds
    /// it — one widget to a scope, or one scope shared by a closure's whole run.
    fn id(&self) -> OwnerId {
        match self {
            OwnerHandle::Exclusive(id) => *id,
            OwnerHandle::Shared(shared) => shared.guard.0,
        }
    }
}

impl Drop for OwnedWidget {
    fn drop(&mut self) {
        if let OwnerHandle::Exclusive(owner_id) = self.owner {
            dispose_owner_now(owner_id);
        }
        // Shared: the SharedOwner guard disposes when its last clone drops
    }
}

impl Widget for OwnedWidget {
    fn advance_animations(&mut self, tree: &mut Tree, id: WidgetId) -> bool {
        self.inner.advance_animations(tree, id)
    }

    fn reconcile_children(&mut self, tree: &mut Tree, id: WidgetId) -> bool {
        self.inner.reconcile_children(tree, id)
    }

    fn begin_exit(&mut self, tree: &mut Tree, id: WidgetId) -> bool {
        self.inner.begin_exit(tree, id)
    }

    fn is_exiting(&self) -> bool {
        self.inner.is_exiting()
    }

    fn cancel_exit(&mut self, tree: &mut Tree, id: WidgetId) {
        self.inner.cancel_exit(tree, id)
    }

    fn owned_scope(&self) -> Option<OwnerId> {
        Some(self.owner.id())
    }

    fn refresh_paint_bounds(&self, tree: &mut Tree, id: WidgetId) {
        self.inner.refresh_paint_bounds(tree, id)
    }

    fn placement(&self, tree: &Tree, id: WidgetId) -> crate::widgets::Placement {
        self.inner.placement(tree, id)
    }

    fn layout_hints(&self) -> LayoutHints {
        self.inner.layout_hints()
    }

    /// Registration is reactive work, so it happens under this widget's own
    /// scope rather than under whatever scope the frame is in.
    ///
    /// This and [`layout`](Self::layout) are the two that re-enter it, and the
    /// line is drawn there because they are the two the frame runs as
    /// *machinery*: nothing a caller wrote decides what they build.
    ///
    /// `event` and `reconcile_children` run a caller's own closure — a handler,
    /// an `items_fn` — and a signal made there may be handed somewhere that
    /// outlives the row on purpose. Disposing it would turn a later read into a
    /// panic, so those two are left alone, and a test says so rather than a
    /// comment promising it. That nothing in the library allocates there either
    /// is true today and is the weaker half of the reason: it would stop being
    /// true without anything failing, which is why it is not the argument.
    ///
    /// The factory ran inside `with_owner`; this runs afterwards, and anything
    /// it creates — `Container::fold_enabled`'s derived — would otherwise be
    /// filed under the surface and outlive the widget by the whole life of the
    /// application.
    ///
    /// Descendants come along: a plain `Container` inside this one is
    /// registered from within this call, so it is inside the scope too.
    fn register_children(&mut self, tree: &mut Tree, id: WidgetId) {
        under_owner(self.owner.id(), || self.inner.register_children(tree, id))
    }

    /// Laying out builds things too, so it is inside the scope for the same
    /// reason registration is.
    ///
    /// A scroller assembles its scrollbar's track and handle the first time it
    /// lays out — two containers, and every declared property on them is a
    /// signal. That is ten per row against `fold_enabled`'s one, and it needs
    /// nothing of the caller but `.scroll(..)`.
    fn layout(&mut self, ctx: &mut LayoutCtx, constraints: Constraints) -> Size {
        under_owner(self.owner.id(), || self.inner.layout(ctx, constraints))
    }

    fn paint(&self, ctx: &mut PaintContext) {
        self.inner.paint(ctx)
    }

    fn event(&mut self, tree: &mut Tree, id: WidgetId, event: &Event) -> EventResponse {
        self.inner.event(tree, id, event)
    }
}

#[cfg(test)]
mod tests {
    use std::cell::RefCell;

    use super::*;
    use crate::jobs::pump_and_layout;
    use crate::reactive::storage::live_signal_count;
    use crate::reactive::{RwSignal, create_signal};
    use crate::widgets::{AnyWidget, Scroll, container, keyed};

    /// A registered root, and the two phases that make a keyed list actually
    /// replace its rows: the queued jobs, then a layout.
    ///
    /// Without the jobs the reconciler never runs — the widget ids come back
    /// identical and a leak test reads a meaningless zero. The generation
    /// counter moving on the reused ids is what says a round happened.
    struct Rows {
        tree: Tree,
        root: WidgetId,
    }

    impl Rows {
        fn new(widget: impl Widget + 'static) -> Self {
            let mut tree = Tree::new();
            let root = tree.register(Box::new(widget));
            tree.with_widget_mut(root, |w, id, t| w.register_children(t, id));
            // The first frame builds the rows. Without it the baseline below
            // is taken before any exist, and every round after it looks like
            // growth.
            let mut rows = Self { tree, root };
            rows.frame();
            rows
        }

        /// A press and release at a point, in the surface's coordinates.
        fn click(&mut self, x: f32, y: f32) {
            let root = self.root;
            crate::reactive::diagnostics::snapshot_zone(|| {
                for event in [
                    Event::mouse_down(x, y, crate::widgets::widget::MouseButton::Left),
                    Event::mouse_up(x, y, crate::widgets::widget::MouseButton::Left),
                ] {
                    self.tree.dispatch(root, &event);
                }
            });
        }

        fn frame(&mut self) {
            pump_and_layout(
                &mut self.tree,
                self.root,
                Constraints::new(0.0, 0.0, 200.0, 200.0),
            );
        }
    }

    /// Replace every key, so each round builds a full set of rows and discards
    /// the set before it. The assertion is here so that every caller has it.
    fn churn(rows: &mut Rows, keys: RwSignal<Vec<u32>>, round: u32) {
        let before = rows.tree.get_children(rows.root).to_vec();
        keys.set((0..ROWS).map(|i| round * 100 + i).collect());
        rows.frame();
        assert_ne!(
            before,
            rows.tree.get_children(rows.root).to_vec(),
            "round {round} replaced no rows, so nothing after it measures anything"
        );
    }

    /// How wide `churn` makes a list, whatever it started at.
    const ROWS: u32 = 4;

    /// A row's reactive resources die with the row — including the ones built
    /// while it was being *registered*, not only the ones its factory built.
    ///
    /// `Container::fold_enabled` is the only thing in the widget layer that
    /// creates a signal during `register_children`, and it does so exactly when
    /// a row declares `enabled` inside a control that declares it too. Until
    /// this was fixed the derived it built was filed under the *surface*, and a
    /// list that churned leaked one signal per row for the surface's lifetime —
    /// measured at +41 over forty rows built and discarded.
    ///
    /// The baseline is taken after a round rather than before, because the
    /// dynamic-children machinery allocates one signal on its first reconcile
    /// and never again: counting from zero would fold that one-off into the
    /// number and make the test assert a constant instead of a slope.
    #[test]
    fn a_signal_built_while_a_row_registers_dies_with_the_row() {
        let keys = create_signal(vec![0u32, 1, 2, 3]);
        let outer = create_signal(true);
        let mut rows = Rows::new(
            container()
                .width(200.0)
                .height(200.0)
                .enabled(outer)
                .children(keyed(
                    move || keys.get(),
                    |k| *k,
                    move |_| {
                        let own = create_signal(true);
                        container().width(50.0).height(10.0).enabled(own).into_any()
                    },
                )),
        );

        churn(&mut rows, keys, 1);
        let settled = live_signal_count();

        for round in 2..=10u32 {
            churn(&mut rows, keys, round);
        }

        assert_eq!(
            live_signal_count(),
            settled,
            "thirty-six rows built and discarded left signals behind"
        );
    }

    /// `event` is outside the scope on purpose, and this is what says so.
    ///
    /// A handler runs at a caller's intent, not as machinery, and an
    /// application may create a signal there and hand it somewhere that
    /// outlives the row — a selection the list reports upwards, say. Wrapping
    /// `event` would dispose it and turn every later read into a panic. So the
    /// exclusion is a promise to the caller, and a promise nothing tested is
    /// one the next person to widen this would break without hearing anything.
    #[test]
    fn a_signal_a_handler_creates_outlives_the_row_that_created_it() {
        let keys = create_signal(vec![0u32, 1, 2, 3]);
        let escaped: Rc<RefCell<Option<RwSignal<u32>>>> = Rc::new(RefCell::new(None));
        let sink = escaped.clone();
        let mut rows = Rows::new(container().width(200.0).height(200.0).children(keyed(
            move || keys.get(),
            |k| *k,
            move |k| {
                let sink = sink.clone();
                container()
                    .width(50.0)
                    .height(10.0)
                    .on_click(move || *sink.borrow_mut() = Some(create_signal(k)))
                    .into_any()
            },
        )));

        // Click the first row, so its handler builds a signal and hands it out.
        rows.click(0.0, 0.0);
        let handed_out = escaped.borrow().expect("the handler ran");
        assert_eq!(handed_out.get_untracked(), 0);

        // Now churn that row away entirely.
        for round in 1..=3u32 {
            churn(&mut rows, keys, round);
        }

        assert_eq!(
            handed_out.get_untracked(),
            0,
            "the row's disposal took a signal its handler had given away"
        );
    }

    /// The control, and it is what makes the test above mean anything: a row
    /// that declares nothing for `fold_enabled` to fold allocates no signal at
    /// registration, so it churned cleanly even before the fix. If this ever
    /// fails, the one above is measuring the machinery rather than the defect.
    #[test]
    fn a_row_that_builds_nothing_at_registration_was_never_the_problem() {
        let keys = create_signal(vec![0u32, 1, 2, 3]);
        let mut rows = Rows::new(container().width(200.0).height(200.0).children(keyed(
            move || keys.get(),
            |k| *k,
            move |_| -> AnyWidget { container().width(50.0).height(10.0).into_any() },
        )));

        churn(&mut rows, keys, 1);
        let settled = live_signal_count();
        for round in 2..=10u32 {
            churn(&mut rows, keys, round);
        }
        assert_eq!(live_signal_count(), settled);
    }

    /// The scope a row re-enters is its own, so a list *inside* a row is inside
    /// it too — and the rows that list builds get their owners parented there
    /// rather than at the surface.
    ///
    /// Three levels of `enabled` nested in each other, which is three derived
    /// signals per leaf and the shape that leaked hardest: +108 over nine
    /// rounds before the fix, against +36 for the flat list above.
    #[test]
    fn a_list_inside_a_row_is_inside_the_row_s_scope() {
        let outer_keys = create_signal(vec![0u32, 1, 2, 3]);
        let enabled = create_signal(true);
        let mut rows = Rows::new(
            container()
                .width(200.0)
                .height(200.0)
                .enabled(enabled)
                .children(keyed(
                    move || outer_keys.get(),
                    |k| *k,
                    move |k| {
                        let inner_keys = create_signal(vec![k * 10, k * 10 + 1]);
                        let own = create_signal(true);
                        container()
                            .width(100.0)
                            .height(50.0)
                            .enabled(own)
                            .children(keyed(
                                move || inner_keys.get(),
                                |x| *x,
                                move |_| {
                                    let deep = create_signal(true);
                                    container().width(10.0).height(5.0).enabled(deep).into_any()
                                },
                            ))
                            .into_any()
                    },
                )),
        );
        churn(&mut rows, outer_keys, 1);
        let settled = live_signal_count();
        for round in 2..=10u32 {
            churn(&mut rows, outer_keys, round);
        }
        assert_eq!(
            live_signal_count(),
            settled,
            "a nested list left its rows' signals behind"
        );
    }

    /// A row that scrolls builds its scrollbar during *layout*, not during
    /// registration — and every declared property on the track and the handle
    /// is a signal.
    ///
    /// This is the same defect an octave lower: ten signals per row against
    /// `fold_enabled`'s one, measured at +360 over thirty-six rows, and it asks
    /// nothing of the caller but `.scroll(..)`. A fix that covered only
    /// registration would have left it exactly as it was.
    #[test]
    fn a_scrollbar_built_while_a_row_lays_out_dies_with_the_row() {
        let keys = create_signal(vec![0u32, 1, 2, 3]);
        let mut rows = Rows::new(container().width(200.0).height(200.0).children(keyed(
            move || keys.get(),
            |k| *k,
            move |_| {
                container()
                    .width(50.0)
                    .height(20.0)
                    .scroll(Scroll::vertical())
                    .children(
                        (0..8)
                            .map(|_| container().width(50.0).height(20.0).into_any())
                            .collect::<Vec<_>>(),
                    )
                    .into_any()
            },
        )));
        churn(&mut rows, keys, 1);
        let settled = live_signal_count();
        for round in 2..=10u32 {
            churn(&mut rows, keys, round);
        }
        assert_eq!(
            live_signal_count(),
            settled,
            "a scroller left its scrollbar's signals behind"
        );
    }
}