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
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
//! Reactive ownership system for automatic resource cleanup.
//!
//! This module implements a reactive owner pattern (similar to Leptos/SolidJS/Dioxus)
//! where signals and effects belong to an owner, and when the owner is disposed,
//! all owned resources are automatically cleaned up.
//!
//! # Overview
//!
//! - Every signal and effect can belong to an owner
//! - Owners form a tree structure (child owners are disposed before parents)
//! - When an owner is disposed, all owned signals, effects, and cleanup callbacks are cleaned up
//! - `on_cleanup` allows registering custom cleanup logic (timers, connections, etc.)
//!
//! # Example
//!
//! ```no_run
//! # use guido::prelude::*;
//! # use guido::reactive::__internal::{with_owner, dispose_owner};
//! // Create a scope with automatic cleanup
//! let (result, owner_id) = with_owner(|| {
//!     let signal = create_signal(42);
//!     create_effect(move || {
//!         println!("Signal: {}", signal.get());
//!     });
//!
//!     // Register custom cleanup
//!     on_cleanup(|| {
//!         println!("Cleaning up!");
//!     });
//!
//!     signal
//! });
//!
//! // Later, dispose everything in that scope
//! dispose_owner(owner_id);
//! // All signals, effects, and cleanup callbacks are now disposed
//! ```

use std::any::{Any, TypeId};
use std::num::NonZeroU32;
use std::rc::Rc;

use super::invalidation::clear_signal_subscribers;
use super::runtime::{EffectId, SignalId, flush_unless_batching, with_runtime};
use super::state::with_reactive;
use super::storage::dispose_signal;

/// The values one scope declares, in declaration order.
type Declarations = Vec<(TypeId, Rc<dyn Any>)>;

/// Unique identifier for an owner in the owner arena.
///
/// Generational: the arena recycles slot indices and bumps the generation on
/// every reuse, so a stale `OwnerId` held after disposal can never dispose or
/// mutate an unrelated owner that later occupied the same slot.
///
/// The generation counts from one so that zero is free to be the niche: an
/// `Option<OwnerId>` is eight bytes rather than twelve, which is what
/// `Owner::parent` and every derived closure's captured scope are made of.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct OwnerId {
    index: u32,
    generation: NonZeroU32,
}

impl OwnerId {
    /// Run `f` with this scope current, so what it creates belongs here.
    ///
    /// For an effect body that makes something meant to outlive the run:
    /// everything else a run creates is disposed when the effect runs again.
    ///
    /// ```no_run
    /// # use guido::prelude::*;
    /// # let trigger = create_signal(0);
    /// let outer = current_owner().expect("created inside a scope");
    /// create_effect(move || {
    ///     trigger.get();
    ///     let kept = outer.run(|| create_signal(0)); // lives as long as `outer`
    /// });
    /// ```
    ///
    /// It enters a scope that exists; [`with_owner`] is what makes one. Under a
    /// scope that has been disposed, what `f` creates is owned by nothing.
    pub fn run<T>(self, f: impl FnOnce() -> T) -> T {
        under_owner(self, f)
    }
}

/// An owner that manages the lifecycle of reactive primitives.
struct Owner {
    /// The owner this one was created under, if any. Used to prune this
    /// owner from the parent's `children` list on disposal.
    parent: Option<OwnerId>,
    /// What the scope holds, allocated the first time it holds anything: most
    /// scopes never do — every effect has one, and most runs make nothing — and
    /// four empty lists inline made the arena slot 120 bytes rather than 24.
    held: Option<Box<Held>>,
}

/// What one scope holds.
#[derive(Default)]
struct Held {
    signals: Vec<SignalId>,
    effects: Vec<EffectId>,
    cleanups: Vec<Box<dyn FnOnce()>>,
    children: Vec<OwnerId>,
    /// Values declared for this scope and everything below it, keyed by type.
    ///
    /// Inline: the scope's own box is what keeps a scope that declares nothing
    /// from paying for the list, and a second one would be a second hop on
    /// every step of a context lookup's walk up the scopes.
    ///
    /// `Rc` rather than `Box` on the value so a lookup can clone the handle and
    /// drop the arena borrow before the value reaches a caller's closure: that
    /// closure reads signals, and a signal read borrows the arena again.
    contexts: Declarations,
}

impl Owner {
    fn new(parent: Option<OwnerId>) -> Self {
        Self { parent, held: None }
    }

    /// What the scope holds, allocated if this is the first thing it will.
    fn held(&mut self) -> &mut Held {
        self.held.get_or_insert_default()
    }
}

impl Held {
    /// Whether the scope holds nothing — what most effect runs leave behind,
    /// which then costs no more than this check.
    fn is_empty(&self) -> bool {
        self.signals.is_empty()
            && self.effects.is_empty()
            && self.cleanups.is_empty()
            && self.children.is_empty()
            && self.contexts.is_empty()
    }
}

/// Slot in the owner arena. The generation survives vacancy so recycled
/// indices can be distinguished from their previous occupants.
struct OwnerSlot {
    owner: Option<Owner>,
    generation: NonZeroU32,
    /// Whether the scope's effects are held back: set by [`pause_owner`] on a
    /// scope and every scope below it, cleared by [`resume_owner`]. A scope
    /// opened under a paused one starts paused.
    ///
    /// Here rather than on `Owner`, where it would cost the arena eight bytes a
    /// slot; beside the generation it fits in the padding.
    paused: bool,
}

