nsh-core 0.8.0

Platform-independent core: shadow tree, styles, layout and mount instructions.
Documentation
//! A Rust [`Signal`] or [`Memo`] returned to JS: TS gets a read-only
//! `Accessor<T>` (`() => T`) that JS's reactive graph tracks.
//!
//! The two graphs stay apart. The call that returns the signal (a function
//! with `cx`, or an `async` one: both run where Rust's graph is) makes a
//! Rust effect in a root of its own; JS gets a signal of its graph holding
//! the value at the call. Each later change the effect sees is posted to JS
//! (the next JS turn), where it writes that signal, so JS reads it one turn
//! after Rust. The signal's writer does not keep it: once JS lets the
//! accessor go, the next write finds it gone and the effect disposes its
//! root at the change after that. Writing stays Rust's (the module's
//! methods): TS has no `set`.

use std::{
    cell::{Cell, RefCell},
    rc::Rc,
};

use super::{
    JsHost, JsOwned, Memo, PropError, Signal, TsTypes,
    call::ToJs,
    callback::{CallbackHandle, JsCall, ReplyFn},
    class::{ClassDef, Ret},
    reactive::{Owner, create_root, effect},
};

/// What links a Rust value to the JS signal mirroring it.
struct Link<T> {
    /// The value JS has not got yet: the one at the call, then the latest
    /// change before JS took the accessor.
    pending: RefCell<Option<T>>,
    /// What writes the JS signal, once JS has it.
    writer: RefCell<Option<Rc<dyn CallbackHandle>>>,
    /// JS let the accessor go (or never got it): the effect stops.
    gone: Cell<bool>,
    /// The root of the effect.
    owner: RefCell<Option<Owner>>,
}

/// Starts mirroring what `read` reads (tracked) for JS: the call's result,
/// converted when JS receives it. Runs where Rust's graph is (a call with
/// `cx`, a task).
pub(crate) fn bridge<T: Ret + Clone + 'static>(read: impl Fn() -> T + 'static) -> Box<dyn ToJs> {
    let link = Rc::new(Link {
        pending: RefCell::new(None),
        writer: RefCell::new(None),
        gone: Cell::new(false),
        owner: RefCell::new(None),
    });
    let (owner, ()) = create_root(|| {
        let link = link.clone();
        effect(move || {
            if link.gone.get() {
                // Read nothing: it never runs again, its root goes.
                let owner = link.owner.borrow_mut().take();
                if let Some(owner) = owner {
                    owner.dispose();
                }
                return;
            }
            let value = read();
            let writer = link.writer.borrow().clone();
            match writer {
                Some(writer) => {
                    let gone = Rc::downgrade(&link);
                    let reply: ReplyFn = Box::new(move |result| {
                        // `false`: the JS signal was collected.
                        if let Ok(v) = result
                            && v.host().bool(v.raw()) == Some(false)
                            && let Some(link) = gone.upgrade()
                        {
                            link.gone.set(true);
                        }
                    });
                    writer.post(JsCall::new(
                        writer.clone(),
                        value,
                        Some(reply),
                        false,
                        false,
                    ));
                }
                None => *link.pending.borrow_mut() = Some(value),
            }
        });
    });
    *link.owner.borrow_mut() = Some(owner);
    Box::new(Mirror { link })
}

/// A mirrored value on its way to JS ([`bridge`]).
struct Mirror<T> {
    link: Rc<Link<T>>,
}

impl<T> Drop for Mirror<T> {
    fn drop(&mut self) {
        // Never reached JS (its promise went, its conversion failed): the
        // effect stops at the next change.
        if self.link.writer.borrow().is_none() {
            self.link.gone.set(true);
        }
    }
}

impl<T: Ret + 'static> Ret for Mirror<T> {
    fn ts_type(types: &mut TsTypes) -> String {
        accessor_type::<T>(types)
    }

    fn into_js<'a>(self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
        let value = self
            .link
            .pending
            .borrow_mut()
            .take()
            .ok_or_else(|| PropError("the value was handed to JS already".into()))?;
        let initial = value.into_js(host)?.into_raw();
        let (read, write) = host.new_signal(initial)?;
        let read = JsOwned::new(host, read);
        let writer = host.callback(write);
        host.free(write);
        let writer =
            writer.ok_or_else(|| PropError("the signal's writer is no function".into()))?;
        *self.link.writer.borrow_mut() = Some(writer);
        Ok(read)
    }

    fn classes(out: &mut Vec<&'static ClassDef>) {
        T::classes(out);
    }
}

/// `Accessor<T>`, declared next to the module's types.
fn accessor_type<T: Ret>(types: &mut TsTypes) -> String {
    let name = types.declare("Accessor", |_| {
        "/** A value Rust owns, read by calling it (tracked). */\nexport interface Accessor<T> {\n  (): T;\n}".into()
    });
    format!("{name}<{}>", T::ts_type(types))
}

/// Where Rust's graph is not (a synchronous function without `cx`).
#[cold]
fn outside_graph(what: &str) -> PropError {
    PropError(format!(
        "a {what} is returned from a function with `cx` or an `async` one, where Rust's reactive graph runs"
    ))
}

/// A signal for JS: `Accessor<T>`, read-only, tracked by JS's graph
/// (writes go through the module's own functions).
impl<T: Ret + Clone + 'static> Ret for Signal<T> {
    fn ts_type(types: &mut TsTypes) -> String {
        accessor_type::<T>(types)
    }

    fn into_js<'a>(self, _host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
        Err(outside_graph("Signal"))
    }

    fn boxed(self) -> Box<dyn ToJs> {
        bridge(move || self.get())
    }

    fn classes(out: &mut Vec<&'static ClassDef>) {
        T::classes(out);
    }
}

/// A memo for JS, as a [`Signal`]: `Accessor<T>`.
impl<T: Ret + Clone + 'static> Ret for Memo<T> {
    fn ts_type(types: &mut TsTypes) -> String {
        accessor_type::<T>(types)
    }

    fn into_js<'a>(self, _host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
        Err(outside_graph("Memo"))
    }

    fn boxed(self) -> Box<dyn ToJs> {
        bridge(move || self.get())
    }

    fn classes(out: &mut Vec<&'static ClassDef>) {
        T::classes(out);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::element::reactive::{Runtime, signal};

    #[test]
    fn a_mirror_js_never_took_stops_after_the_next_changes() {
        let rt = Runtime::default();
        let _entered = rt.enter();
        let count = signal(1.0f64);
        let before = rt.slots_in_use();
        let mirror = count.boxed();
        assert!(
            rt.slots_in_use() > before,
            "the effect is made with the call"
        );
        drop(mirror);
        // The first change finds it gone and disposes its root.
        count.set(2.0);
        count.set(3.0);
        assert_eq!(rt.slots_in_use(), before, "nothing of the mirror is left");
    }
}