Skip to main content

nsh_core/element/
reactive.rs

1//! Signals for Rust components: the reactive graph of
2//! [`crate::reactive`] with Rust values and closures, as TSX has it
3//! (`signal`, `computed`, `effect`, `batch`, `untracked`, `cleanup`, context).
4//!
5//! Handles ([`Signal`], [`Memo`], [`ReadSignal`]) are `Copy` indices into
6//! the graph, so closures and async blocks capture them as they are. What is
7//! made under an owner (a component, an effect, a branch of `when`, a row of
8//! `each`) is disposed with it; a handle of a disposed node reads as gone
9//! ([`Signal::try_get`]) and panics when read as live. The UI's other
10//! handles (animated values, element refs) are kept the same way
11//! (`Kept`), but find their value gone rather than panic.
12//!
13//! The graph is the engine's: the core enters it ([`Runtime::enter`]) while
14//! Rust code of the components runs on the engine thread, and the functions
15//! here act on the graph entered.
16
17use std::{
18    any::{Any, TypeId},
19    cell::{Cell, RefCell, UnsafeCell},
20    fmt,
21    marker::PhantomData,
22    mem::ManuallyDrop,
23    panic::AssertUnwindSafe,
24    rc::Rc,
25};
26
27use crate::reactive::{self as r, DISPOSED, Equals, Kind, NONE, UNOWNED};
28
29/// A value in the graph (`None`: none yet, an effect's).
30type Value = Option<Rc<dyn Any>>;
31type Func = Rc<dyn Compute>;
32type Compare = fn(&dyn Any, &dyn Any) -> bool;
33
34/// A computation of the graph. One method rather than `dyn Fn`, whose
35/// vtables, one per closure, also hold `FnMut` / `FnOnce` shims.
36pub(crate) trait Compute {
37    fn run(&self, prev: Value) -> Value;
38}
39
40impl<F: Fn(Value) -> Value> Compute for F {
41    fn run(&self, prev: Value) -> Value {
42        self(prev)
43    }
44}
45
46/// The graph's host for Rust: values are `Rc<dyn Any>`, computations
47/// closures.
48#[derive(Clone, Copy)]
49pub(crate) struct Rust;
50
51/// What the Rust host keeps in the graph.
52#[derive(Default)]
53pub(crate) struct RustData {
54    /// Panics of computations, with the owner they ran under, for the core
55    /// to report ([`Runtime::take_failures`]).
56    failures: Vec<(u32, String)>,
57    runaway: bool,
58    /// Events components that run once emitted, for the core.
59    emits: Vec<super::once::Emitted>,
60    /// What components read of the core (the free functions of [`super`]).
61    pub(crate) ambient: super::Ambient,
62    /// The APIs views registered, by host ([`super::Scope::methods`]).
63    apis: rustc_hash::FxHashMap<crate::NodeId, ApiEntry>,
64    /// The error boundaries ([`super::catch_error`]): what fails under the
65    /// owner sets its signal.
66    boundaries: rustc_hash::FxHashMap<Owner, Signal<Option<super::ComponentError>>>,
67}
68
69/// Makes the current owner an error boundary: what fails under it sets
70/// `failed`, for as long as it lives.
71pub(crate) fn register_boundary(failed: Signal<Option<super::ComponentError>>) {
72    let owner = Owner::current();
73    with_data(|d| d.boundaries.insert(owner, failed));
74    cleanup(move || {
75        with_data(|d| d.boundaries.remove(&owner));
76    });
77}
78
79/// The nearest error boundary at or above `owner`.
80pub(crate) fn boundary_of(owner: Owner) -> Option<Signal<Option<super::ComponentError>>> {
81    let mut at = Some(owner);
82    while let Some(owner) = at.filter(Owner::is_live) {
83        if let Some(signal) = with_data(|d| d.boundaries.get(&owner).copied()) {
84            return Some(signal);
85        }
86        at = owner.parent();
87    }
88    None
89}
90
91/// A registered [`super::Api`], its type erased (a method's call, made
92/// in the JS call, downcasts it).
93#[derive(Clone)]
94struct ApiEntry {
95    api: Rc<dyn Any>,
96}
97
98/// Registers `api` as the ref of the component on `host` for as long as the
99/// current owner lives.
100pub(crate) fn register_api<A: super::Api>(host: crate::NodeId, api: A) {
101    let entry = ApiEntry { api: Rc::new(api) };
102    with_data(|d| d.apis.insert(host, entry));
103    cleanup(move || {
104        with_data(|d| d.apis.remove(&host));
105    });
106}
107
108/// The API of type `A` the component on `host` registered.
109pub(crate) fn api_of<A: super::Api>(host: crate::NodeId) -> Option<Rc<A>> {
110    let entry = with_data(|d| d.apis.get(&host).cloned())?;
111    entry.api.downcast::<A>().ok()
112}
113
114/// Calls `call` (a method its arguments were decoded for) with the API of
115/// the component on `host`; `None` without one, or with one of another
116/// type.
117pub(crate) fn call_api(host: crate::NodeId, call: super::MethodCall) -> Option<super::JsResult> {
118    // Out of the data first: the method writes signals.
119    let entry = with_data(|d| d.apis.get(&host).cloned())?;
120    call(&*entry.api)
121}
122
123/// Runs `f` on the entered runtime's data.
124pub(crate) fn with_data<R>(f: impl FnOnce(&mut RustData) -> R) -> R {
125    f(&mut graph().data)
126}
127
128/// [`with_data`] where a graph is entered (the engine's thread, while it
129/// runs Rust code), else `None`.
130pub(crate) fn try_with_data<R>(f: impl FnOnce(&mut RustData) -> R) -> Option<R> {
131    let graph = CURRENT.with(Cell::get);
132    // SAFETY: an entered graph lives until its guard drops; the borrow
133    // ends with `f`.
134    (!graph.is_null()).then(|| f(unsafe { &mut (*graph).data }))
135}
136
137/// Queues `event` of the component on `host` for the core.
138pub(crate) fn emit(host: crate::NodeId, event: Box<dyn super::builder::AnyEvent>) {
139    graph().data.emits.push((host, event));
140}
141
142thread_local! {
143    /// The graph entered on this thread ([`Runtime::enter`]).
144    #[allow(
145        clippy::missing_const_for_thread_local,
146        reason = "it is const; clippy misreads Android's expansion"
147    )]
148    static CURRENT: Cell<*mut r::Graph<Rust>> = const { Cell::new(std::ptr::null_mut()) };
149}
150
151// SAFETY: the graph is the one entered on this thread; the graph's
152// functions and the handles here take only short borrows of it.
153unsafe impl r::Host for Rust {
154    type Value = Value;
155    type Func = Func;
156    type Equals = Compare;
157    type Cleanup = Box<dyn FnOnce()>;
158    type Context = (TypeId, Rc<dyn Any>);
159    type Data = RustData;
160
161    #[inline]
162    unsafe fn graph<'a>(self) -> &'a mut r::Graph<Rust> {
163        let graph = CURRENT.with(Cell::get);
164        assert!(
165            !graph.is_null(),
166            "no reactive runtime: signals are used on the engine thread, while components run"
167        );
168        // SAFETY: an entered graph lives until its guard drops.
169        unsafe { &mut *graph }
170    }
171
172    #[inline]
173    fn empty() -> Value {
174        None
175    }
176
177    #[inline]
178    fn dup(self, v: &Value) -> Value {
179        v.clone()
180    }
181
182    #[inline]
183    fn free(self, v: Value) {
184        drop(v);
185    }
186
187    #[inline]
188    fn dup_func(self, f: &Func) -> Func {
189        f.clone()
190    }
191
192    #[inline]
193    fn free_func(self, f: Func) {
194        drop(f);
195    }
196
197    fn dup_equals(self, e: &Compare) -> Compare {
198        *e
199    }
200
201    fn free_equals(self, _: Compare) {}
202
203    fn call(self, f: &Func, prev: Value) -> Option<Value> {
204        match std::panic::catch_unwind(AssertUnwindSafe(|| f.run(prev))) {
205            Ok(value) => Some(value),
206            Err(panic) => {
207                let message = super::component::panic_message(panic);
208                // SAFETY: a short borrow.
209                let graph = unsafe { self.graph() };
210                let owner = graph.owner();
211                graph.data.failures.push((owner, message));
212                None
213            }
214        }
215    }
216
217    #[inline]
218    fn same(self, a: &Value, b: &Value) -> bool {
219        match (a, b) {
220            (Some(a), Some(b)) => Rc::ptr_eq(a, b),
221            (None, None) => true,
222            _ => false,
223        }
224    }
225
226    fn truthy(self, v: &Value) -> bool {
227        v.as_ref()
228            .and_then(|v| v.downcast_ref::<bool>())
229            .copied()
230            .unwrap_or(v.is_some())
231    }
232
233    fn custom_changed(self, e: &Compare, prev: Value, next: &Value) -> bool {
234        match (&prev, next) {
235            (Some(a), Some(b)) => !e(&**a, &**b),
236            (None, None) => false,
237            _ => true,
238        }
239    }
240
241    fn run_cleanup(self, f: Box<dyn FnOnce()>) {
242        if let Err(panic) = std::panic::catch_unwind(AssertUnwindSafe(f)) {
243            let message = super::component::panic_message(panic);
244            // SAFETY: a short borrow.
245            let graph = unsafe { self.graph() };
246            let owner = graph.owner();
247            graph.data.failures.push((owner, message));
248        }
249    }
250
251    fn free_cleanup(self, f: Box<dyn FnOnce()>) {
252        drop(f);
253    }
254
255    fn runaway(self) {
256        // SAFETY: a short borrow.
257        let graph = unsafe { self.graph() };
258        graph.data.runaway = true;
259        log::error!(target: "js", "potential infinite loop: an effect keeps changing what it reads");
260    }
261}
262
263fn graph<'a>() -> &'a mut r::Graph<Rust> {
264    // SAFETY: every borrow here is short and ends before the next call
265    // into the graph's functions.
266    unsafe { r::Host::graph(Rust) }
267}
268
269/// The reactive graph of an engine's Rust components.
270pub struct Runtime {
271    graph: Box<UnsafeCell<r::Graph<Rust>>>,
272}
273
274impl Default for Runtime {
275    fn default() -> Self {
276        // One runtime per engine: its id is the engine's.
277        let mut data = RustData::default();
278        data.ambient.engine_id = Some(super::EngineId::next());
279        Self {
280            graph: Box::new(UnsafeCell::new(r::Graph::new(data))),
281        }
282    }
283}
284
285impl fmt::Debug for Runtime {
286    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
287        f.write_str("Runtime")
288    }
289}
290
291/// While it lives, the graph it entered is the thread's
292/// ([`Runtime::enter`]).
293#[must_use = "the runtime is entered while the guard lives"]
294pub struct Entered {
295    previous: *mut r::Graph<Rust>,
296}
297
298impl Drop for Entered {
299    fn drop(&mut self) {
300        CURRENT.with(|c| c.set(self.previous));
301    }
302}
303
304impl Runtime {
305    /// Makes this runtime the thread's until the guard drops (entries nest).
306    pub fn enter(&self) -> Entered {
307        let previous = CURRENT.with(|c| c.replace(self.graph.get()));
308        Entered { previous }
309    }
310
311    /// The panics of computations since the last call, with the owner each
312    /// ran under.
313    pub(crate) fn take_failures(&self) -> Vec<(Owner, String)> {
314        let _entered = self.enter();
315        let graph = graph();
316        std::mem::take(&mut graph.data.failures)
317            .into_iter()
318            .map(|(id, message)| (Owner::of(graph, id), message))
319            .collect()
320    }
321
322    /// The events components emitted since the last call.
323    pub(crate) fn take_emits(&self) -> Vec<super::once::Emitted> {
324        let _entered = self.enter();
325        std::mem::take(&mut graph().data.emits)
326    }
327
328    /// The graph's slots in use.
329    #[cfg(test)]
330    pub(crate) fn slots_in_use(&self) -> usize {
331        let _entered = self.enter();
332        graph().slots().0
333    }
334
335    /// Frees what the graph holds (at teardown; no component code runs).
336    pub(crate) fn free_all(&self) {
337        let _entered = self.enter();
338        graph().free_all(Rust);
339    }
340}
341
342impl Drop for Runtime {
343    fn drop(&mut self) {
344        // Cleanups and values may hold handles: release them inside the
345        // runtime, before it goes.
346        self.free_all();
347    }
348}
349
350/// A handle of a node: its index and generation.
351#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
352struct Handle {
353    id: u32,
354    generation: u32,
355}
356
357impl Handle {
358    fn of(graph: &r::Graph<Rust>, id: u32) -> Self {
359        Self {
360            id,
361            generation: graph.generation(id),
362        }
363    }
364
365    fn live(self) -> bool {
366        graph().live(self.id, self.generation, u32::MAX)
367    }
368
369    /// The node, or a panic naming where the handle was made.
370    #[track_caller]
371    fn expect(self, what: &str) -> u32 {
372        assert!(
373            self.live(),
374            "{what} read or written after its owner was disposed"
375        );
376        self.id
377    }
378}
379
380/// A node of the graph, whatever it is (a signal, a memo), by handle.
381#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
382pub(crate) struct Node(Handle);
383
384impl Node {
385    /// Whether its owner is still live (it was not disposed).
386    pub(crate) fn is_live(self) -> bool {
387        self.0.live()
388    }
389
390    /// `f` of its value, subscribing the running computation (`what` names
391    /// it if it is gone).
392    #[track_caller]
393    pub(crate) fn with<T: 'static, R>(self, what: &str, f: impl FnOnce(&T) -> R) -> R {
394        read_value(self.0.expect(what), true, f)
395    }
396
397    /// `f` of its value, subscribing nothing (`what` names it if it is
398    /// gone).
399    #[track_caller]
400    pub(crate) fn with_untracked<T: 'static, R>(self, what: &str, f: impl FnOnce(&T) -> R) -> R {
401        read_value(self.0.expect(what), false, f)
402    }
403
404    /// Whether it is a memo that runs again before its value is current
405    /// (what it reads changed). False once it is gone.
406    pub(crate) fn is_outdated(self) -> bool {
407        self.0.live() && graph().outdated(self.0.id)
408    }
409
410    /// Brings the memo it names up to date now, subscribing nothing: what
411    /// its run writes is written before the caller reads it. Nothing when
412    /// it is current or gone.
413    pub(crate) fn bring_up_to_date(self) {
414        if self.is_outdated() {
415            untracked(|| drop(r::read(Rust, self.0.id)));
416        }
417    }
418
419    /// Writes `value` to it (a signal's node): what read it runs again,
420    /// unless the signal finds it equal.
421    #[track_caller]
422    pub(crate) fn set<T: 'static>(self, value: T) {
423        r::write(Rust, self.0.expect("a prop"), Some(Rc::new(value)));
424    }
425}
426
427fn read_value<T: 'static, R>(id: u32, tracked: bool, f: impl FnOnce(&T) -> R) -> R {
428    let value = read_any(id, tracked, TypeId::of::<T>());
429    // SAFETY: `read_any` checked that the value is a `T`; `value` keeps it
430    // alive while `f` borrows it.
431    f(unsafe { &*value.as_ptr().cast::<T>() })
432}
433
434/// Node `id`'s value, checked to be of type `ty`. The non-generic part of
435/// every read, out of line: hundreds of types and closures read signals.
436#[cfg_attr(target_arch = "wasm32", inline(never))]
437fn read_any(id: u32, tracked: bool, ty: TypeId) -> ReadValue {
438    let value = if tracked {
439        r::read(Rust, id)
440    } else {
441        graph().value(id).clone()
442    };
443    let value = value.expect("a signal always holds a value");
444    assert!(
445        (*value).type_id() == ty,
446        "a handle reads the type it was made with"
447    );
448    ReadValue(ManuallyDrop::new(value))
449}
450
451/// A value read out of the graph ([`read_any`]), released out of line.
452struct ReadValue(ManuallyDrop<Rc<dyn Any>>);
453
454impl ReadValue {
455    fn as_ptr(&self) -> *const dyn Any {
456        Rc::as_ptr(&self.0)
457    }
458}
459
460impl Drop for ReadValue {
461    #[cfg_attr(target_arch = "wasm32", inline(never))]
462    fn drop(&mut self) {
463        // SAFETY: dropped once, here.
464        unsafe { ManuallyDrop::drop(&mut self.0) }
465    }
466}
467
468fn compare<T: PartialEq + 'static>(a: &dyn Any, b: &dyn Any) -> bool {
469    match both_of(a, b, TypeId::of::<T>()) {
470        // SAFETY: `both_of` checked that both are `T`s.
471        Ok((a, b)) => unsafe { *a.cast::<T>() == *b.cast::<T>() },
472        Err(equal) => equal,
473    }
474}
475
476/// The data of `a` and `b` when both are of type `ty`; else whether they
477/// count as equal, as two downcasts compared would (both of another type).
478#[cfg_attr(target_arch = "wasm32", inline(never))]
479fn both_of(a: &dyn Any, b: &dyn Any, ty: TypeId) -> Result<(*const (), *const ()), bool> {
480    match (a.type_id() == ty, b.type_id() == ty) {
481        (true, true) => Ok((
482            (a as *const dyn Any).cast::<()>(),
483            (b as *const dyn Any).cast::<()>(),
484        )),
485        (a, b) => Err(a == b),
486    }
487}
488
489/// How a signal decides that a write changed it.
490#[derive(Debug, Clone, Copy, PartialEq, Eq)]
491pub enum SignalEquals {
492    /// Every write notifies (types without `PartialEq`, or values that
493    /// change in place).
494    Never,
495}
496
497/// A value that is read in bindings and written from anywhere: reading it
498/// in a computation subscribes the computation (TS: `signal(value)`).
499pub struct Signal<T> {
500    handle: Handle,
501    _t: PhantomData<fn() -> T>,
502}
503
504impl<T> Clone for Signal<T> {
505    fn clone(&self) -> Self {
506        *self
507    }
508}
509
510impl<T> Copy for Signal<T> {}
511
512impl<T> PartialEq for Signal<T> {
513    fn eq(&self, other: &Self) -> bool {
514        self.handle == other.handle
515    }
516}
517
518impl<T> fmt::Debug for Signal<T> {
519    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
520        write!(f, "Signal({})", self.handle.id)
521    }
522}
523
524/// A new signal holding `value`, owned by the current owner. A write of an
525/// equal value notifies no one (TS: `===`).
526pub fn signal<T: PartialEq + 'static>(value: T) -> Signal<T> {
527    make_signal(value, Equals::Custom(compare::<T>))
528}
529
530/// A new signal holding `value` whose every write notifies.
531pub fn signal_with<T: 'static>(value: T, equals: SignalEquals) -> Signal<T> {
532    match equals {
533        SignalEquals::Never => make_signal(value, Equals::Never),
534    }
535}
536
537/// A value of the current owner that is not reactive ([`stored`]): a
538/// `Copy` handle to state closures share but nothing displays (a running
539/// task, a cache). It goes with the owner.
540pub struct Stored<T: 'static>(Signal<Rc<RefCell<T>>>);
541
542impl<T> Clone for Stored<T> {
543    fn clone(&self) -> Self {
544        *self
545    }
546}
547
548impl<T> Copy for Stored<T> {}
549
550impl<T: 'static> Stored<T> {
551    /// `f` of the value, which it may change (`f` must not reach this
552    /// value again).
553    #[track_caller]
554    pub fn with<R>(&self, f: impl FnOnce(&mut T) -> R) -> R {
555        self.0.with_untracked(|cell| f(&mut cell.borrow_mut()))
556    }
557
558    /// `f` of the value, or `None` (and `f` not called) once the value's
559    /// owner was disposed: for cleanups that may run after it.
560    pub fn try_with<R>(&self, f: impl FnOnce(&mut T) -> R) -> Option<R> {
561        self.0.is_live().then(|| self.with(f))
562    }
563
564    /// Replaces the value, returning the old one.
565    #[track_caller]
566    pub fn replace(&self, value: T) -> T {
567        self.with(|v| std::mem::replace(v, value))
568    }
569}
570
571impl<T: Clone + 'static> Stored<T> {
572    /// A copy of the value (reading it subscribes nothing, unlike
573    /// [`Signal::get`]).
574    #[track_caller]
575    pub fn get(&self) -> T {
576        self.with(|v| v.clone())
577    }
578}
579
580/// A value of the current owner that is not reactive: reading it subscribes
581/// nothing, changing it notifies nothing.
582pub fn stored<T: 'static>(value: T) -> Stored<T> {
583    Stored(signal_with(
584        Rc::new(RefCell::new(value)),
585        SignalEquals::Never,
586    ))
587}
588
589/// A value the current owner keeps for a `Copy` handle that is not a
590/// signal ([`super::AnimatedValue`], [`super::ElementRef`]): released with
591/// the owner (with no owner, it lives as long as the graph, as a signal
592/// does). Unlike a signal's, its handle finds it gone afterwards rather
593/// than panicking, and off the engine thread, where no graph is entered.
594pub(crate) struct Kept<T: 'static> {
595    handle: Handle,
596    _t: PhantomData<fn() -> T>,
597}
598
599impl<T> Clone for Kept<T> {
600    fn clone(&self) -> Self {
601        *self
602    }
603}
604
605impl<T> Copy for Kept<T> {}
606
607impl<T> PartialEq for Kept<T> {
608    fn eq(&self, other: &Self) -> bool {
609        self.handle == other.handle
610    }
611}
612
613impl<T: 'static> Kept<T> {
614    /// Keeps `value` in the current owner. The `Rc` is the graph's value
615    /// as it is (no allocation of its own).
616    pub(crate) fn new(value: Rc<T>) -> Self {
617        Self {
618            handle: owned_signal(Some(value as Rc<dyn Any>), Equals::Never),
619            _t: PhantomData,
620        }
621    }
622
623    /// A handle of nothing: always gone.
624    pub(crate) fn gone() -> Self {
625        Self {
626            handle: Handle {
627                id: u32::MAX,
628                generation: 0,
629            },
630            _t: PhantomData,
631        }
632    }
633
634    /// `f` of the graph's value while the owner lives (and a graph is
635    /// entered). `f` must not reach the graph: it runs inside a borrow.
636    fn raw<R>(self, f: impl FnOnce(&Rc<dyn Any>) -> R) -> Option<R> {
637        let graph = CURRENT.with(Cell::get);
638        if graph.is_null() {
639            return None;
640        }
641        // SAFETY: an entered graph lives until its guard drops; the borrow
642        // ends with `f`, which does not reach the graph.
643        let graph = unsafe { &*graph };
644        let Handle { id, generation } = self.handle;
645        if !graph.live(id, generation, u32::MAX) {
646            return None;
647        }
648        graph.value(id).as_ref().map(f)
649    }
650
651    /// `f` of the value while its owner lives (and a graph is entered).
652    /// `f` must not reach the graph: it runs inside a borrow of it.
653    pub(crate) fn with<R>(self, f: impl FnOnce(&T) -> R) -> Option<R> {
654        self.raw(|v| v.downcast_ref::<T>().map(f)).flatten()
655    }
656
657    /// Whether its owner lives (and a graph is entered).
658    pub(crate) fn is_live(self) -> bool {
659        self.raw(|_| ()).is_some()
660    }
661
662    /// The value while its owner lives (and a graph is entered).
663    pub(crate) fn get(self) -> Option<Rc<T>> {
664        self.raw(Rc::clone)?.downcast::<T>().ok()
665    }
666}
667
668fn make_signal<T: 'static>(value: T, equals: Equals<Compare>) -> Signal<T> {
669    Signal {
670        handle: owned_signal(Some(Rc::new(value)), equals),
671        _t: PhantomData,
672    }
673}
674
675/// A signal node of the current owner; under [`DISPOSED`] one disposed at
676/// once, its handle naming nothing.
677fn owned_signal(value: Value, equals: Equals<Compare>) -> Handle {
678    let graph = graph();
679    let id = graph.owned_signal(value, equals);
680    let handle = Handle::of(graph, id);
681    if graph.owner() == DISPOSED {
682        r::dispose(Rust, id);
683    }
684    handle
685}
686
687impl<T: 'static> Signal<T> {
688    /// The value (a clone), subscribing the running computation.
689    #[track_caller]
690    pub fn get(&self) -> T
691    where
692        T: Clone,
693    {
694        self.with(T::clone)
695    }
696
697    /// `f` of the value, subscribing the running computation.
698    #[track_caller]
699    pub fn with<R>(&self, f: impl FnOnce(&T) -> R) -> R {
700        read_value(self.handle.expect("a signal"), true, f)
701    }
702
703    /// The value (a clone), without subscribing.
704    #[track_caller]
705    pub fn get_untracked(&self) -> T
706    where
707        T: Clone,
708    {
709        self.with_untracked(T::clone)
710    }
711
712    /// `f` of the value, without subscribing.
713    #[track_caller]
714    pub fn with_untracked<R>(&self, f: impl FnOnce(&T) -> R) -> R {
715        read_value(self.handle.expect("a signal"), false, f)
716    }
717
718    /// Whether its owner lives: it may be read and written.
719    pub(crate) fn is_live(&self) -> bool {
720        self.handle.live()
721    }
722
723    /// The value, or `None` once the signal's owner was disposed.
724    pub fn try_get(&self) -> Option<T>
725    where
726        T: Clone,
727    {
728        self.handle.live().then(|| self.get())
729    }
730
731    /// Writes `value`: what read the signal runs again, unless it is equal
732    /// to the current value.
733    #[track_caller]
734    pub fn set(&self, value: T) {
735        r::write(Rust, self.handle.expect("a signal"), Some(Rc::new(value)));
736    }
737
738    /// Writes `value`; false (and nothing written) once the signal's owner
739    /// was disposed.
740    pub fn try_set(&self, value: T) -> bool {
741        if !self.handle.live() {
742            return false;
743        }
744        r::write(Rust, self.handle.id, Some(Rc::new(value)));
745        true
746    }
747
748    /// Changes the value in place and writes it: every update notifies.
749    /// The value is cloned only while something else holds it (a reader
750    /// in the middle of `with`).
751    #[track_caller]
752    pub fn update(&self, f: impl FnOnce(&mut T))
753    where
754        T: Clone,
755    {
756        let id = self.handle.expect("a signal");
757        let taken = graph().replace_value(id, None);
758        let shared = taken
759            .and_then(|v| v.downcast::<T>().ok())
760            .expect("a signal holds its type");
761        let mut value = Rc::try_unwrap(shared).unwrap_or_else(|shared| (*shared).clone());
762        f(&mut value);
763        r::write(Rust, id, Some(Rc::new(value)));
764    }
765
766    /// Its node.
767    pub(crate) fn node(&self) -> Node {
768        Node(self.handle)
769    }
770
771    /// A read-only view of the signal.
772    pub fn read_only(&self) -> ReadSignal<T> {
773        ReadSignal {
774            handle: self.handle,
775            _t: PhantomData,
776        }
777    }
778}
779
780/// A signal that can only be read (from [`Signal::read_only`]).
781pub struct ReadSignal<T> {
782    handle: Handle,
783    _t: PhantomData<fn() -> T>,
784}
785
786impl<T> Clone for ReadSignal<T> {
787    fn clone(&self) -> Self {
788        *self
789    }
790}
791
792impl<T> Copy for ReadSignal<T> {}
793
794impl<T> PartialEq for ReadSignal<T> {
795    fn eq(&self, other: &Self) -> bool {
796        self.handle == other.handle
797    }
798}
799
800impl<T> fmt::Debug for ReadSignal<T> {
801    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
802        write!(f, "ReadSignal({})", self.handle.id)
803    }
804}
805
806/// A value computed from others and cached: it runs again only when what it
807/// read changed, and notifies only when its result changed (TS:
808/// `computed(fn)`).
809pub struct Memo<T> {
810    handle: Handle,
811    _t: PhantomData<fn() -> T>,
812}
813
814impl<T> Clone for Memo<T> {
815    fn clone(&self) -> Self {
816        *self
817    }
818}
819
820impl<T> Copy for Memo<T> {}
821
822impl<T> PartialEq for Memo<T> {
823    fn eq(&self, other: &Self) -> bool {
824        self.handle == other.handle
825    }
826}
827
828impl<T> fmt::Debug for Memo<T> {
829    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
830        write!(f, "Memo({})", self.handle.id)
831    }
832}
833
834/// A memo of `f`, owned by the current owner.
835pub fn computed<T: PartialEq + 'static>(f: impl Fn() -> T + 'static) -> Memo<T> {
836    let func: Func = Rc::new(move |_| Some(Rc::new(f()) as Rc<dyn Any>));
837    let id = r::memo(Rust, func, None, Equals::Custom(compare::<T>), false);
838    Memo {
839        handle: Handle::of(graph(), id),
840        _t: PhantomData,
841    }
842}
843
844macro_rules! readable {
845    ($name:ident, $what:literal) => {
846        impl<T: 'static> $name<T> {
847            /// The value (a clone), subscribing the running computation.
848            #[track_caller]
849            pub fn get(&self) -> T
850            where
851                T: Clone,
852            {
853                self.with(T::clone)
854            }
855
856            /// `f` of the value, subscribing the running computation.
857            #[track_caller]
858            pub fn with<R>(&self, f: impl FnOnce(&T) -> R) -> R {
859                read_value(self.handle.expect($what), true, f)
860            }
861
862            /// The value (a clone), without subscribing.
863            #[track_caller]
864            pub fn get_untracked(&self) -> T
865            where
866                T: Clone,
867            {
868                self.with_untracked(T::clone)
869            }
870
871            /// `f` of the value, without subscribing.
872            #[track_caller]
873            pub fn with_untracked<R>(&self, f: impl FnOnce(&T) -> R) -> R {
874                // A memo is brought up to date by a read: read it, untracked.
875                untracked(|| self.with(f))
876            }
877
878            /// The value, or `None` once its owner was disposed.
879            pub fn try_get(&self) -> Option<T>
880            where
881                T: Clone,
882            {
883                self.handle.live().then(|| self.get())
884            }
885
886            /// Its node.
887            pub(crate) fn node(&self) -> Node {
888                Node(self.handle)
889            }
890        }
891    };
892}
893
894readable!(ReadSignal, "a signal");
895readable!(Memo, "a memo");
896
897/// Runs `f` now and again whenever what it read changes, after the
898/// bindings of the change are updated (TS: `effect(fn)`). Owned by the
899/// current owner.
900pub fn effect(f: impl Fn() + 'static) {
901    let func: Func = Rc::new(move |_| {
902        f();
903        None
904    });
905    r::effect(Rust, Kind::UserEffect, func, None);
906}
907
908/// A binding: runs `f` now and again whenever what it read changes, before
909/// user effects.
910pub(crate) fn render_effect(f: impl Fn() + 'static) {
911    let func: Func = Rc::new(move |_| {
912        f();
913        None
914    });
915    r::effect(Rust, Kind::Effect, func, None);
916}
917
918/// Runs `f` before the current owner runs again or is disposed (TS:
919/// `cleanup(fn)`). With no owner it never runs; under an owner disposed
920/// while it ran ([`Owner::scope`]) it runs at once.
921pub fn cleanup(f: impl FnOnce() + 'static) {
922    cleanup_boxed(Box::new(f));
923}
924
925/// [`cleanup`] of a boxed `f` (its non-generic part).
926#[cfg_attr(target_arch = "wasm32", inline(never))]
927fn cleanup_boxed(f: Box<dyn FnOnce()>) {
928    if let Err(f) = graph().on_cleanup(f)
929        && graph().owner() == DISPOSED
930    {
931        r::Host::run_cleanup(Rust, f);
932    }
933}
934
935/// The number of cleanups `owner` holds.
936#[cfg(test)]
937pub(crate) fn cleanup_count(owner: Owner) -> usize {
938    owner
939        .0
940        .filter(|h| h.live())
941        .map_or(0, |h| graph().cleanup_count(h.id))
942}
943
944/// A cleanup [`removable_cleanup`] added, which its maker can take back
945/// once what it undoes ended by itself (a task that finished).
946pub(crate) struct RemovableCleanup {
947    owner: Owner,
948    /// The address of the boxed cleanup in the owner's list, which tells it
949    /// from the others: unique while `pending` holds, as the box lives.
950    key: *const (),
951    pending: Rc<Cell<bool>>,
952}
953
954/// Clears `pending` once the cleanup runs or is dropped unrun.
955struct Pending(Rc<Cell<bool>>);
956
957impl Drop for Pending {
958    fn drop(&mut self) {
959        self.0.set(false);
960    }
961}
962
963/// [`cleanup`] of `f`, which [`RemovableCleanup::remove`] can take back
964/// (`None` when there was no owner to add it to, or it ran at once).
965pub(crate) fn removable_cleanup(f: impl FnOnce() + 'static) -> Option<RemovableCleanup> {
966    let pending = Rc::new(Cell::new(true));
967    let marker = Pending(pending.clone());
968    let f: Box<dyn FnOnce()> = Box::new(move || {
969        // Cleared before `f` runs: the box is freed by now, so what `f`
970        // does (ending the task, whose end removes this cleanup) must not
971        // look for it.
972        drop(marker);
973        f();
974    });
975    let key = (&*f as *const dyn FnOnce()).cast::<()>();
976    let owner = Owner::current();
977    match graph().on_cleanup(f) {
978        Ok(()) => Some(RemovableCleanup {
979            owner,
980            key,
981            pending,
982        }),
983        Err(f) => {
984            if graph().owner() == DISPOSED {
985                r::Host::run_cleanup(Rust, f);
986            }
987            None
988        }
989    }
990}
991
992impl RemovableCleanup {
993    /// Removes the cleanup from its owner unrun; nothing once it ran, its
994    /// owner went, or no graph is entered (the engine going away).
995    pub(crate) fn remove(self) {
996        if !self.pending.get() || CURRENT.with(Cell::get).is_null() || !self.owner.is_live() {
997            return;
998        }
999        let Some(h) = self.owner.0 else { return };
1000        let key = self.key;
1001        let removed = graph().remove_cleanup(h.id, |c| {
1002            std::ptr::eq((&**c as *const dyn FnOnce()).cast::<()>(), key)
1003        });
1004        // Dropped outside the graph's borrow: what it holds may reach it.
1005        drop(removed);
1006    }
1007}
1008
1009/// Runs `f`; its writes notify together at its end (TS: `batch(fn)`).
1010pub fn batch<R>(f: impl FnOnce() -> R) -> R {
1011    erased(f, batch_dyn)
1012}
1013
1014/// [`batch`] of `f` with its type erased: one copy of the graph's part for
1015/// every closure.
1016#[inline(never)]
1017fn batch_dyn(f: &mut dyn FnMut()) {
1018    rethrow(r::batch(Rust, shielded(f)))
1019}
1020
1021/// Runs `f` without subscribing to what it reads (TS: `untracked(fn)`).
1022pub fn untracked<R>(f: impl FnOnce() -> R) -> R {
1023    erased(f, untracked_dyn)
1024}
1025
1026/// [`untracked`] of `f` with its type erased.
1027#[inline(never)]
1028fn untracked_dyn(f: &mut dyn FnMut()) {
1029    rethrow(r::untracked(Rust, shielded(f)))
1030}
1031
1032/// Runs `f` through `run`, which takes it with its type erased, and returns
1033/// its result: the generic part left for each closure is this, the graph's
1034/// part (entering an owner, catching a panic) exists once.
1035#[inline(always)]
1036fn erased<R>(f: impl FnOnce() -> R, run: impl FnOnce(&mut dyn FnMut())) -> R {
1037    let mut f = Some(f);
1038    let mut result = None;
1039    run(&mut || {
1040        if let Some(f) = f.take() {
1041            result = Some(f());
1042        }
1043    });
1044    // `run` runs it once, or goes on with its panic.
1045    result.unwrap_or_else(|| unreachable!("an erased closure did not run"))
1046}
1047
1048/// `f`, made to catch its panic: the graph functions that run app code
1049/// change the graph's state (the owner, the listener, the round of
1050/// updates) around it and restore it when it returns, so a panic must not
1051/// unwind through them ([`rethrow`] goes on once they returned).
1052fn shielded<R>(f: impl FnOnce() -> R) -> impl FnOnce() -> std::thread::Result<R> {
1053    move || std::panic::catch_unwind(AssertUnwindSafe(f))
1054}
1055
1056/// `f`'s result, or its panic, going on now that the graph is consistent.
1057fn rethrow<R>(result: std::thread::Result<R>) -> R {
1058    result.unwrap_or_else(|panic| std::panic::resume_unwind(panic))
1059}
1060
1061/// Provides `value` to what the current owner makes from now on, however
1062/// deep; [`use_context`] finds the nearest of its type.
1063pub fn provide_context<T: Clone + 'static>(value: T) {
1064    let replaced = graph().provide((TypeId::of::<T>(), Rc::new(value) as Rc<dyn Any>));
1065    drop(replaced);
1066}
1067
1068/// The nearest value of type `T` provided above the current owner.
1069pub fn use_context<T: Clone + 'static>() -> Option<T> {
1070    let mut frame = graph().context();
1071    while let Some(f) = frame {
1072        if f.data.0 == TypeId::of::<T>() {
1073            return f.data.1.downcast_ref::<T>().cloned();
1074        }
1075        frame = f.parent.clone();
1076    }
1077    None
1078}
1079
1080/// An owner: what was made under it is disposed with it.
1081#[derive(Clone, Copy, PartialEq, Eq, Hash)]
1082pub struct Owner(Option<Handle>);
1083
1084impl fmt::Debug for Owner {
1085    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1086        match self.0 {
1087            Some(h) => write!(f, "Owner({})", h.id),
1088            None => f.write_str("Owner(none)"),
1089        }
1090    }
1091}
1092
1093impl Owner {
1094    /// No owner: what is made under it lives until it is disposed itself.
1095    pub fn detached() -> Self {
1096        Owner(None)
1097    }
1098
1099    fn of(graph: &r::Graph<Rust>, id: u32) -> Self {
1100        if id == NONE || id == UNOWNED {
1101            Owner(None)
1102        } else if id == DISPOSED {
1103            // A handle of no node: never live.
1104            Owner(Some(Handle { id, generation: 0 }))
1105        } else {
1106            Owner(Some(Handle::of(graph, id)))
1107        }
1108    }
1109
1110    /// The owner of what runs now.
1111    pub fn current() -> Self {
1112        let graph = graph();
1113        Self::of(graph, graph.owner())
1114    }
1115
1116    /// The owner it was made under (none for one made with no owner).
1117    pub(crate) fn parent(&self) -> Option<Owner> {
1118        let h = self.0?;
1119        if !h.live() {
1120            return None;
1121        }
1122        let graph = graph();
1123        let parent = Self::of(graph, graph.parent(h.id));
1124        parent.0.map(|_| parent)
1125    }
1126
1127    /// Whether it is still live (not disposed).
1128    pub fn is_live(&self) -> bool {
1129        self.0.is_some_and(|h| h.live() && !graph().disposed(h.id))
1130    }
1131
1132    /// Runs `f` under this owner, untracked (what it makes is this owner's;
1133    /// once it is disposed, what `f` makes is disposed at once).
1134    pub fn run<R>(&self, f: impl FnOnce() -> R) -> R {
1135        erased(f, |f| self.run_dyn(f))
1136    }
1137
1138    /// [`Self::run`] of `f` with its type erased.
1139    #[inline(never)]
1140    fn run_dyn(&self, f: &mut dyn FnMut()) {
1141        rethrow(r::with_owner(Rust, self.graph_id(), shielded(f)))
1142    }
1143
1144    /// The graph's id of it: [`DISPOSED`] once it is disposed.
1145    fn graph_id(&self) -> u32 {
1146        match self.0 {
1147            Some(h) if self.is_live() => h.id,
1148            Some(_) => DISPOSED,
1149            None => NONE,
1150        }
1151    }
1152
1153    /// The owner of what runs now, or none where no graph is entered.
1154    pub(crate) fn current_or_detached() -> Self {
1155        if CURRENT.with(Cell::get).is_null() {
1156            Self::detached()
1157        } else {
1158            Self::current()
1159        }
1160    }
1161
1162    /// Runs `f` with this owner current, so what it makes is this owner's.
1163    /// Once the owner is disposed, before `f` or while it runs (a listener
1164    /// closing the view it belongs to), what `f` makes from then on is
1165    /// disposed at once: signals and memos panic when used, as disposed ones
1166    /// do, effects never run, cleanups (a task's cancel) run at once, and
1167    /// animated values and element refs do nothing. Unlike [`Self::run`] it
1168    /// is no batch and keeps the listener: writes notify as they happen, as
1169    /// they did before (listeners and tasks run their code this way).
1170    pub(crate) fn scope<R>(&self, f: impl FnOnce() -> R) -> R {
1171        /// Puts the previous owner back, on a panic too.
1172        struct Restore(r::SavedOwner);
1173        impl Drop for Restore {
1174            fn drop(&mut self) {
1175                graph().leave_owner(self.0);
1176            }
1177        }
1178        let _restore = Restore(graph().enter_owner(self.graph_id()));
1179        f()
1180    }
1181
1182    /// Makes this root go with `owner` as well, before what `owner` made
1183    /// (it may still go first on its own). Nothing when either is gone.
1184    pub(crate) fn dispose_with(&self, owner: Owner) {
1185        if !self.is_live() || !owner.is_live() {
1186            return;
1187        }
1188        if let (Some(root), Some(keeper)) = (self.0, owner.0) {
1189            r::dispose_with(Rust, root.id, keeper.id);
1190        }
1191    }
1192
1193    /// Disposes it: what was made under it, its cleanups first.
1194    pub fn dispose(&self) {
1195        if let Some(h) = self.0
1196            && h.live()
1197        {
1198            r::dispose_owner(Rust, h.id);
1199        }
1200    }
1201}
1202
1203/// Runs `f` in a new owner under the current one (it sees its context; the
1204/// current owner does not dispose it): the owner, to dispose, and `f`'s
1205/// result.
1206pub fn create_root<R>(f: impl FnOnce() -> R) -> (Owner, R) {
1207    let mut owner = Owner::detached();
1208    let r = erased(f, |f| owner = create_root_dyn(f));
1209    (owner, r)
1210}
1211
1212/// [`create_root`] of `f` with its type erased.
1213#[inline(never)]
1214fn create_root_dyn(f: &mut dyn FnMut()) -> Owner {
1215    let (id, result) = r::with_root(Rust, shielded(f));
1216    let owner = root_owner(id);
1217    match result {
1218        Ok(()) => owner,
1219        Err(panic) => dispose_and_resume(owner, panic),
1220    }
1221}
1222
1223/// The owner of root `id` ([`create_root`]).
1224#[cfg_attr(target_arch = "wasm32", inline(never))]
1225fn root_owner(id: u32) -> Owner {
1226    Owner::of(graph(), id)
1227}
1228
1229/// Disposes the root `f` of [`create_root`] panicked in (what it made so
1230/// far goes with it) and goes on with the panic.
1231#[cold]
1232#[inline(never)]
1233fn dispose_and_resume(owner: Owner, panic: Box<dyn Any + Send>) -> ! {
1234    owner.dispose();
1235    std::panic::resume_unwind(panic)
1236}
1237
1238/// A value that is set once or bound: what element setters and props take
1239/// ([`IntoReactive`]).
1240pub enum Reactive<T> {
1241    /// A value set once (no binding).
1242    Static(T),
1243    /// A value read in a binding: a signal, a memo or a closure, run again
1244    /// when what it read changes.
1245    Bound(Rc<dyn Fn() -> T>),
1246}
1247
1248impl<T: Clone> Clone for Reactive<T> {
1249    fn clone(&self) -> Self {
1250        match self {
1251            Self::Static(v) => Self::Static(v.clone()),
1252            Self::Bound(f) => Self::Bound(f.clone()),
1253        }
1254    }
1255}
1256
1257impl<T: fmt::Debug> fmt::Debug for Reactive<T> {
1258    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1259        match self {
1260            Self::Static(v) => f.debug_tuple("Static").field(v).finish(),
1261            Self::Bound(_) => f.write_str("Bound"),
1262        }
1263    }
1264}
1265
1266impl<T: Clone> Reactive<T> {
1267    /// The value now (a bound one is read, subscribing the running
1268    /// computation).
1269    pub fn get(&self) -> T {
1270        match self {
1271            Self::Static(v) => v.clone(),
1272            Self::Bound(f) => f(),
1273        }
1274    }
1275}
1276
1277impl<T: 'static> Reactive<T> {
1278    /// This value turned into another by `f` (static stays static).
1279    pub fn map<U: 'static>(self, f: impl Fn(T) -> U + 'static) -> Reactive<U> {
1280        match self {
1281            Self::Static(v) => Reactive::Static(f(v)),
1282            Self::Bound(g) => Reactive::Bound(Rc::new(move || f(g()))),
1283        }
1284    }
1285}
1286
1287/// What can be a [`Reactive`] `T`: a value of a type that becomes a `T`
1288/// (set once), a [`Signal`], [`Memo`] or [`ReadSignal`] of `T`, or a
1289/// closure returning what becomes a `T` (bound).
1290pub trait IntoReactive<T> {
1291    /// As a [`Reactive`].
1292    fn into_reactive(self) -> Reactive<T>;
1293}
1294
1295impl<T> IntoReactive<T> for Reactive<T> {
1296    fn into_reactive(self) -> Reactive<T> {
1297        self
1298    }
1299}
1300
1301impl<T: 'static, U: Into<T>, F: Fn() -> U + 'static> IntoReactive<T> for F {
1302    fn into_reactive(self) -> Reactive<T> {
1303        Reactive::Bound(Rc::new(move || self().into()))
1304    }
1305}
1306
1307macro_rules! bound_handles {
1308    ($($handle:ident),*) => {$(
1309        impl<T: Clone + 'static> IntoReactive<T> for $handle<T> {
1310            fn into_reactive(self) -> Reactive<T> {
1311                Reactive::Bound(Rc::new(move || self.get()))
1312            }
1313        }
1314    )*};
1315}
1316
1317bound_handles!(Signal, Memo, ReadSignal);
1318
1319/// Lets values of the types after the colon be passed as static values
1320/// where a setter or a builder takes `impl IntoReactive<Target>` (closures,
1321/// signals and memos of it are already taken): an app's own types, as
1322/// `nsh_core::static_reactive!(Tone: Tone);`. Each type converts with
1323/// `Target::from`.
1324#[macro_export]
1325macro_rules! static_reactive {
1326    ($target:ty: $($source:ty),* $(,)?) => {$(
1327        impl $crate::element::IntoReactive<$target> for $source {
1328            fn into_reactive(self) -> $crate::element::Reactive<$target> {
1329                $crate::element::Reactive::Static(<$target>::from(self))
1330            }
1331        }
1332    )*};
1333}
1334
1335static_reactive!(bool: bool);
1336static_reactive!(f32: f32);
1337static_reactive!(f64: f64);
1338static_reactive!(u32: u32);
1339static_reactive!(i32: i32);
1340static_reactive!(usize: usize);
1341static_reactive!(u8: u8);
1342static_reactive!(u64: u64);
1343static_reactive!(u128: u128);
1344static_reactive!(i8: i8);
1345static_reactive!(i64: i64);
1346static_reactive!(i128: i128);
1347static_reactive!(isize: isize);
1348static_reactive!((u32, u32): (u32, u32));
1349static_reactive!(String: String);
1350static_reactive!(Vec<String>: Vec<String>);
1351static_reactive!(std::time::Duration: std::time::Duration);
1352
1353impl IntoReactive<String> for &str {
1354    fn into_reactive(self) -> Reactive<String> {
1355        Reactive::Static(self.to_owned())
1356    }
1357}
1358
1359/// As `&str`: what setters that took a `&str` were given (`&url`).
1360impl IntoReactive<String> for &String {
1361    fn into_reactive(self) -> Reactive<String> {
1362        Reactive::Static(self.clone())
1363    }
1364}
1365static_reactive!(super::SharedString: super::SharedString, String, &'static str);
1366
1367/// A string where an optional one goes (`.app_class("text-sm")`).
1368macro_rules! some_shared_string {
1369    ($($source:ty),*) => {$(
1370        impl IntoReactive<Option<super::SharedString>> for $source {
1371            fn into_reactive(self) -> Reactive<Option<super::SharedString>> {
1372                Reactive::Static(Some(self.into()))
1373            }
1374        }
1375    )*};
1376}
1377
1378some_shared_string!(super::SharedString, String, &'static str);
1379
1380impl<T: 'static> IntoReactive<Option<T>> for Option<T> {
1381    fn into_reactive(self) -> Reactive<Option<T>> {
1382        Reactive::Static(self)
1383    }
1384}
1385
1386#[cfg(test)]
1387mod tests;