/// Arena-based storage for owners with slot recycling.
#[derive(Default)]
pub(crate) struct OwnerArena {
    slots: Vec<OwnerSlot>,
    /// Vacant slot indices available for reuse.
    free_indices: Vec<u32>,
}

impl OwnerArena {
    fn allocate(&mut self, parent: Option<OwnerId>) -> OwnerId {
        let paused = parent.is_some_and(|parent| self.is_paused(parent));
        let owner = Owner::new(parent);
        if let Some(index) = self.free_indices.pop() {
            let slot = &mut self.slots[index as usize];
            // Wrapping, and skipping zero on the way round: zero is what makes
            // `Option<OwnerId>` eight bytes.
            slot.generation = slot.generation.checked_add(1).unwrap_or(NonZeroU32::MIN);
            slot.owner = Some(owner);
            slot.paused = paused;
            OwnerId {
                index,
                generation: slot.generation,
            }
        } else {
            let index = self.slots.len() as u32;
            self.slots.push(OwnerSlot {
                owner: Some(owner),
                generation: NonZeroU32::MIN,
                paused,
            });
            OwnerId {
                index,
                generation: NonZeroU32::MIN,
            }
        }
    }

    /// The slot `id` occupies, if the scope is still there.
    fn live_slot(&self, id: OwnerId) -> Option<&OwnerSlot> {
        self.slots
            .get(id.index as usize)
            .filter(|slot| slot.generation == id.generation && slot.owner.is_some())
    }

    fn get(&self, id: OwnerId) -> Option<&Owner> {
        self.live_slot(id).and_then(|slot| slot.owner.as_ref())
    }

    fn get_mut(&mut self, id: OwnerId) -> Option<&mut Owner> {
        self.slots
            .get_mut(id.index as usize)
            .filter(|slot| slot.generation == id.generation)
            .and_then(|slot| slot.owner.as_mut())
    }

    /// Whether `id` is paused. A scope that is gone is not: nothing of it is
    /// left to hold back.
    fn is_paused(&self, id: OwnerId) -> bool {
        self.live_slot(id).is_some_and(|slot| slot.paused)
    }

    /// Set `paused` on `id` and every scope below it, and hand back the effects
    /// they own.
    fn set_paused(&mut self, id: OwnerId, paused: bool) -> Vec<EffectId> {
        let mut effects = Vec::new();
        let mut stack = vec![id];
        while let Some(id) = stack.pop() {
            let Some(slot) = self
                .slots
                .get_mut(id.index as usize)
                .filter(|slot| slot.generation == id.generation)
            else {
                continue;
            };
            let Some(owner) = &slot.owner else {
                continue;
            };
            slot.paused = paused;
            if let Some(held) = &owner.held {
                effects.extend_from_slice(&held.effects);
                stack.extend_from_slice(&held.children);
            }
        }
        effects
    }

    fn take(&mut self, id: OwnerId) -> Option<Owner> {
        let slot = self
            .slots
            .get_mut(id.index as usize)
            .filter(|slot| slot.generation == id.generation)?;
        let owner = slot.owner.take();
        if owner.is_some() {
            // Recycle the slot. Any still-live OwnerId for it is now stale
            // and will fail the generation check above.
            self.free_indices.push(id.index);
        }
        owner
    }
}

/// Create a root owner and set it as the current owner.
///
/// This is used by `App::run()` to establish a root scope for all reactive
/// primitives created during setup. The root owner owns everything — when
/// disposed, all signals, effects, and cleanup callbacks cascade.
pub(crate) fn create_root_owner() -> OwnerId {
    with_reactive(|reactive| {
        let id = reactive.owners.borrow_mut().allocate(None);
        reactive.current_owner.set(Some(id));
        reactive.root_owner.set(Some(id));
        id
    })
}

/// Run `f` under the root owner instead of whatever scope is current.
///
/// For process-wide state built on first use — the modifier state, the output
/// list, the compositor's capabilities. Each lives in a thread-local behind a
/// lazily created signal, and *whoever reads it first* decides the owner. When
/// that first reader is a widget's reactive closure, the signal belongs to a
/// scope that is disposed on the closure's next run, while the thread-local goes
/// on holding the dead handle: the read after that panics with "signal was
/// disposed". Anchoring the creation at the root makes the lifetime match what
/// the thing actually is.
///
/// With no `App` — unit tests — there is no root, and the current scope is used
/// as before.
pub(crate) fn with_root_owner<T>(f: impl FnOnce() -> T) -> T {
    match with_reactive(|reactive| reactive.root_owner.get()) {
        Some(root) => under_owner(root, f),
        None => f(),
    }
}

/// Run `f` with `owner_id` as the current owner, whatever it was before.
///
/// The one place the current owner is swapped: [`with_owner`] allocates a scope
/// and hands it here, [`with_root_owner`] names the root, a widget names its
/// own, and [`under_scope`] names the one a derived closure was written in —
/// which is the frequent one, once per read of a reactive property. Restoring on unwind is why they all go through it — a leaked scope
/// silently re-parents every reactive resource created afterwards, and the copy
/// that forgot the guard is the one that would have done it.
///
/// It does not *make* a scope. [`with_owner`] is the one that does, and picking
/// the wrong one compiles: this one files resources under an owner somebody else
/// disposes, that one under a fresh scope nothing does.
pub(crate) fn under_owner<T>(owner_id: OwnerId, f: impl FnOnce() -> T) -> T {
    let previous = with_reactive(|reactive| reactive.current_owner.replace(Some(owner_id)));
    let _guard = crate::reactive::guard::defer(move || {
        with_reactive(|reactive| reactive.current_owner.set(previous));
    });
    f()
}

