use std::cell::RefCell;
use std::future::Future;
use std::pin::Pin;
use std::rc::Rc;
use hyve::state::{Owner, on_cleanup};
use hyve::{Ctx, Scope};
#[derive(Clone, Debug)]
pub struct View {
scope: Scope,
owner: Owner,
}
thread_local! {
static CURRENT: RefCell<Vec<View>> = const { RefCell::new(Vec::new()) };
static EXECUTOR: RefCell<Option<Rc<dyn Executor>>> = const { RefCell::new(None) };
}
impl View {
pub fn root(scope: Scope) -> View {
let owner = Owner::new();
let s = scope.clone();
owner.with(|| on_cleanup(move || s.dispose()));
View { scope, owner }
}
pub fn child(&self) -> View {
self.child_in(&self.scope)
}
pub fn child_in(&self, parent: &Scope) -> View {
let scope = parent.child();
let owner = Owner::new();
let s = scope.clone();
owner.with(|| on_cleanup(move || s.dispose()));
View { scope, owner }
}
pub fn run<R>(&self, f: impl FnOnce() -> R) -> R {
let _g = Push::new(self.clone());
self.scope.enter(|| self.owner.with(f))
}
pub fn enter<R>(&self, f: impl FnOnce() -> R) -> R {
let _g = Push::new(self.clone());
self.scope.enter(f)
}
pub fn current() -> Option<View> {
CURRENT.with(|c| c.borrow().last().cloned())
}
pub fn scope(&self) -> &Scope {
&self.scope
}
pub fn owner(&self) -> Owner {
self.owner
}
pub fn dispose(&self) {
self.owner.dispose();
}
pub fn is_alive(&self) -> bool {
self.owner.is_alive() && !self.scope.is_disposed()
}
}
struct Push;
impl Push {
fn new(v: View) -> Push {
CURRENT.with(|c| c.borrow_mut().push(v));
Push
}
}
impl Drop for Push {
fn drop(&mut self) {
CURRENT.with(|c| {
c.borrow_mut().pop();
});
}
}
pub fn inject<T: Send + Sync + 'static>() -> Ctx<T> {
let scope = Scope::current().expect("serge: components run inside a view scope");
scope.get::<T>().unwrap_or_else(|| {
panic!(
"serge: no `{}` is provided here; provide it with `.provide(..)` on the app or a feature that encloses this view",
std::any::type_name::<T>()
)
})
}
pub type LocalFuture = Pin<Box<dyn Future<Output = ()>>>;
pub trait Executor {
fn spawn(&self, task: LocalFuture) -> TaskHandle;
}
pub struct TaskHandle(Box<dyn FnOnce()>);
impl TaskHandle {
pub fn new(abort: impl FnOnce() + 'static) -> Self {
TaskHandle(Box::new(abort))
}
pub fn abort(self) {
(self.0)()
}
}
pub fn install_executor(executor: Rc<dyn Executor>) {
EXECUTOR.with(|e| *e.borrow_mut() = Some(executor));
}
pub fn with_executor<R>(executor: Rc<dyn Executor>, f: impl FnOnce() -> R) -> R {
struct Restore(Option<Rc<dyn Executor>>);
impl Drop for Restore {
fn drop(&mut self) {
EXECUTOR.with(|slot| {
slot.replace(self.0.take());
});
}
}
let _restore = Restore(EXECUTOR.with(|slot| slot.replace(Some(executor))));
f()
}
pub fn spawn(future: impl Future<Output = ()> + 'static) {
let view = View::current();
let task: LocalFuture = match &view {
Some(v) => Box::pin(v.scope().clone().scoped(future)),
None => Box::pin(future),
};
let handle = EXECUTOR.with(|e| {
e.borrow()
.clone()
.expect("serge: no executor is installed; run the app (or a test harness) first")
.spawn(task)
});
if let Some(v) = view {
let handle = RefCell::new(Some(handle));
v.owner().with(|| {
on_cleanup(move || {
if let Some(h) = handle.borrow_mut().take() {
h.abort();
}
})
});
}
}
#[cfg(not(target_arch = "wasm32"))]
pub fn runtime() -> &'static tokio::runtime::Runtime {
static RT: std::sync::OnceLock<tokio::runtime::Runtime> = std::sync::OnceLock::new();
RT.get_or_init(|| {
tokio::runtime::Builder::new_multi_thread()
.worker_threads(2)
.thread_name("serge-io")
.enable_all()
.build()
.expect("serge: failed to start the tokio runtime")
})
}
pub async fn sleep(duration: std::time::Duration) {
#[cfg(not(target_arch = "wasm32"))]
{
let timer = {
let _rt = runtime().enter();
tokio::time::sleep(duration)
};
timer.await;
}
#[cfg(target_arch = "wasm32")]
{
let ms = i32::try_from(duration.as_millis()).unwrap_or(i32::MAX);
let p = js_sys::Promise::new(&mut |resolve, _| {
if let Some(w) = web_sys::window() {
let _ = w.set_timeout_with_callback_and_timeout_and_arguments_0(&resolve, ms);
}
});
let _ = wasm_bindgen_futures::JsFuture::from(p).await;
}
}