whisker-runtime 0.19.2

Host-independent Whisker runtime: reactivity, retained elements, layout, and frames.
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
//! Owner / scope API surface.
//!
//! [`Owner`] is the public-facing handle for a reactive scope —
//! the lifetime unit that ties together signals, effects, computed
//! values, view element handles, and cleanup callbacks. Disposing
//! an `Owner` cascades into its children, frees every node it
//! allocated, releases the element handles it owned, and runs its
//! cleanup callbacks in LIFO order.
//!
//! ## When to reach for these methods
//!
//! - Application code: **almost never**. `#[component]`,
//!   `provide_context`, `on_cleanup` etc. set up and tear down
//!   owners for you automatically.
//! - Framework extension code (custom control-flow primitives, a
//!   router, a custom list virtualizer): when you need to mount
//!   sub-trees whose lifetime is shorter than the surrounding
//!   component — that's where `Owner::new` / `owner.with` /
//!   `owner.dispose` come in.
//! - Tests: hand-driving owner lifecycle is convenient for
//!   reactive unit tests.
//!
//! See the crate-level docs for the conceptual model.
//!
//! The underlying [`Owner`] type is a `Copy` slotmap key
//! defined in [`super::runtime`]; the methods on this page are
//! attached to that type via an `impl` block.

use std::rc::Rc;

use super::error::invariant;
use super::runtime::{NodeId, Owner, Scope};
use super::with_runtime;

impl Owner {
    /// Create a new owner. If `parent` is `None` the current
    /// top-of-stack owner is used (or the owner becomes a root if
    /// the stack is empty).
    ///
    /// The new owner inherits its parent's `paused` flag — so a
    /// sub-component mounted while its containing route is
    /// suspended starts paused, and its effects won't fire until
    /// the route resumes.
    pub fn new(parent: Option<Owner>) -> Owner {
        with_runtime(|rt| {
            invariant!(
                !rt.shutting_down,
                "cannot create an owner during runtime shutdown"
            );
            let parent = parent.or_else(|| rt.current_owner());
            invariant!(
                parent
                    .is_none_or(|parent| rt.owners.get(parent).is_some_and(|owner| !owner.closing)),
                "cannot create a child of a disposed owner"
            );
            let parent_paused = parent
                .and_then(|p| rt.owners.get(p))
                .map(|o| o.paused)
                .unwrap_or(false);
            let mut scope = Scope::new(parent);
            scope.paused = parent_paused;
            let id = rt.owners.insert(scope);
            if let Some(p) = parent
                && let Some(parent_scope) = rt.owners.get_mut(p)
            {
                parent_scope.children.push(id);
            }
            id
        })
    }

    /// Creates a parentless owner whose Copy handle does not dispose it on drop.
    /// Call `dispose` explicitly; use [`crate::runtime_local!`] for Runtime-owned caches.
    pub fn detached_root() -> Owner {
        with_runtime(|rt| {
            invariant!(
                !rt.shutting_down,
                "cannot create an owner during runtime shutdown"
            );
            rt.owners.insert(Scope::new(None))
        })
    }

    /// Push `self` as the current scope, run `f`, pop back.
    /// Reactive primitives (`signal()`, `effect()`, `computed()`,
    /// view elements created via `render!`) allocated inside `f`
    /// will belong to this owner.
    pub fn with<R>(self, f: impl FnOnce() -> R) -> R {
        with_runtime(|rt| rt.owner_stack.push(self));
        struct Restore(Owner);
        impl Drop for Restore {
            fn drop(&mut self) {
                with_runtime(|rt| {
                    let popped = rt.owner_stack.pop();
                    debug_assert_eq!(popped, Some(self.0));
                });
            }
        }
        let _restore = Restore(self);
        f()
    }

    pub(crate) fn service() -> Self {
        if let Some(owner) = with_runtime(|rt| rt.service_owner) {
            return owner;
        }
        let owner = Self::detached_root();
        with_runtime(|rt| rt.service_owner = Some(owner));
        owner
    }

    /// Whether this owner still accepts new work.
    #[doc(hidden)]
    pub fn is_alive(self) -> bool {
        with_runtime(|rt| rt.owners.get(self).is_some_and(|scope| !scope.closing))
    }

    /// Dispose `self`, freeing all its descendants, nodes, and
    /// running its cleanup callbacks.
    ///
    /// Recursive — disposes children first, then this owner. Safe
    /// to call even if the owner has already been disposed (no-op).
    pub fn dispose(self) {
        let drain = with_runtime(|rt| {
            if rt.owners.get(self).is_none_or(|scope| scope.closing) {
                return false;
            }
            let mut pending = vec![self];
            while let Some(owner) = pending.pop() {
                if let Some(scope) = rt.owners.get_mut(owner) {
                    scope.closing = true;
                    pending.extend(scope.children.iter().copied());
                }
            }
            rt.disposing.push(self);
            rt.execution_depth == 0
        });
        if drain {
            Self::drain_disposals();
        }
    }