/// Run `f` under `scope`, where there is one and it is not already current.
///
/// Two things are nothing to do, and both are common: a closure written outside
/// any scope has none to enter, and entering the scope that is already current
/// changes nothing — which is every read during layout, since
/// `OwnedWidget::layout` has entered the row's scope before any of its
/// properties are read.
///
/// The second is worth its branch and then some. Without it a frame of three
/// hundred rows measured 77.5µs against 56.5µs with it — the swap is cheap and
/// a frame does it thousands of times. It is also invisible to every test,
/// because entering the scope you are already in is a no-op by definition: the
/// mutation job reports the guard as unkilled and always will, and the
/// benchmark in `reactive::bench` is what holds it instead.
pub(crate) fn under_scope<T>(scope: Option<OwnerId>, f: impl FnOnce() -> T) -> T {
    match scope {
        Some(scope) if current_owner() != Some(scope) => under_owner(scope, f),
        _ => f(),
    }
}

/// Execute a closure within a new owner scope.
///
/// All signals and effects created within the closure will be registered
/// with this owner and automatically cleaned up when the owner is disposed.
///
/// Returns a tuple of the closure's return value and the owner ID.
///
/// This is used internally by the dynamic children system to automatically
/// manage reactive resource lifetimes. User code should use `on_cleanup`
/// inside dynamic children closures to register custom cleanup logic.
///
/// **Note:** This function is not part of the public API and may change.
/// Use `on_cleanup` for registering cleanup callbacks in user code.
pub fn with_owner<T>(f: impl FnOnce() -> T) -> (T, OwnerId) {
    let owner_id = child_scope();
    (under_owner(owner_id, f), owner_id)
}

/// Make a scope under the current one, if any, without entering it.
///
/// [`with_owner`] makes one and enters it at once; an effect makes one when it
/// is created and enters it on each run.
pub(crate) fn child_scope() -> OwnerId {
    with_reactive(|reactive| {
        let parent_id = reactive.current_owner.get();
        let mut owners = reactive.owners.borrow_mut();
        let id = owners.allocate(parent_id);

        // Register as child of current owner
        if let Some(parent_id) = parent_id
            && let Some(parent_owner) = owners.get_mut(parent_id)
        {
            parent_owner.held().children.push(id);
        }

        id
    })
}

/// Hand the current scope's declarations to `f`, or `None` if no scope is
/// current.
///
/// What may be declared, and what a second declaration of a type means, is the
/// caller's to decide — see `context`. This is the storage and nothing else.
pub(crate) fn with_scope_declarations<R>(f: impl FnOnce(&mut Declarations) -> R) -> Option<R> {
    with_reactive(|reactive| {
        let id = reactive.current_owner.get()?;
        let mut owners = reactive.owners.borrow_mut();
        // A current scope that is no longer in the arena is a scope that is
        // gone, which is the same answer as none at all — and the caller has a
        // better sentence for it than an `expect` here would.
        let owner = owners.get_mut(id)?;
        Some(f(&mut owner.held().contexts))
    })
}

/// The nearest declaration of `type_id` at or above the current scope.
///
/// `None` where nothing declared it and where no scope is current at all — a
/// handler, a paint closure — which are the same answer on purpose: both mean
/// *there is nothing here to read*.
///
/// The handle is cloned and the arena borrow released before it goes back to
/// the caller, which is what lets a borrowed read hand the value to a closure
/// that reads a signal — the shape `call_derived` uses, for the same
/// reason.
pub(crate) fn nearest_declaration(type_id: TypeId) -> Option<Rc<dyn Any>> {
    with_reactive(|reactive| {
        let mut scope = reactive.current_owner.get();
        let owners = reactive.owners.borrow();
        while let Some(id) = scope {
            let owner = owners.get(id)?;
            let declared = owner
                .held
                .as_ref()
                .and_then(|held| held.contexts.iter().find(|(d, _)| *d == type_id));
            if let Some((_, value)) = declared {
                return Some(Rc::clone(value));
            }
            scope = owner.parent;
        }
        None
    })
}

/// Get the current owner ID, if any.
///
/// Returns `None` if not currently inside an owner scope.
pub fn current_owner() -> Option<OwnerId> {
    with_reactive(|reactive| reactive.current_owner.get())
}

/// Hand the current scope to `f`, if there is one and it is still in the
/// arena. One visit to the reactive state rather than two: the scope and the
/// arena are fields of one struct now, and every registration below wants
/// both.
fn with_current_owner(f: impl FnOnce(&mut Owner)) {
    with_reactive(|reactive| {
        let Some(id) = reactive.current_owner.get() else {
            return;
        };
        if let Some(owner) = reactive.owners.borrow_mut().get_mut(id) {
            f(owner);
        }
    });
}

