Skip to main content

serge_core/
view.rs

1//! View scopes: a `hyve` [`Scope`] (provided values, cancellation) paired with
2//! a reactive [`Owner`] (signals, effects). Every mounted component and
3//! reactive region has one; unmounting disposes both, which cancels the
4//! `#[server]` calls and tasks started under it.
5
6use std::cell::RefCell;
7use std::future::Future;
8use std::pin::Pin;
9use std::rc::Rc;
10
11use hyve::state::{Owner, on_cleanup};
12use hyve::{Ctx, Scope};
13
14/// A view scope. Cheap to clone.
15#[derive(Clone, Debug)]
16pub struct View {
17    scope: Scope,
18    owner: Owner,
19}
20
21thread_local! {
22    static CURRENT: RefCell<Vec<View>> = const { RefCell::new(Vec::new()) };
23    static EXECUTOR: RefCell<Option<Rc<dyn Executor>>> = const { RefCell::new(None) };
24}
25
26impl View {
27    /// A root view over `scope` (owned by the current reactive owner).
28    pub fn root(scope: Scope) -> View {
29        let owner = Owner::new();
30        let s = scope.clone();
31        owner.with(|| on_cleanup(move || s.dispose()));
32        View { scope, owner }
33    }
34
35    /// A child view whose owner is a child of the *current* reactive owner
36    /// (inside an effect: disposed before the effect reruns) and whose scope is
37    /// a child of this view's scope.
38    pub fn child(&self) -> View {
39        self.child_in(&self.scope)
40    }
41
42    /// Like [`child`](Self::child) with a scope under `parent` instead (a
43    /// screen under its feature's scope).
44    pub fn child_in(&self, parent: &Scope) -> View {
45        let scope = parent.child();
46        let owner = Owner::new();
47        let s = scope.clone();
48        owner.with(|| on_cleanup(move || s.dispose()));
49        View { scope, owner }
50    }
51
52    /// Runs `f` inside this view: its scope is current (for `Ctx<T>` and
53    /// `#[server]` stubs) and its owner owns what `f` creates.
54    pub fn run<R>(&self, f: impl FnOnce() -> R) -> R {
55        let _g = Push::new(self.clone());
56        self.scope.enter(|| self.owner.with(f))
57    }
58
59    /// Runs `f` with this view's scope current but the reactive owner
60    /// unchanged (effect bodies, which own their own nodes).
61    pub fn enter<R>(&self, f: impl FnOnce() -> R) -> R {
62        let _g = Push::new(self.clone());
63        self.scope.enter(f)
64    }
65
66    /// The innermost view being run on this thread.
67    pub fn current() -> Option<View> {
68        CURRENT.with(|c| c.borrow().last().cloned())
69    }
70
71    /// The view's `hyve` scope.
72    pub fn scope(&self) -> &Scope {
73        &self.scope
74    }
75
76    /// The view's reactive owner.
77    pub fn owner(&self) -> Owner {
78        self.owner
79    }
80
81    /// Disposes the owner (and with it the scope): effects stop, cleanups run,
82    /// the scope's cancellation token fires.
83    pub fn dispose(&self) {
84        self.owner.dispose();
85    }
86
87    /// Whether the view is still mounted.
88    pub fn is_alive(&self) -> bool {
89        self.owner.is_alive() && !self.scope.is_disposed()
90    }
91}
92
93struct Push;
94
95impl Push {
96    fn new(v: View) -> Push {
97        CURRENT.with(|c| c.borrow_mut().push(v));
98        Push
99    }
100}
101
102impl Drop for Push {
103    fn drop(&mut self) {
104        CURRENT.with(|c| {
105            c.borrow_mut().pop();
106        });
107    }
108}
109
110/// The value of type `T` provided to the current view (by `.provide()` on
111/// the app or a feature).
112///
113/// # Panics
114///
115/// Panics with the type's name when nothing provides it — a component that
116/// takes `Ctx<T>` is mounted where `T` was not provided.
117pub fn inject<T: Send + Sync + 'static>() -> Ctx<T> {
118    let scope = Scope::current().expect("serge: components run inside a view scope");
119    scope.get::<T>().unwrap_or_else(|| {
120        panic!(
121            "serge: no `{}` is provided here; provide it with `.provide(..)` on the app or a feature that encloses this view",
122            std::any::type_name::<T>()
123        )
124    })
125}
126
127/// A boxed local future (UI tasks touch thread-local signals, so they are
128/// not `Send`).
129pub type LocalFuture = Pin<Box<dyn Future<Output = ()>>>;
130
131/// Runs UI tasks on the UI thread. Each target installs one
132/// ([`install_executor`]).
133pub trait Executor {
134    /// Starts `task`; the returned handle aborts it.
135    fn spawn(&self, task: LocalFuture) -> TaskHandle;
136}
137
138/// Stops a spawned task (drops its future).
139pub struct TaskHandle(Box<dyn FnOnce()>);
140
141impl TaskHandle {
142    /// A handle that runs `abort` when aborted.
143    pub fn new(abort: impl FnOnce() + 'static) -> Self {
144        TaskHandle(Box::new(abort))
145    }
146
147    /// Aborts the task.
148    pub fn abort(self) {
149        (self.0)()
150    }
151}
152
153/// Installs the UI-thread executor (the target does this at startup).
154pub fn install_executor(executor: Rc<dyn Executor>) {
155    EXECUTOR.with(|e| *e.borrow_mut() = Some(executor));
156}
157
158/// Temporarily installs an executor on this thread, restoring it on return or unwind.
159pub fn with_executor<R>(executor: Rc<dyn Executor>, f: impl FnOnce() -> R) -> R {
160    struct Restore(Option<Rc<dyn Executor>>);
161    impl Drop for Restore {
162        fn drop(&mut self) {
163            EXECUTOR.with(|slot| {
164                slot.replace(self.0.take());
165            });
166        }
167    }
168    let _restore = Restore(EXECUTOR.with(|slot| slot.replace(Some(executor))));
169    f()
170}
171
172/// Runs `future` as a task of the current view: its scope stays current
173/// across `.await`s (so `#[server]` calls find the transport and its
174/// cancellation), and the task is dropped when the view unmounts. This is
175/// what `event => async move { .. }` handlers use.
176///
177/// # Panics
178///
179/// Panics when no executor is installed (outside a running app or test
180/// harness).
181pub fn spawn(future: impl Future<Output = ()> + 'static) {
182    let view = View::current();
183    let task: LocalFuture = match &view {
184        Some(v) => Box::pin(v.scope().clone().scoped(future)),
185        None => Box::pin(future),
186    };
187    let handle = EXECUTOR.with(|e| {
188        e.borrow()
189            .clone()
190            .expect("serge: no executor is installed; run the app (or a test harness) first")
191            .spawn(task)
192    });
193    if let Some(v) = view {
194        let handle = RefCell::new(Some(handle));
195        v.owner().with(|| {
196            on_cleanup(move || {
197                if let Some(h) = handle.borrow_mut().take() {
198                    h.abort();
199                }
200            })
201        });
202    }
203}
204
205/// The process-wide `tokio` runtime of native targets: the UI executor polls
206/// tasks inside its context (so in-process `#[server]` handlers can use I/O
207/// and timers), and remote transports run their I/O on it.
208#[cfg(not(target_arch = "wasm32"))]
209pub fn runtime() -> &'static tokio::runtime::Runtime {
210    static RT: std::sync::OnceLock<tokio::runtime::Runtime> = std::sync::OnceLock::new();
211    RT.get_or_init(|| {
212        tokio::runtime::Builder::new_multi_thread()
213            .worker_threads(2)
214            .thread_name("serge-io")
215            .enable_all()
216            .build()
217            .expect("serge: failed to start the tokio runtime")
218    })
219}
220
221/// Waits `duration` without blocking the UI thread (a timer on serge's
222/// runtime natively, `setTimeout` on the web). For UI tasks: polling,
223/// animations, demo producers.
224pub async fn sleep(duration: std::time::Duration) {
225    #[cfg(not(target_arch = "wasm32"))]
226    {
227        let timer = {
228            let _rt = runtime().enter();
229            tokio::time::sleep(duration)
230        };
231        timer.await;
232    }
233    #[cfg(target_arch = "wasm32")]
234    {
235        let ms = i32::try_from(duration.as_millis()).unwrap_or(i32::MAX);
236        let p = js_sys::Promise::new(&mut |resolve, _| {
237            if let Some(w) = web_sys::window() {
238                let _ = w.set_timeout_with_callback_and_timeout_and_arguments_0(&resolve, ms);
239            }
240        });
241        let _ = wasm_bindgen_futures::JsFuture::from(p).await;
242    }
243}