    pub(crate) fn drain_disposals() {
        loop {
            let owners = with_runtime(|rt| std::mem::take(&mut rt.disposing));
            if owners.is_empty() {
                break;
            }
            for owner in owners {
                let report_to = with_runtime(|rt| rt.owners.get(owner).and_then(|o| o.parent));
                owner.dispose_now(report_to);
            }
        }
    }

    /// `report_to` is the live owner above the disposed subtree; the
    /// subtree's own scopes are removed before their cleanups run.
    fn dispose_now(self, report_to: Option<Owner>) {
        // Everything is pulled out under a short borrow rather than
        // held across the recursion — deeper levels re-enter the
        // runtime.
        let children;
        let nodes;
        let cleanups;
        let parent;
        let mount_fn;
        let elements;
        let registrations;
        {
            let removed = with_runtime(|rt| rt.owners.remove(self));
            let Some(o) = removed else { return };
            children = o.children;
            nodes = o.nodes;
            cleanups = o.cleanups;
            parent = o.parent;
            mount_fn = o.mount_fn;
            elements = o.elements;
            registrations = o.registrations;
        }

        // A component owner must leave the hot-reload registry, or
        // `owners_for_fn` hands remount logic a dangling Owner.
        if let Some(fp) = mount_fn {
            with_runtime(|rt| {
                if let Some(list) = rt.component_owners.get_mut(&fp) {
                    list.retain(|o| *o != self);
                    if list.is_empty() {
                        rt.component_owners.remove(&fp);
                    }
                }
            });

            // Likewise its remountable MountSites: an orphan site
            // survives cascading disposal and the next
            // `remount_components_for` then operates on freed parent /
            // body_root handles.
            //
            // `site.owner` is `None` *during* a remount (the
            // take-then-reinstall window in `remount_one`), so this
            // scan can't evict a site that is mid-flight.
            let stale = with_runtime(|rt| {
                let stale: Vec<super::component::MountId> = rt
                    .mount_sites
                    .iter()
                    .filter_map(|(id, site)| {
                        if site.owner == Some(self) {
                            Some(*id)
                        } else {
                            None
                        }
                    })
                    .collect();
                for id in &stale {
                    rt.mount_sites.remove(id);
                    if let Some(list) = rt.fn_ptr_mounts.get_mut(&fp) {
                        list.retain(|m| m != id);
                        if list.is_empty() {
                            rt.fn_ptr_mounts.remove(&fp);
                        }
                    }
                }
                stale
            });
            // Element ids are reused, so a pending entry must not outlive its site.
            super::component::forget_pending_mounts(&stale);
        }

        if let Some(p) = parent {
            with_runtime(|rt| {
                if let Some(parent_scope) = rt.owners.get_mut(p) {
                    parent_scope.children.retain(|&c| c != self);
                }
            });
        }

        for child in children {
            child.dispose_now(report_to);
        }

        // Cleanups run before this owner's nodes are freed, so an
        // `on_cleanup` can still read and write the signals it closed
        // over (what Solid / Leptos / React all allow). Children are
        // already disposed above, so a *child's* signal still reads as
        // gone. LIFO, and with no runtime borrow held — a cleanup may
        // re-enter the runtime.
        for (_, cancel) in registrations {
            cancel();
        }

        // Caught one by one so a failing cleanup neither skips the rest
        // nor, during an unwind's `drain_disposals`, double-panics.
        for cleanup in cleanups.into_iter().rev() {
            super::error::catch(report_to, super::error::ErrorPhase::Cleanup, cleanup);
        }

        // Freeing a node also detaches it from every subscriber list
        // it was on, so no live node notifies a freed slot later.
        // Arc-signal back-refs are collected here and unsubscribed
        // below, outside the borrow — those callees re-enter the
        // runtime.
        let mut removed_nodes = Vec::new();
        let arc_unsubscribes: Vec<(Rc<dyn super::runtime::ArcSubscription>, NodeId)> =
            with_runtime(|rt| {
                let mut out: Vec<(Rc<dyn super::runtime::ArcSubscription>, NodeId)> = Vec::new();
                for node_id in &nodes {
                    let Some(mut node) = rt.nodes.remove(*node_id) else {
                        continue;
                    };
                    for source in std::mem::take(&mut node.sources) {
                        if let Some(src_node) = rt.nodes.get_mut(source) {
                            src_node.subscribers.remove(node_id);
                        }
                    }
                    // A signal this owner held may have been read by an
                    // outer effect, so clear the reverse edge too.
                    for sub in std::mem::take(&mut node.subscribers) {
                        if let Some(sub_node) = rt.nodes.get_mut(sub) {
                            sub_node.sources.remove(node_id);
                        }
                    }
                    for arc_src in std::mem::take(&mut node.arc_sources) {
                        out.push((arc_src, *node_id));
                    }
                    removed_nodes.push(node);
                }
                // A scheduled node left in these queues would be re-run
                // from its freed slot on the next flush / resume.
                rt.pending.retain(|n| !nodes.contains(n));
                rt.deferred.retain(|n| !nodes.contains(n));
                out
            });

        // An Arc-backed signal outlives its subscribers, so pruning
        // here is what keeps its list from accumulating dead
        // `NodeId`s across transient subscribers.
        drop(removed_nodes);
        for (arc_src, subscriber) in arc_unsubscribes {
            arc_src.unsubscribe(subscriber);
        }

        // Element release comes after the child recursion so the
        // renderer sees children released before their parents, and
        // runs with no runtime borrow held so a renderer may call back
        // into the reactive system.
        for handle in elements {
            crate::view::release_element(handle);
        }
    }