/// Dispose an owner and all its resources.
///
/// This will:
/// 1. Recursively dispose all child owners (depth-first)
/// 2. Run all cleanup callbacks in reverse order
/// 3. Dispose all effects
/// 4. Dispose all signals
///
/// After disposal, any attempt to access the disposed signals will panic
/// with a clear error message.
///
/// Internal engine: synchronous disposal, used by the library's own
/// teardown paths (surface close, reconcile discard, component Drop)
/// where ordering invariants are controlled. A running effect that
/// disposes its own owner is protected by the runtime's take/put-back
/// callback pattern (`EffectState::DisposedWhileRunning`), but code
/// after the call must not touch the owner's signals — public callers
/// get the deferred [`dispose_owner`] instead, which is safe anywhere.
#[doc(hidden)]
pub fn dispose_owner_now(id: OwnerId) {
    // Take the owner out of the arena and prune it from its parent's
    // children list. Without the pruning, long-lived parents (most notably
    // the root owner) accumulate one dead child entry for every owner ever
    // created under them. During recursive disposal the parent has already
    // been taken from the arena, so `get_mut` fails and the prune is skipped.
    let owner = with_reactive(|reactive| {
        let mut arena = reactive.owners.borrow_mut();
        let owner = arena.take(id)?;
        if let Some(parent_id) = owner.parent
            && let Some(parent) = arena.get_mut(parent_id)
            && let Some(held) = parent.held.as_mut()
            && let Some(pos) = held.children.iter().position(|c| *c == id)
        {
            // Sibling disposal order is unspecified, so swap_remove is fine.
            held.children.swap_remove(pos);
        }
        Some(owner)
    });

    if let Some(mut held) = owner.and_then(|owner| owner.held) {
        release(&mut held);
    }
}

/// Dispose what `id` holds and keep the scope itself, empty, for whatever is
/// made in it next.
///
/// What an effect does before each run: what the last run made goes, in the
/// order [`dispose_owner_now`] disposes it, and the next run fills the same
/// scope again.
///
/// The scope keeps what held it — the box and the lists, emptied — so a run
/// that makes something, as the last one did, allocates nothing to file it.
pub(crate) fn empty_owner(id: OwnerId) {
    let held = with_reactive(|reactive| {
        let mut arena = reactive.owners.borrow_mut();
        let held = arena.get_mut(id)?.held.as_deref_mut()?;
        (!held.is_empty()).then(|| std::mem::take(held))
    });
    let Some(mut held) = held else {
        return;
    };
    release(&mut held);
    // Put the emptied lists back, unless the scope went while its contents
    // were released, or something was filed in it meanwhile.
    with_reactive(|reactive| {
        let mut arena = reactive.owners.borrow_mut();
        if let Some(kept) = arena
            .get_mut(id)
            .and_then(|owner| owner.held.as_deref_mut())
            && kept.is_empty()
        {
            *kept = held;
        }
    });
}

/// Dispose everything `held` holds, taken out of the arena first: its
/// children depth-first, then its cleanups last-first, then its effects, then
/// its signals, and its declarations dropped. The lists are left empty with
/// their allocations.
fn release(held: &mut Held) {
    for child_id in held.children.drain(..) {
        dispose_owner_now(child_id);
    }

    for cleanup in held.cleanups.drain(..).rev() {
        // Teardown code reads for the current value; the scope is going away
        crate::reactive::diagnostics::snapshot_zone(cleanup);
    }

    for effect_id in held.effects.drain(..) {
        with_runtime(|rt| rt.dispose_effect(effect_id));
    }

    // Dispose signals (clear widget and effect subscriptions first to
    // prevent stale notifications from a future occupant of the slot)
    for signal_id in held.signals.drain(..) {
        clear_signal_subscribers(signal_id);
        with_runtime(|rt| rt.dispose_signal_subscriptions(signal_id));
        dispose_signal(signal_id);
    }

    held.contexts.clear();
}

/// Hold back every effect owned by `id` and the scopes below it, until
/// [`resume_owner`] or disposal.
///
/// For a subtree that is leaving but not yet disposed: its effects must not run
/// on what they read — the item a row was built for may already be gone — but
/// they must still be there if the row is asked for again. A write to what a
/// paused effect read does not run it; it is remembered, and the effect runs
/// once on resume. Svelte 5 does the same for an outroing block: `pause_effect`
/// marks its effects `INERT`, and `resume_effect` runs the ones that went dirty.
pub(crate) fn pause_owner(id: OwnerId) {
    let effects = with_reactive(|reactive| reactive.owners.borrow_mut().set_paused(id, true));
    with_runtime(|rt| rt.set_effects_paused(&effects, true));
}

/// Undo [`pause_owner`]: the effects of `id` and the scopes below it run on
/// what they read again, and each one a write reached while it was paused runs
/// now, once.
pub(crate) fn resume_owner(id: OwnerId) {
    let effects = with_reactive(|reactive| reactive.owners.borrow_mut().set_paused(id, false));
    with_runtime(|rt| rt.set_effects_paused(&effects, false));
    flush_unless_batching();
}

/// Whether the current scope is paused, so an effect made in it starts paused.
pub(crate) fn current_owner_is_paused() -> bool {
    with_reactive(|reactive| {
        reactive
            .current_owner
            .get()
            .is_some_and(|id| reactive.owners.borrow().is_paused(id))
    })
}

/// Register a cleanup callback to run when the current owner is disposed.
///
/// This is useful for cleaning up non-reactive resources like timers,
/// event listeners, or external connections.
///
/// Cleanup callbacks are run in reverse order (LIFO) - the last registered
/// callback runs first.
///
/// # Panics
///
/// This function will silently do nothing if called outside an owner scope.
///
/// # Example
///
/// ```no_run
/// # use guido::prelude::*;
/// # use guido::reactive::__internal::with_owner;
/// # let start_timer = || 0u32;
/// # let stop_timer = |_: u32| {};
/// with_owner(|| {
///     // Start a timer
///     let timer_id = start_timer();
///
///     // Register cleanup to stop the timer
///     on_cleanup(move || {
///         stop_timer(timer_id);
///     });
/// });
/// ```
pub fn on_cleanup(f: impl FnOnce() + 'static) {
    with_current_owner(|owner| owner.held().cleanups.push(Box::new(f)));
}

/// Register a signal with the current owner.
///
/// This is called internally by `create_signal` to register newly created
/// signals for automatic cleanup.
pub(crate) fn register_signal(id: SignalId) {
    with_current_owner(|owner| owner.held().signals.push(id));
}

/// Register an effect with the current owner.
///
/// This is called internally by `create_effect` to register newly created
/// effects for automatic cleanup.
pub(crate) fn register_effect(id: EffectId) {
    with_current_owner(|owner| owner.held().effects.push(id));
}

/// Check if an effect is owned by any owner.
///
/// The effect's slot in the runtime holds its own scope, which is a child of
/// the one that owns the effect. A map here beside it would be a second copy of
/// one fact, maintained on the creation and disposal paths to answer a question
/// only these tests ask.
#[cfg(test)]
pub(crate) fn effect_has_owner(id: EffectId) -> bool {
    crate::reactive::runtime::with_runtime(|rt| rt.effect_scope(id)).is_some_and(|scope| {
        with_reactive(|reactive| reactive.owners.borrow().get(scope)?.parent).is_some()
    })
}

/// Dispose an owner: all its signals, effects, and cleanup callbacks.
///
/// Disposal is **deferred**: the main loop drains pending disposals once
/// per iteration, at a point where no user closure is on the stack. That
/// makes this safe to call from anywhere — including code the owner
/// itself owns (an effect observing a popup's dismissal, a dialog's own
/// close button) and code whose widgets outlive the current instant
/// (a popup surface that lives until its Close command is processed).
///
/// Disposing the same owner twice (or an already-disposed owner) is
/// harmless.
pub fn dispose_owner(id: OwnerId) {
    // Pushing is what wakes the loop, so a disposal requested in a quiet
    // moment — a compositor dismissal with nothing else going on — is not
    // postponed indefinitely.
    with_reactive(|reactive| reactive.pending_disposals.push(id));
}