    /// Pause `self` (and its descendants): effects and computeds
    /// whose scope is the paused subtree skip flush. Their
    /// scheduled re-runs land on the runtime's `deferred` list
    /// until [`Owner::resume`] drains them back.
    ///
    /// Idempotent — pausing an already-paused owner is a no-op.
    /// The cascade walks the children tree breadth-first; new
    /// descendants created while paused inherit the flag via
    /// [`Owner::new`].
    ///
    /// Used by `StackLayout` to freeze back-stack entries that are
    /// mounted-but-off-screen, matching iOS
    /// `UINavigationController` / Android Fragment back-stack
    /// semantics: state survives but no CPU is spent on
    /// signal-driven re-renders behind the top route.
    pub fn pause(self) {
        with_runtime(|rt| {
            let mut stack = vec![self];
            while let Some(id) = stack.pop() {
                let Some(o) = rt.owners.get_mut(id) else {
                    continue;
                };
                if o.paused {
                    continue;
                }
                o.paused = true;
                stack.extend(o.children.iter().copied());
            }
        });
    }

    /// Resume `self` (and its descendants): clear the paused flag
    /// and move any of its deferred effects back onto the pending
    /// queue so they fire on the next flush.
    ///
    /// Idempotent. Iterates [`super::runtime::ReactiveRuntime::deferred`]
    /// and re-queues every node whose owner is no longer paused —
    /// including descendants resumed by this cascade, and any
    /// deferred node whose owner happens to have been unpaused by
    /// an earlier call.
    pub fn resume(self) {
        let any_resumed = with_runtime(|rt| {
            let mut stack = vec![self];
            let mut any = false;
            while let Some(id) = stack.pop() {
                let Some(o) = rt.owners.get_mut(id) else {
                    continue;
                };
                if !o.paused {
                    continue;
                }
                o.paused = false;
                any = true;
                stack.extend(o.children.iter().copied());
            }
            if !any {
                return false;
            }
            // Nodes disposed while their owner was paused are still
            // listed here; they get dropped rather than re-queued.
            let deferred = std::mem::take(&mut rt.deferred);
            for node in deferred {
                let still_paused = rt
                    .nodes
                    .get(node)
                    .and_then(|n| rt.owners.get(n.owner))
                    .map(|o| o.paused);
                match still_paused {
                    Some(false) => {
                        if !rt.pending.contains(&node) {
                            rt.pending.push(node);
                        }
                    }
                    Some(true) => rt.deferred.push(node),
                    None => {} // node or owner is gone; drop silently
                }
            }
            true
        });
        if any_resumed {
            crate::runtime_wake::wake_runtime();
        }
    }

    /// Whether `self` is currently paused. Mainly for tests;
    /// production code should drive pause / resume from the
    /// lifecycle layer and not branch on the flag directly.
    pub fn is_paused(self) -> bool {
        with_runtime(|rt| rt.owners.get(self).map(|o| o.paused).unwrap_or(false))
    }

    /// The owner currently at the top of the scope stack, if any —
    /// the scope that new signals, effects, and cleanups would
    /// register against. Lets registries capture the scope of the
    /// code that called them (see `whisker-driver`'s `back` module).
    pub fn current() -> Option<Owner> {
        with_runtime(|rt| rt.current_owner())
    }
}

/// Register a callback to run when the current owner is disposed.
/// Calls accumulate in LIFO order, mirroring Solid / Leptos
/// `onCleanup` semantics.
///
/// No-op (with a warning in `debug`) if there is no current owner.
///
/// Kept as a free function (not a method on [`Owner`]) because it
/// operates on whatever owner happens to be at the top of the
/// runtime's owner stack — the caller can't sensibly name it.
pub fn on_cleanup(f: impl FnOnce() + 'static) {
    let registered = with_runtime(|rt| {
        let Some(owner_id) = rt.current_owner() else {
            return false;
        };
        if let Some(scope) = rt.owners.get_mut(owner_id) {
            scope.cleanups.push(Box::new(f));
            return true;
        }
        false
    });
    if !registered {
        debug_assert!(
            false,
            "on_cleanup called outside any owner — registration ignored"
        );
    }
}