/// Run every pending deferred disposal. Called by the main loop at a safe
/// point — never call from inside reactive computations.
pub(crate) fn flush_pending_disposals() {
    // split_off keeps draining safe even if a cleanup callback disposes
    // another owner while running (it lands in the next batch)
    loop {
        let batch = with_reactive(|reactive| reactive.pending_disposals.drain());
        if batch.is_empty() {
            return;
        }
        for id in batch {
            dispose_owner_now(id);
        }
    }
}

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

    /// The guard is the whole of `under_owner`, and until this test the suite
    /// said nothing about it: the restore could be moved out of `defer` and
    /// onto the line after `f()` with every test still green.
    ///
    /// It matters because the corruption is silent and permanent. The one
    /// caller of `with_root_owner` (`global.rs`) runs application code inside
    /// it; if that panics and the owner is not put back, the current owner stays
    /// pinned at the root, and every `with_owner` after it captures root as its
    /// `previous` and restores *that*. Nothing ever notices.
    ///
    /// Both spellings are checked, because they are one function now.
    #[test]
    fn an_unwinding_closure_puts_the_previous_owner_back() {
        let hushed = std::panic::take_hook();
        std::panic::set_hook(Box::new(|_| {}));

        let outer = create_root_owner();
        assert_eq!(current_owner(), Some(outer));

        let panicked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            with_owner(|| panic!("a builder that gave up"));
        }));
        assert!(panicked.is_err());
        assert_eq!(
            current_owner(),
            Some(outer),
            "a new scope that unwound left itself current"
        );

        let panicked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            with_root_owner(|| panic!("a global initialiser that gave up"))
        }));
        assert!(panicked.is_err());
        assert_eq!(
            current_owner(),
            Some(outer),
            "the root stayed current after an unwind, and would have swallowed \
             every scope opened afterwards"
        );

        std::panic::set_hook(hushed);
        crate::reactive::state::reset();
    }

    #[test]
    fn test_with_owner_basic() {
        let (value, owner_id) = with_owner(|| 42);
        assert_eq!(value, 42);
        dispose_owner_now(owner_id);
    }

    /// The public dispose_owner defers: nothing is disposed until the main
    /// loop flushes, so an owned computation can safely dispose its own
    /// owner ("close myself" UI). Double-disposing is harmless.
    #[test]
    fn test_dispose_owner_defers_disposal() {
        let cleaned = std::rc::Rc::new(std::cell::Cell::new(false));
        let flag = cleaned.clone();
        let (_, owner_id) = with_owner(move || {
            on_cleanup(move || flag.set(true));
        });

        dispose_owner(owner_id);
        dispose_owner(owner_id); // idempotent
        assert!(
            !cleaned.get(),
            "public dispose_owner must not dispose synchronously"
        );

        flush_pending_disposals();
        assert!(cleaned.get(), "flush must dispose the pending owner");

        // Flushing again (and a stale dispose) must be a no-op
        dispose_owner(owner_id);
        flush_pending_disposals();
    }

    /// A cleanup callback that disposes ANOTHER owner while the queue is
    /// being flushed must not be lost.
    #[test]
    fn test_dispose_during_flush_is_processed() {
        let cleaned_b = std::rc::Rc::new(std::cell::Cell::new(false));
        let flag_b = cleaned_b.clone();
        let (_, owner_b) = with_owner(move || {
            on_cleanup(move || flag_b.set(true));
        });
        let (_, owner_a) = with_owner(move || {
            on_cleanup(move || dispose_owner(owner_b));
        });

        dispose_owner(owner_a);
        flush_pending_disposals();
        assert!(
            cleaned_b.get(),
            "an owner disposed during the flush must be handled in the same flush"
        );
    }

    /// A disposed owner's slot is recycled with a bumped generation, so a
    /// stale OwnerId must never resolve to (or dispose) the new occupant.
    #[test]
    fn test_stale_owner_id_cannot_alias_recycled_slot() {
        let (_, first) = with_owner(|| ());
        dispose_owner_now(first);

        // Reuses the freed slot
        let disposed = std::rc::Rc::new(std::cell::Cell::new(false));
        let flag = disposed.clone();
        let (_, second) = with_owner(move || {
            on_cleanup(move || flag.set(true));
        });
        assert_eq!(first.index, second.index, "slot should be recycled");
        assert_ne!(first.generation, second.generation);

        // Disposing via the stale ID must be a no-op
        dispose_owner_now(first);
        assert!(!disposed.get(), "stale OwnerId disposed the new owner");

        dispose_owner_now(second);
        assert!(disposed.get());
    }

    /// Emptying a scope keeps what held its contents: the box and the lists in
    /// it, at the same addresses, so a scope refilled with what it held before
    /// — an effect making a signal on every run — allocates nothing for it.
    #[test]
    fn emptying_a_scope_keeps_what_held_its_contents() {
        use crate::reactive::create_signal;

        let held_at = |id: OwnerId| {
            with_reactive(|reactive| {
                let arena = reactive.owners.borrow();
                let held = arena.get(id)?.held.as_deref()?;
                Some((std::ptr::from_ref(held), held.signals.as_ptr()))
            })
        };

        let ((), scope) = with_owner(|| {
            create_signal(0u32);
        });
        let before = held_at(scope).expect("a scope that made a signal holds it");

        empty_owner(scope);
        assert!(with_reactive(|reactive| {
            let arena = reactive.owners.borrow();
            arena
                .get(scope)
                .unwrap()
                .held
                .as_deref()
                .unwrap()
                .is_empty()
        }));
        under_owner(scope, || create_signal(1u32));

        assert_eq!(held_at(scope), Some(before), "the scope allocated again");
        dispose_owner_now(scope);
    }

    /// What a run declared goes with the rest of what it made: the next run
    /// starts with nothing declared, as it starts with nothing made.
    #[test]
    fn emptying_a_scope_drops_what_it_declared() {
        let ((), scope) = with_owner(|| {
            with_scope_declarations(|declared| {
                declared.push((TypeId::of::<u8>(), Rc::new(7u8)));
            });
        });
        let declared = || under_owner(scope, || nearest_declaration(TypeId::of::<u8>()));
        assert!(declared().is_some(), "the control: the scope declared it");

        empty_owner(scope);
        assert!(declared().is_none(), "emptied, it declares nothing");
        dispose_owner_now(scope);
    }

    /// Disposing a child owner must remove it from the parent's children
    /// list; otherwise long-lived parents grow without bound.
    #[test]
    fn test_dispose_prunes_parent_children_list() {
        let (child_ids, parent_id) = with_owner(|| {
            (0..4)
                .map(|_| with_owner(|| ()).1)
                .collect::<Vec<OwnerId>>()
        });

        let children = || {
            with_reactive(|reactive| {
                let arena = reactive.owners.borrow();
                let parent = arena.get(parent_id).expect("parent still live");
                let mut children = parent
                    .held
                    .as_deref()
                    .expect("it held children")
                    .children
                    .clone();
                children.sort_by_key(|id| id.index);
                children
            })
        };

        // The one disposed goes, and its live siblings stay: a sibling pruned
        // in its place would never be disposed with the parent.
        dispose_owner_now(child_ids[1]);
        assert_eq!(
            children(),
            [child_ids[0], child_ids[2], child_ids[3]],
            "the disposed child, and only it, is pruned"
        );

        for child in &child_ids {
            dispose_owner_now(*child);
        }
        assert!(children().is_empty(), "disposed children not pruned");

        dispose_owner_now(parent_id);
    }

    #[test]
    fn test_current_owner_inside_scope() {
        let ((inner_owner, outer_owner), _outer_id) = with_owner(|| {
            let outer = current_owner();
            let (inner, _inner_id) = with_owner(current_owner);
            (inner, outer)
        });

        // Both should be Some
        assert!(inner_owner.is_some());
        assert!(outer_owner.is_some());

        // They should be different
        assert_ne!(inner_owner, outer_owner);
    }

    #[test]
    fn test_current_owner_outside_scope() {
        // Outside any scope, should be None
        assert!(current_owner().is_none());
    }

    #[test]
    fn test_nested_owners() {
        let cleanup_order = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));

        let order = cleanup_order.clone();
        let (_, outer_id) = with_owner(|| {
            let order_inner = order.clone();
            on_cleanup(move || {
                order_inner.lock().unwrap().push("outer");
            });

            let order_nested = order.clone();
            with_owner(|| {
                on_cleanup(move || {
                    order_nested.lock().unwrap().push("inner");
                });
            });
        });

        // Dispose the outer owner
        dispose_owner_now(outer_id);

        // Children should be disposed first
        let order = cleanup_order.lock().unwrap();
        assert_eq!(*order, vec!["inner", "outer"]);
    }

    #[test]
    fn test_on_cleanup_reverse_order() {
        let cleanup_order = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));

        let order = cleanup_order.clone();
        let (_, owner_id) = with_owner(|| {
            let order1 = order.clone();
            on_cleanup(move || {
                order1.lock().unwrap().push("first");
            });

            let order2 = order.clone();
            on_cleanup(move || {
                order2.lock().unwrap().push("second");
            });

            let order3 = order.clone();
            on_cleanup(move || {
                order3.lock().unwrap().push("third");
            });
        });

        dispose_owner_now(owner_id);

        // Should be reverse order (LIFO)
        let order = cleanup_order.lock().unwrap();
        assert_eq!(*order, vec!["third", "second", "first"]);
    }

    #[test]
    fn test_dispose_owner_twice_is_safe() {
        let (_, owner_id) = with_owner(|| {});

        // Should not panic
        dispose_owner_now(owner_id);
        dispose_owner_now(owner_id);
    }

    #[test]
    fn test_effect_registration_and_reverse_mapping() {
        use super::super::effect::create_effect_id;
        use super::super::signal::create_signal;

        let effect_ran = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
        let effect_ran_clone = effect_ran.clone();

        let (effect_id, owner_id) = with_owner(|| {
            let signal = create_signal(0);
            create_effect_id(move || {
                let _ = signal.get();
                effect_ran_clone.store(true, std::sync::atomic::Ordering::SeqCst);
            })
        });

        // Effect should be owned via reverse mapping
        assert!(
            effect_has_owner(effect_id),
            "Effect should be owned after registration"
        );

        // Dispose the owner
        dispose_owner_now(owner_id);

        // Effect should no longer be owned (removed from reverse mapping)
        assert!(
            !effect_has_owner(effect_id),
            "Effect should not be owned after disposal"
        );
    }

    #[test]
    fn test_signal_registration() {
        use super::super::signal::create_signal;

        let (signal, owner_id) = with_owner(|| create_signal(42));

        // Should be able to read before disposal
        assert_eq!(signal.get(), 42);

        // Dispose the owner
        dispose_owner_now(owner_id);

        // Note: accessing disposed signal should panic, but we don't test that
        // here since it would terminate the test. The storage.rs tests cover
        // the panic messages.
    }

    #[test]
    fn test_multiple_effects_registration() {
        use super::super::effect::create_effect_id;
        use super::super::signal::create_signal;

        let (effect_ids, owner_id) = with_owner(|| {
            let signal = create_signal(0);
            let e1 = create_effect_id(move || {
                let _ = signal.get();
            });
            let e2 = create_effect_id(move || {
                let _ = signal.get();
            });
            let e3 = create_effect_id(move || {
                let _ = signal.get();
            });
            (e1, e2, e3)
        });

        // All effects should be owned
        assert!(effect_has_owner(effect_ids.0));
        assert!(effect_has_owner(effect_ids.1));
        assert!(effect_has_owner(effect_ids.2));

        // Dispose
        dispose_owner_now(owner_id);

        // None should be owned anymore
        assert!(!effect_has_owner(effect_ids.0));
        assert!(!effect_has_owner(effect_ids.1));
        assert!(!effect_has_owner(effect_ids.2));
    }

    #[test]
    fn test_nested_owners_effect_cleanup() {
        use super::super::effect::create_effect_id;
        use super::super::signal::create_signal;

        let ((inner_effect, outer_effect), outer_id) = with_owner(|| {
            let signal = create_signal(0);
            let outer = create_effect_id(move || {
                let _ = signal.get();
            });

            let (inner, _inner_id) = with_owner(|| {
                create_effect_id(move || {
                    let _ = signal.get();
                })
            });

            (inner, outer)
        });

        // Both should be owned
        assert!(effect_has_owner(inner_effect));
        assert!(effect_has_owner(outer_effect));

        // Dispose outer (which should dispose inner first due to depth-first)
        dispose_owner_now(outer_id);

        // Both should be disposed
        assert!(!effect_has_owner(inner_effect));
        assert!(!effect_has_owner(outer_effect));
    }

    /// A scope with one effect counting its runs of `signal`, and one nested
    /// scope with another. Returns the scope and the two counts.
    fn counting_scopes(
        signal: crate::reactive::RwSignal<u32>,
    ) -> (OwnerId, Rc<std::cell::Cell<u32>>, Rc<std::cell::Cell<u32>>) {
        use super::super::effect::create_effect;
        let outer = Rc::new(std::cell::Cell::new(0));
        let inner = Rc::new(std::cell::Cell::new(0));
        let (o, i) = (outer.clone(), inner.clone());
        let (_, id) = with_owner(move || {
            create_effect(move || {
                signal.get();
                o.set(o.get() + 1);
            });
            with_owner(move || {
                create_effect(move || {
                    signal.get();
                    i.set(i.get() + 1);
                })
            });
        });
        (id, outer, inner)
    }

    /// A paused scope's effects, and those of the scopes below it, do not run
    /// on a write; they run once on resume however many writes they missed.
    #[test]
    fn a_paused_scope_runs_what_it_missed_once_on_resume() {
        use super::super::signal::create_signal;
        let signal = create_signal(0u32);
        let (id, outer, inner) = counting_scopes(signal);
        assert_eq!((outer.get(), inner.get()), (1, 1));

        pause_owner(id);
        signal.set(1);
        signal.set(2);
        assert_eq!((outer.get(), inner.get()), (1, 1), "paused, nothing ran");

        resume_owner(id);
        assert_eq!((outer.get(), inner.get()), (2, 2), "each ran once");

        signal.set(3);
        assert_eq!(
            (outer.get(), inner.get()),
            (3, 3),
            "and they are live again"
        );
        dispose_owner_now(id);
    }

    /// Resuming a scope nothing was written to while it was paused runs
    /// nothing.
    #[test]
    fn a_paused_scope_that_missed_nothing_runs_nothing_on_resume() {
        use super::super::signal::create_signal;
        let signal = create_signal(0u32);
        let (id, outer, inner) = counting_scopes(signal);
        pause_owner(id);
        resume_owner(id);
        assert_eq!((outer.get(), inner.get()), (1, 1));
        dispose_owner_now(id);
    }

    /// A paused scope disposed without resuming takes its effects with it:
    /// what they missed is never run, and a later write runs nothing.
    #[test]
    fn a_paused_scope_disposed_runs_nothing() {
        use super::super::signal::create_signal;
        let signal = create_signal(0u32);
        let (id, outer, inner) = counting_scopes(signal);
        pause_owner(id);
        signal.set(1);
        dispose_owner_now(id);
        resume_owner(id);
        signal.set(2);
        assert_eq!((outer.get(), inner.get()), (1, 1));
    }

    /// A scope opened, or an effect made, under a paused scope is paused with
    /// it: it waits for the resume rather than running on its own.
    #[test]
    fn what_is_made_under_a_paused_scope_waits_for_the_resume() {
        use super::super::effect::create_effect;
        use super::super::signal::create_signal;
        let signal = create_signal(0u32);
        let (_, id) = with_owner(|| ());
        pause_owner(id);
        let runs = Rc::new(std::cell::Cell::new(0));
        let counted = runs.clone();
        under_owner(id, || {
            with_owner(move || {
                create_effect(move || {
                    signal.get();
                    counted.set(counted.get() + 1);
                })
            })
        });
        signal.set(1);
        assert_eq!(runs.get(), 0, "not even its first run");

        resume_owner(id);
        assert_eq!(runs.get(), 1, "the first run, on resume");
        signal.set(2);
        assert_eq!(runs.get(), 2);
        dispose_owner_now(id);
    }

    /// Pausing reaches down, not up or across: a sibling scope and the parent
    /// go on running.
    #[test]
    fn pausing_a_scope_leaves_its_parent_and_siblings_running() {
        use super::super::effect::create_effect;
        use super::super::signal::create_signal;
        let signal = create_signal(0u32);
        let runs = Rc::new(std::cell::Cell::new(0));
        let counted = runs.clone();
        let ((paused, sibling_runs), parent) = with_owner(move || {
            create_effect(move || {
                signal.get();
                counted.set(counted.get() + 1);
            });
            let (paused, ..) = counting_scopes(signal);
            let (_, sibling_runs, _) = counting_scopes(signal);
            (paused, sibling_runs)
        });
        pause_owner(paused);
        signal.set(1);
        assert_eq!(runs.get(), 2, "the parent still runs");
        assert_eq!(sibling_runs.get(), 2, "and so does its sibling");
        dispose_owner_now(parent);
    }

    /// The niche is the whole point of the `NonZeroU32`. `Option<OwnerId>` is
    /// what `Owner::parent` and every derived closure's captured scope are made
    /// of; twelve bytes there was four spent on a tag the generation can carry
    /// itself, on a structure allocated per surface, per popup and per row.
    #[test]
    fn an_optional_owner_id_costs_no_more_than_an_owner_id() {
        assert_eq!(size_of::<OwnerId>(), 8);
        assert_eq!(size_of::<Option<OwnerId>>(), size_of::<OwnerId>());
    }

    #[test]
    fn test_root_owner_and_reset() {
        use super::super::signal::create_signal;

        // Simulate App lifecycle: create root owner → create signals → dispose → reset
        let root_id = create_root_owner();
        assert!(current_owner().is_some());

        let signal = create_signal(42);
        assert_eq!(signal.get(), 42);

        // Dispose root owner — cascades signal disposal
        dispose_owner_now(root_id);

        // Signal should be disposed (reading would panic)
        let panicked = std::panic::catch_unwind(|| signal.get()).is_err();
        assert!(panicked, "Accessing disposed signal should panic");

        // Reset owner arena
        crate::reactive::state::reset();
        assert!(current_owner().is_none());

        // After reset, creating a new root owner should work cleanly
        let new_root = create_root_owner();
        assert!(current_owner().is_some());
        let signal2 = create_signal(99);
        assert_eq!(signal2.get(), 99);

        // Cleanup
        dispose_owner_now(new_root);
        crate::reactive::state::reset();
    }
}